简体   繁体   中英

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.

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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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