如何为Windows窗体表单设置热键

Riy*_*iya 16 .net c#

我想在我的Windows窗体表单中设置热键.例如,Ctrl+ N表示新表单,Ctrl+ S表示保存.我该怎么做?

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)

  • 哦,对了。我忘记设置`KeyPreview`属性,这种情况是必需的。+1。 (3认同)

Gma*_*man 5

您还可以覆盖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


R1t*_*chY 5

如果您的窗口有菜单,您可以使用以下ShortcutKeys属性System.Windows.Forms.ToolStripMenuItem:

myMenuItem.ShortcutKeys = Keys.Control | Keys.S;
Run Code Online (Sandbox Code Playgroud)

在Visual Studio中,您也可以在菜单项的属性页中进行设置.