I would like to set hotkeys in my Windows Forms form. For example, Ctrl + N for a new form and Ctrl + S for save. How would I do th开发者_如何转开发is?
Set
myForm.KeyPreview = true;
Create a handler for the KeyDown event:
myForm.KeyDown += new KeyEventHandler(Form_KeyDown);
Example of handler:
// Hot keys handler
void Form_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.S) // Ctrl-S Save
{
// Do what you want here
e.SuppressKeyPress = true; // Stops other controls on the form receiving event.
}
}
You can also override ProcessCmdKey
in your Form
derived type like this:
protected override bool ProcessCmdKey(ref Message message, Keys keys)
{
switch (keys)
{
case Keys.B | Keys.Control | Keys.Alt | Keys.Shift:
// ... Process Shift+Ctrl+Alt+B ...
return true; // signal that we've processed this key
}
// run base implementation
return base.ProcessCmdKey(ref message, keys);
}
I believe it's more suitable for hotkeys. No KeyPreview
needed.
If your window has a menu, you can use the ShortcutKeys
property of System.Windows.Forms.ToolStripMenuItem
:
myMenuItem.ShortcutKeys = Keys.Control | Keys.S;
In Visual Studio, you can set it in the property page of the menu item, too.
I'd like a KeyDown
event for the Form and some code like this:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == (Keys.Control | Keys.N))
{
CreateNew();
}
}
If you are trying to link them to menu items in your application, then you don't need any code. On the menu item, you can simply setup the shortcut key property and it will run the same event that you have configured for your menu item click.
I thought I'd put an update here since the newest answer is 5 years old. Specifically addressing the question portion regarding Menu hotkeys, you can manipulate the properties of your MenuStrip.MenuItem
object, by setting the ShortcutKeys
property. In Visual Studio you can do this in the form design window by opening the properties of your MenuStrip
object. Once scrolled down to the the ShortcutKeys
property, you can use VS interface to set your hot keys.
If you want a MenuStrip
to underline a menu item, prefix the ampersand (&) char to the char of the desired hotkey. So for example if you want the "x" of Exit to be underlined, the property setting should be E&xit
.
These property manipulations should yield a result similar to this*:
*Note: To display the shortcut key "Ctrl+N" change ShowShortcutKeys
property to true
.
You can set it using a hidden menu too, if you want. Just set the property of menu.visible = false;
First, you need to handle the KeyDown event, and then you can start watching out for your modifiers:
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (Control.ModifierKeys == Keys.Control && e.KeyCode == Keys.S)
{
//Do whatever
}
}
Of course, you need to make sure your form subscribes to the KeyDown event.
精彩评论