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?
On a form I have a panel with some buttons. When button1 is clicked
Share
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.