Handling keyboard shortcuts in your application can sometimes get a bit tricky.  Consider the standard Ctrl+C shortcut, which every application should support as a “Copy” to clipboard command.  When you users type in textboxes in your application’s form, they will expect that Ctrl+C will copy the selected text.  But this feature is not supported by default; you have to explicitly write some code.

The easiest way is to create a “Copy” menu item and specify Ctrl+C in the menu item’s ShortcutKeys property.  Then if the user presses Ctrl+C, the application will automatically “click” the Copy menu item and execute the corresponding code.

But what if your window doesn’t have a menu?  The way keyboard processing works is that whichever control in the form has focus will receive the keyboard events.  But if your form has 20 textboxes, you certainly don’t want to write keyboard event handlers for all 20 controls.

This is where the Form’s KeyPreview property comes in.  When this property is set to true, the active form will receive all KeyPress, KeyDown and KeyUp events.  After the form’s event handlers have completed processing the key event, the event is then passed to the focused control.

For example, to handle the Ctrl+C shortcut, set the form’s KeyPreview property to true, then override the form’s OnKeyDown method:

protected override void OnKeyDown( KeyEventArgs e )
    if (e.KeyCode == Keys.C && Control.ModifierKeys == Keys.Control)
        // perform copy
        e.Handled = true;

Notice how the Handled property is set to true.  This prevents the KeyDown event from being passed on to the focused control.  In our example, this will prevent the computer from beeping because Ctrl+C is not a valid character you can type into a textbox. 

Note that if a form has no visible or enabled controls, it automatically receives all keyboard events.

Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot