Writing Low-Level Keyboard Handlers

Visual Basic provides three events that are recognized by forms and by any control that accepts keyboard input. They are described in the following table.

Keyboard event Occurs
KeyPress When a key corresponding to an ASCII character is pressed
KeyDown As any key on the keyboard is pressed
KeyUp As any key on the keyboard is released

Only the object that has the focus can receive a keyboard event. For keyboard events, a form has the focus only if it is active and no control on that form has the focus. This happens only on blank forms and forms on which all controls have been disabled. However, if you set the KeyPreview property on a form to True, the form receives all keyboard events for every control on the form before the control recognizes them. This is extremely useful when you want to perform the same action whenever a certain key is pressed, regardless of which control has the focus at the time.

The KeyDown and KeyUp events provide the lowest level of keyboard response. Use these events to detect a condition that the KeyPress event is unable to detect, for instance:

The keyboard events are not mutually exclusive. When the user presses a key, both the KeyDown and KeyPress events are generated, followed by a KeyUp event when the user releases the key. When the user presses one of the keys that KeyPress does not detect, only a KeyDown event occurs, followed by a KeyUp event.

Before using the KeyUp and KeyDown events, make sure that the KeyPress event isn't sufficient. This event detects keys that correspond to all the standard ASCII characters: letters, digits, and punctuation on a standard keyboard, as well as the ENTER, TAB, and BACKSPACE keys. It's generally easier to write code for the KeyPress event.

You also should consider using shortcut and access keys, which are described in "Menu Basics" in "Forms, Controls, and Menus." Shortcut keys must be attached to menu commands, but they can include function keys (including some function-key – shift-key combinations). You can assign shortcut keys without writing additional code.

Note   The Windows ANSI (American National Standards Institute) character set corresponds to the 256 characters that include the standard Latin alphabet, publishing marks (such as copyright symbol, em dash, ellipsis), as well as many alternate and accented letters. These characters are represented by a unique 1-byte numeric value (0-255). ASCII (American Standard Code for Information Interchange) is essentially a subset (0-127) of the ANSI character set and represents the standard letters, digits, and punctuation on a standard keyboard. The two character sets are often referred to interchangeably.