alex555
alex555

Reputation: 1786

KeyDown not firing for Up, Down, Left and Right

On a form I have a panel with some buttons. When button1 is clicked I replace the panel with a new UserControl which has a label (e.g. this.Controls.Clear(), this.Controls.Add(UserControl1)). Except the label on my userControl has a KeyDown handler. It works fine, the event fires, but not for keys Up, Down, Left and Right. Can anybody explain why there is a difference between these keys? What decides whether the event is fired or not?

Upvotes: 0

Views: 2365

Answers (4)

Hans Passant
Hans Passant

Reputation: 942348

Two basic reasons. First the mysterious one: a Label control cannot receive the focus so can't see keystrokes. The reason its KeyDown event is hidden in the designer. Not so sure why you see any keystrokes at all. The more common reason is that the cursor and TAB keys are used for navigation, moving the focus from one control to another. Which is done before the key is passed to the control. You'd have to override the control so you can override its IsInputKey() method. But more practically you'd override the UserControl's ProcessCmdKey() instead to solve both issues.

Also note that you've got a nasty handle leak in your program. Never call Controls.Clear() without also calling the Dispose() method on the controls you remove. Unless you intended to reuse them later, not so common. It is a nasty kind of leak that the garbage collector doesn't solve and ultimately crashes your program after first making it slow and unwieldy.

Upvotes: 6

Munawar
Munawar

Reputation: 2587

To handle arrow keys you may either set the Form's KeyPreview property to true and then handle them at form level instead specific control level. I have done so and it works perfect!

In case, above does not work for you then consider ProcessCmdKey something like this:

 protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData) 
{

       if(KeyData == Keys.Right)
       {
        //Move Right
         return true;
         }
        else
        {
         return base.ProcessCmdKey(msg, keyData);
        }

 }

Upvotes: 0

Youenn Bouglouan
Youenn Bouglouan

Reputation: 56

You should override method ProcessCmdKey instead. Arrow keys are not processed the same way as other standard keys. Another solution would be this one: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown.aspx suggested by Microsoft.

Upvotes: 1

Dave New
Dave New

Reputation: 40092

According to MSDN:

This event supports the .NET Framework infrastructure and is not intended to be used directly from your code.

Occurs when the user presses a key while the label has focus.

Edit: There doesn't seem to be an alternative event for this. From what I've read, arrows keys should definitely be detected. Please supply some code.

Upvotes: 1

Related Questions