views:

3991

answers:

3

I'm looking for a best way to implement common windows keyboard shortcuts (for example Ctrl-F, Ctrl-N) in my winforms app in C#.

The app has a main form which hosts many child forms (one at a time). What I'd like to do is this: when a user hits Ctrl-F I'd like to show custom search form. The search form would depend on the current open child form in the application.

I was thinking of using something like this in the *ChildForm_KeyDown* event:

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

But this doesn't work. The event doesn't even fire when you press a key. Any ideas?

+1  A: 

The best way is to use menu mnemonics, i.e. to have menu entries in your main form that get assigned the keyboard shortcut you want. Then everything else is handled internally and all you have to do is to implement the appropriate action that gets executed in the Click event handler of that menu entry.

Konrad Rudolph
The problem is that main form doesn't use common windows menus. It uses custom navigation panel that is used to show child forms. The search forms are invoked by click on the ToolStripButton on the child form.
Mr. Brownstone
+16  A: 

You probably forget to set the form's KeyPreview property to True. Overriding the ProcessCmdKey() method is the generic solution:

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);
}
Hans Passant
This seems to be pretty much what I needed. Tnx
Mr. Brownstone
+1  A: 

If you have a menu then:
Changing ShortcutKeys property of the ToolStripMenuItem should do the trick.

If not:
You could create one and set it's visible property to false.

Corin
No I do't have a menu. ToolStripButton for search is actually located on the BindingNavigator control, so adding a menu is probably not an option.
Mr. Brownstone