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?
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.
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.
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.
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.
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); }
On your Main form
KeyPreview
to TrueAdd 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(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With