Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to implement keyboard shortcuts in a Windows Forms application?

I'm looking for a best way to implement common Windows keyboard shortcuts (for example Ctrl+F, Ctrl+N) in my Windows Forms application in C#.

The application has a main form which hosts many child forms (one at a time). When a user hits Ctrl+F, I'd like to show a 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. What is the solution?

like image 838
Rockcoder Avatar asked Dec 30 '08 12:12

Rockcoder


People also ask

How do you implement keyboard shortcuts?

Begin keyboard shortcuts with CTRL or a function key. Press the TAB key repeatedly until the cursor is in the Press new shortcut key box. Press the combination of keys that you want to assign. For example, press CTRL plus the key that you want to use.

How use function keys for Button in C# Windows form?

Set the button's UseMnemonic property to true and add an ampersand (&) just before the letter in the button's Text property you want to use for the hotkey. The user would press Alt + to activate the hotkey. Show activity on this post. Windows Application and shortcut key are synonyms.

Which keyboard shortcut can be used to get help in most Windows applications?

When you press the Alt key, you will have access to all of the menus in the current application. This means you can perform almost any task with just your keyboard. For example, you can type Alt+F+X to quit an application.

What is the keyboard shortcut to quickly move within your open Windows and applications?

Moving between open windows and applications To move between any open programs on your computer, press and hold the Alt key, then press the Tab key.


2 Answers

You probably forgot 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); } 
like image 126
Hans Passant Avatar answered Sep 21 '22 19:09

Hans Passant


On your Main form

  1. Set KeyPreview to True
  2. Add KeyDown event handler with the following code

    private void MainForm_KeyDown(object sender, KeyEventArgs e) {     if (e.Control && e.KeyCode == Keys.N)     {         SearchForm searchForm = new SearchForm();         searchForm.Show();     } } 
like image 33
Almir Avatar answered Sep 17 '22 19:09

Almir