Disadvantage of setting Form.KeyPreview = true?

后端 未结 4 877
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 10:59

I wonder what the Form.KeyPreview property actually is good for? Why do it exist and what do I \"risk\" by setting it to true? I guess it must have some negative ef

4条回答
  •  爱一瞬间的悲伤
    2020-12-01 11:06

    Form.KeyPreview is a bit of an anachronism, inherited from the Visual Basic object model for form design. Back in the VB6 days, you needed KeyPreview to be able to implement short-cut keystrokes. That isn't needed anymore in Windows Forms, overriding the ProcessCmdKey() is the better solution:

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
      if (keyData == (Keys.Control | Keys.F)) {
        DoSomething();   // Implement the Ctrl+F short-cut keystroke
        return true;     // This keystroke was handled, don't pass to the control with the focus
      }
      return base.ProcessCmdKey(ref msg, keyData);
    }
    

    But KeyPreview was supported to help the legion of VB6 programmers switch to .NET back in the early 2000's. The point of KeyPreview or ProcessCmdKey() is to allow your UI to respond to shortcut keystrokes. Keyboard messages are normally sent to the control that has the focus. The Windows Forms message loop allows code to have a peek at that message before the control sees it. That's important for short-cut keys, implementing the KeyDown event for every control that might get the focus to detect them is very impractical.

    Setting KeyPreview to True doesn't cause problems. The form's KeyDown event will run, it will only have an affect if it has code that does something with the keystroke. But do beware that it closely follows the VB6 usage, 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. Not a problem with ProcessCmdKey().

提交回复
热议问题