Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Exploring Secrets of .NET Keystroke Handling

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.




Application Security Testing: An Integral Part of DevOps

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
  • C# 3.0
  • .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.
Element Character class 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 alphanumeric 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 alphanumeric 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 (modifiers) alphanumeric 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 (modifiers) 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 (Shift) alphanumeric An example would be to display <SPAN CLASS="PF">A</SPAN> when a user types Shift+A.
Inter-control Navigation Tab Move focus from one control in your application to the next in a predefined sequence.
Intra-control Navigation Navigational keys:
— Arrow keys
— Home/End
— Page Up/Page Down
Move the cursor appropriately in a TextBox, or move to a different cell in a DataGridView, etc.
Change program state Escape You would typically use Escape to let users close or cancel a dialog box or an ongoing operation.
Miscellaneous Space 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.

Hooking Keystrokes
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.
Method Purpose Override When…

Where Available

Form Form with preview Child
OnPreviewKeyDown Raises the PreviewKeyDown event.       X
ProcessCmdKey Check for keys associated with a command You need custom shortcut handling unachievable with a MenuItem. X X X
IsInputKey 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.     X
ProcessDialogKey Check for navigational keys (e.g. escape, tab, return, arrows, home/end, etc.) You want special input/navigational handling for your child controls X X X
OnKeyDown Raises the KeyDown event.     X X
IsInputChar 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.     X
ProcessDialogChar Check for navigational keys You need special navigational handling to occur on a key press X   X
ProcessMnemonic Check for matching mnemonic on the current control. Writing a control that has special handling of mnemonics X    
OnKeyPress Raises the KeyPress event.     X X
OnKeyUp Raises the KeyUp event.     X X

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 when its KeyPreview 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.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date