title | description | ms.date | dev_langs | helpviewer_keywords | ms.assetid | ||||||
---|---|---|---|---|---|---|---|---|---|---|---|
How to: Handle Keyboard Input at the Form Level |
Learn how to handle keyboard input for your Windows Forms at the form level, before messages reach a control. |
03/30/2017 |
|
|
d7f8b390-dc91-42d2-ae0f-2ffa388127ad |
Windows Forms provides the ability to handle keyboard messages at the form level, before the messages reach a control. This topic shows how to accomplish this task.
-
Handle the xref:System.Windows.Forms.Control.KeyPress or xref:System.Windows.Forms.Control.KeyDown event of the startup form, and set the xref:System.Windows.Forms.Form.KeyPreview%2A property of the form to
true
so that keyboard messages are received by the form before they reach any controls on the form. The following code example handles the xref:System.Windows.Forms.Control.KeyPress event by detecting all of the number keys and consuming '1', '4', and '7'.[!code-cppSystem.Windows.Forms.KeyboardInputForm#10] [!code-csharpSystem.Windows.Forms.KeyboardInputForm#10] [!code-vbSystem.Windows.Forms.KeyboardInputForm#10]
The following code example is the entire application for the above example. The application includes a xref:System.Windows.Forms.TextBox along with several other controls that allow you to move focus from the xref:System.Windows.Forms.TextBox. The xref:System.Windows.Forms.Control.KeyPress event of the main xref:System.Windows.Forms.Form consumes '1', '4', and '7', and the xref:System.Windows.Forms.Control.KeyPress event of the xref:System.Windows.Forms.TextBox consumes '2', '5', and '8' while displaying the remaining keys. Compare the xref:System.Windows.Forms.MessageBox output when you press a number key while the xref:System.Windows.Forms.TextBox has focus with the xref:System.Windows.Forms.MessageBox output when you press a number key while focus is on one of the other controls.
[!code-cppSystem.Windows.Forms.KeyBoardInputForm#0] [!code-csharpSystem.Windows.Forms.KeyBoardInputForm#0] [!code-vbSystem.Windows.Forms.KeyBoardInputForm#0]
This example requires:
- References to the System, System.Drawing and System.Windows.Forms assemblies.