mar*_*mnl 44
组
myForm.KeyPreview = true;
Run Code Online (Sandbox Code Playgroud)
为KeyDown事件创建一个处理程序:
myForm.KeyDown += new KeyEventHandler(Form_KeyDown);
Run Code Online (Sandbox Code Playgroud)
处理程序示例:
// 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.
}
}
Run Code Online (Sandbox Code Playgroud)
您还可以覆盖ProcessCmdKey在你的Form派生类型是这样的:
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);
}
Run Code Online (Sandbox Code Playgroud)
我相信它更适合热键。不需要KeyPreview。
如果您的窗口有菜单,您可以使用以下ShortcutKeys属性System.Windows.Forms.ToolStripMenuItem:
myMenuItem.ShortcutKeys = Keys.Control | Keys.S;
Run Code Online (Sandbox Code Playgroud)
在Visual Studio中,您也可以在菜单项的属性页中进行设置.