Working Principle of Keyboard Input
Windows Forms handles keyboard input by raising keyboard events in response to Windows messages. Most Windows Forms applications handle keyboard input exclusively by processing keyboard events. However, to implement more advanced keyboard input scenarios (such as intercepting keystrokes before they reach a control), it is essential to understand how keyboard messages work. This topic describes the types of keystroke data that Windows Forms can recognize and outlines how keyboard messages are delivered. For information about keyboard events, see Using Keyboard Events.
Windows Forms identifies keyboard input as virtual key codes represented by the bitwise Keys
enumeration. The Keys
enumeration allows you to combine a series of keystrokes to generate a single value, which corresponds to the values accompanied by the WM_KEYDOWN
and WM_SYSKEYDOWN
Windows messages. Most physical key operations can be detected by handling the KeyDown
or KeyUp
events.
Character keys are a subset of the Keys
enumeration, corresponding to values accompanied by the WM_CHAR
and WM_SYSCHAR
Windows messages. If a keystroke combination produces a character, you can detect it by handling the KeyPress
event. Alternatively, you can use the Keyboard
object exposed by the Visual Basic programming interface to identify and send pressed keys. For more information, see Accessing the Keyboard.
As listed above, three keyboard-related events can occur on a control. The following is the general order in which these events occur:
- The user presses the "a" key. The key is preprocessed and dispatched, and a
KeyDown
event occurs.
- The user holds down the "a" key. The key is preprocessed and dispatched, and a
KeyPress
event occurs.
- This event occurs multiple times if the user holds down the key.
- The user releases the "a" key. The key is preprocessed and dispatched, and a
KeyUp
event occurs.