Wednesday, July 2, 2008

C# Form Keyboard Events - KeyPreview property

If you encounter a situation where you want your C# form to see the key events that happen on its controls, then set the Form.KeyPreview property to true.

We have been working on one of the Symbol devices, namely, WT4090 and there was the need to close the form when the user presses the ESC button. The KeyDown event is triggered correctly as long as the form is without any control, and once a control is added, the KeyDown event stopped being triggered. The solution was to set:

Form.KeyPreview = true

Remarks from MSDN
When this property is set to true, the form will receive all KeyPress, KeyDown, and KeyUp events. After the form's event handlers have completed processing the keystroke, the keystroke is then assigned to the control with focus. For example, if the KeyPreview property is set to true and the currently selected control is a TextBox, after the keystroke is handled by the event handlers of the form the TextBox control will receive the key that was pressed. To handle keyboard events only at the form level and not allow controls to receive keyboard events, set the KeyPressEventArgs.Handled property in your form's KeyPress event handler to true.

You can use this property to process most keystrokes in your application and either handle the keystroke or call the appropriate control to handle the keystroke. For example, when an application uses function keys, you might want to process the keystrokes at the form level rather than writing code for each control that might receive keystroke events.

Source: here

1 comment: said...

i like this post