If you've ever been frustrated trying to figure out how to intercept or assign specific keystrokes to specific controls, you'll be glad you found this article.
by Michael Sorens
Oct 23, 2008
Page 1 of 5
ew areas in .NET are seemingly as simple yet deceptively challenging as processing keyboard inputs. This situation is exacerbated because neither the MSDN documentation nor any of the excellent .NET support websites provide comprehensive, practical details about handling keystrokes. Enter Keystroke Sandbox, a small application developed just for this article. Keystroke Sandbox shows you graphically what happens when you press a single key or a combination of keys. Furthermore, it lets you customize its environment at runtime to emulate a variety of the most common Windows Forms application patterns, including both enabling/disabling controls to receive or ignore input as well as simulating consuming keystrokes at different stages and using different controls.
This article covers the different types of keyboard interaction that an application may have. You'll see how you can simplify debugging by observing which methods get invoked on which controls when you press a key. The article concludes with a practical guide for implementing a variety of common key-handling scenarios.
What You Need
Visual Studio 2008
.NET Framework: 2.0 or higher
Keystroke/ Program Interactions
Before considering the practical matter of wiring up key handlers in your code, Table 1 shows a handy reference guide to all the typical situations where your programs need to handle keyboard input (although there are certainly other, more abstruse situations where keyboard input would be required).
Table 1. Types of Keyboard Interactions: The table lists all the common types of keyboard/program interaction.
Example or Details
Open a fixed menu (i.e. on a menu bar)
Alt + alphanumeric
Alt+F typically opens the file menu.
Mnemonic on a fixed menu item
The File menu frequently contains an Exit choice, with the underlined key identifying a mnemonic key that activates that choice.
Mnemonic on a context menu item
A mnemonic key defined on any menu item on a control's context menu. Users open the context menu either by right-clicking or by pressing the Menu key on most modern keyboards.
Mnemonic on another control
Alt + alphanumeric
By defining a mnemonic key on a control such as a Button, users can click the button using Alt plus that mnemonic (or just the mnemonic depending on where the focus is)—just as if they had clicked it with the mouse.
Shortcut on a fixed menu item
Shortcut keys are combinations that call a menu item's underlying handler just as if a user had clicked that item. For example, in most applications the Edit menu defines Control+C as a shortcut key for the Copy menu item, Control+V as a shortcut for Paste, and Control+X for Cut.
Modify a mouse click
Use this when you want to distinguish between an unadorned mouse click and a Control click (depressing Control while clicking with the mouse).
Echo a typed character
An example would be to display <SPAN CLASS="PF">A</SPAN> when a user types Shift+A.
Move focus from one control in your application to the next in a predefined sequence.
Move the cursor appropriately in a TextBox, or move to a different cell in a DataGridView, etc.
Change program state
You would typically use Escape to let users close or cancel a dialog box or an ongoing operation.
Typically used as a toggle. For example, you can use the Space key to toggle a checkbox.
Author's Note: In Table 1, the term modifiers in the table refers to any combination of Shift, Alt, and Control. The terms shown in italics surrounded by parentheses in the Character Class column are optional. If you are unsure what the name of a particular key means, Wikipedia's entry on the standard PC keyboard layout is a useful reference.
To customize key handling in your application, you must be aware of the points where you may add hooks into the .NET framework. Table 2 lists the most common key-handling methods that you can override in any control. Note that this table includes both forms and controls, because a System.Windows.Forms.Form derives from Control just like a Button or a Label.
Table 2. Key-Handling Methods: Blue rows indicate methods that fire events. Salmon rows indicate the primary methods to override to alter key-handling behavior.
Form with preview
Raises the PreviewKeyDown event.
Check for keys associated with a command
You need custom shortcut handling unachievable with a MenuItem.
Determine if a key should raise the OnKeyDown event
You want a key that's normally a navigational key to instead generate the OnKeyDown event.
You want special input/navigational handling for your child controls
Raises the KeyDown event.
Determine if a key should raise the OnKeyPress event
You want a key that's normally a navigational key to instead generate the OnKeyPress event.
Check for navigational keys
You need special navigational handling to occur on a key press
Check for matching mnemonic on the current control.
Writing a control that has special handling of mnemonics
Raises the KeyPress event.
Raises the KeyUp event.
Author's Notes: In Table 2:
Methods appear in the order in which they occur in a running program.
The MSDN reference page for each method listed may be accessed from this MSDN page on Control methods.
The "Override When " column stems from jfo's coding blog, an excellent reference on keyboard events.
The final three columns indicate where the methods are available, described next.
Despite the fact that the parent form and its children all derive from the Control class, you might assume that all the methods in Table 2 are available for both the parent form or its children. But the parent form has slightly different behavior, as noted by the three sub-columns under the "Where Available" column in Table 2. Available in this case means that the indicated method will be executed under some conditions if there is an "X" in the column. Those without an "X" will never be executed. The first column (labeled "Form") applies to a form only whenitsKeyPreview property is disabled (False). The "Form w/preview" column applies to the form with its KeyPreview property enabled. The final "Child" column applies to any child control.