How do I use Num pad short cut keys in a C# Windows form?
So I want to use Ctrl plus a numbe开发者_JAVA技巧r on the num pad for a shortcut to a menu item (or button). But it seems that I am not able to do this with System.Windows.Forms.Shortcut
For example:
this.menuItem3.Shortcut = System.Windows.Forms.Shortcut.Alt7;
Will work for the non-num pad number 7, but not for the num pad 7. I want to specify so that it works on the num pad (I don't care if it works for both).
In the visual designer there is an option in the properties of the menu item that allows this.
The property is ShortcutKeys - the num pad keys are options in the drop down for this.
In the codebehind the designer generates:
this.myToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.NumPad0)));
So you could easily set this yourself from your code if you wanted.
One thing to note is that this only works when the Num Lock is on - I'm pretty sure it is not possible to assign two shortcut keys to the same menu item, so if you want this to work when Num Lock is off as well as on then you will need to handle key press events.
This SO post covers how you can do that. The code from the post is below, with the Insert specified (since this is the non Num Lock key to match NumPad0 from above.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Control | Keys.Insert))
{
// Call your menu item handler here
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
精彩评论