简体   繁体   English

C# Windows Forms 应用程序热键 - KeyDown 事件不起作用

[英]C# Windows Forms Applications Hotkey - KeyDown event not working

I read a lot of questions about making a hotkey for a Windows Forms Applications and tried the code a lot people said it was working, but for me, somehow not.我阅读了很多关于为 Windows Forms 应用程序制作热键的问题,并尝试了很多人说它有效的代码,但对我来说,不知何故没有。

Code:代码:

void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control && e.KeyCode == Keys.S)   
        {
          timer1.Stop();
            e.SuppressKeyPress = true; 
        }
    }

If you want to create global hotkeys manager for your form to be available for all controls in that form, you need to override the Form.ProcessCmdKey() method that catch all keys for all controls, instead of using the form key down event that works only when the background is focused and which can only happens when ActiveControl is null :如果您想为您的表单创建全局热键管理器以供该表单中的所有控件使用,您需要覆盖捕获所有控件的所有键的Form.ProcessCmdKey()方法,而不是使用有效的表单按键事件只有当背景被聚焦并且只有当ActiveControlnull时才会发生:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
  switch ( keyData )
  {
    case Keys.Control | Keys.S:
      timer1.Stop();
      return true;
  }
  return base.ProcessCmdKey(ref msg, keyData);
}

Thus you can catch any key combination you need and return true if processed.因此,您可以捕获所需的任何组合键并在处理后返回 true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM