views:

85

answers:

2

I've been working for a while on my Windows Forms project using Visual Studio 2008, and I decided to experiment with keyboard shortcuts. After a bit of reading, I figured I had to just write an event handler and bind it to the form's KeyDown event:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Control && e.Alt && e.KeyCode == Keys.O)
    {
        MessageBox.Show("Ctrl+Alt+O: magic!");
    }
}

I did that the good ol' way of opening the Properties panel of the Visual Studio 2008 designer, then double-clicking on the KeyDown event of my form to generate the Form1_KeyDown event handler. But on testing my application, the form doesn't respond at all to the Ctrl+Alt+O keyboard shortcut. The Visual Studio designer did generate the code to bind the event handler to the form though:

private void InitializeComponent()
{
    // ...

    this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);

    // ...
}

So I tried adding a Console.WriteLine() call to the handler to check that it was being called at all, but no luck on that either.

Also, I tried to set a breakpoint on the event binding call (shown just above) and found that the program reaches that breakpoint just fine. But any breakpoints I set within the method definition itself are never reached.

To make sure I was doing the first few steps correctly, I tried repeating them with:

  • A new form in the same solution.
    Same issue: the form doesn't respond when I press my Ctrl+Alt+O keyboard shortcut and the debugger isn't even stepping into the event handler. Tried this again and it works.

  • A brand new WinForms solution.
    It works perfectly: the message dialog appears (the Console.WriteLine() call also works).

So I'm quite lost here. What's preventing all the forms in this one project from receiving KeyDown events? I'm still relatively new to WinForms and C# in general; as much as I want to figure out on my own what else I could do to debug and solve this problem in my project, I don't know how to go about it at all so I'm turning to SO for tips. If there's anything else I could provide, leave a comment and I'll be happy to update my question.

Thanks in advance!

+4  A: 

Does you form has KeyPreview property set to true? http://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview.aspx

STO
No, so I toggled it and that solved it! Thanks for your answer and the documentation link.
BoltClock
It's a hack, made available to keep VB6 programmers happy. It has order-of-execution problems, override ProcessCmdKey() instead.
Hans Passant
@Hans Passant: could you leave an answer to my question with an example? It'd help for reference.
BoltClock
+1  A: 

Try setting the KeyPreview property on your form to true. This worked for me for registering key presses.

TeeBasins
Yep, that's it! Thanks a lot.
BoltClock