Forms not responding to KeyDown events

前端 未结 3 1314
长发绾君心
长发绾君心 2020-11-29 04:55

I\'ve been working for a while on my Windows Forms project, and I decided to experiment with keyboard shortcuts. After a bit of reading, I figured I had to just write an eve

相关标签:
3条回答
  • 2020-11-29 05:25

    The most common piece of advice for this problem on StackOverflow and the MSDN1, 2 (including the accepted answer here) is quick and easy:

    KeyDown events are triggered on a Form as long as its KeyPreview property is set to true

    That's adequate for most purposes, but it's risky for two reasons:

    1. KeyDown handlers do not see all keys. Specifically, "you can't see the kind of keystrokes that are used for navigation. Like the cursor keys and Tab, Escape and Enter for a dialog."

    2. There are a few different ways to intercept key events, and they all happen in sequence. KeyDown is handled last. Hence, KeyPreview isn't much of a preview, and the event could be silenced at a few stops on the way.

    (Credit to @HansPassant for those points.)

    Instead, override ProcessCmdKey in your Form:

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
        if (keyData == Keys.Up)
        {
            // Handle key at form level.
            // Do not send event to focused control by returning true.
            return true;
        }
      return base.ProcessCmdKey(ref msg, keyData);
    }
    

    That way, all keys are visible to the method, and the method is first in line to see the event.

    Note that you still have control over whether or not focused controls see the KeyDown event. Just return true to block the subsequent KeyDown event, rather than setting KeyPressEventArgs.Handled to true as you would in a KeyDown event handler. Here is an article with more details.

    0 讨论(0)
  • 2020-11-29 05:32

    Does your form have KeyPreview property set to true?

    Form.KeyPreview Property

    Gets or sets a value indicating whether the form will receive key events before the event is passed to the control that has focus.

    http://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview.aspx

    0 讨论(0)
  • 2020-11-29 05:44

    Try setting the KeyPreview property on your form to true. This worked for me for registering key presses.

    0 讨论(0)
提交回复
热议问题