Coder Perfect

What’s the best approach to add keyboard shortcuts to a Windows Forms app?

Problem

In my C# Windows Forms program, I’m seeking for the easiest way to incorporate standard Windows keyboard shortcuts (for example, Ctrl+F, Ctrl+N).

There is a main form in the application that hosts several child forms (one at a time). I’d like to show a custom search form when a user presses Ctrl+F. The search form would be determined by the application’s current open child form.

In the ChildForm KeyDown event, I was thinking of doing something like this:

   if (e.KeyCode == Keys.F && Control.ModifierKeys == Keys.Control)
        // Show search form

This, however, does not function. When you press a key, the event isn’t even triggered. What is the answer?

Asked by Rockcoder

Solution #1

You most likely neglected to set the KeyPreview property of the form to True. The generic answer is to override the ProcessCmdKey() method:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
  if (keyData == (Keys.Control | Keys.F)) {
    MessageBox.Show("What the Ctrl+F?");
    return true;
  }
  return base.ProcessCmdKey(ref msg, keyData);
}

Answered by Hans Passant

Solution #2

In your primary form,

Answered by Almir

Solution #3

The best method is to employ menu mnemonics, which entails creating menu entries in your main form that are assigned the desired keyboard shortcut. Then everything else is taken care of internally, and all you have to do is implement the necessary action in the menu entry’s Click event handler.

Answered by Konrad Rudolph

Solution #4

You could also use the following example:

public class MDIParent : System.Windows.Forms.Form
{
    public bool NextTab()
    {
         // some code
    }

    public bool PreviousTab()
    {
         // some code
    }

    protected override bool ProcessCmdKey(ref Message message, Keys keys)
    {
        switch (keys)
        {
            case Keys.Control | Keys.Tab:
              {
                NextTab();
                return true;
              }
            case Keys.Control | Keys.Shift | Keys.Tab:
              {
                PreviousTab();
                return true;
              }
        }
        return base.ProcessCmdKey(ref message, keys);
    }
}

public class mySecondForm : System.Windows.Forms.Form
{
    // some code...
}

Answered by Shilpa

Solution #5

If you have a menu, updating the ToolStripMenuItem’s ShortcutKeys property should suffice.

If you don’t have one, you can make one and set the visible property to false.

Answered by Corin Blaikie

Post is based on https://stackoverflow.com/questions/400113/best-way-to-implement-keyboard-shortcuts-in-a-windows-forms-application