PreviewKeyDown不触发 [英] PreviewKeyDown not firing
问题描述
无论如何,我的表单都不会触发 PreviewKeyDown
. KeyPreview
属性已设置为 True
.
My form won't fire PreviewKeyDown
no matter what. The KeyPreview
property is already set to True
.
Private Sub frmMain_PreviewKeyDown(sender As Object, e As PreviewKeyDownEventArgs) Handles MyBase.PreviewKeyDown
'Code never hits this line
End Sub
推荐答案
Winforms并没有因为必须提供与.NET出现之前占主导地位的GUI开发工具VB6的某种程度的向后兼容性而感到幸运.KeyPreview是这样的向后兼容属性,VB6也具有该属性.在VB6中,这是实现快捷键的唯一方法,它在引发具有焦点的控件上的KeyDown事件之前,先引发窗体的 KeyDown 事件.不是PreviewKeyDown.
Winforms wasn't exactly blessed with having to provide some degree of backwards-compatibility with VB6, the dominant GUI development tool before .NET came around. KeyPreview is such a back-compat property, VB6 had that property as well. In VB6 it was the only way to implement shortcut keystrokes, it raises the form's KeyDown event before it raises the KeyDown event on the control with the focus. Not PreviewKeyDown.
它还有更多的VB6怪癖,KeyDown不会提高导航键(例如Tab,箭头键以及Enter和Escape)的功能.这就是Winforms特定的PreviewKeyDown事件的全部内容,在执行导航操作之前,您可以对此类键进行嗅探.但是,只有具有焦点的控件才具有任何控件的形式.
It has some more VB6 quirks, KeyDown won't raise for navigation keys like Tab, the arrow keys and Enter and Escape. Which is what the Winforms specific PreviewKeyDown event is all about, you can have a sniff at such a key before it performs the navigation operation. But only on the control that has the focus which will never be the form when it has any controls.
当然最好放弃此向后兼容功能,并使用Winforms特定的键盘处理支持,以减少意外.实施快捷键击的最佳方法是重写窗体的ProcessCmdKey()方法,无论键或窗体的状态如何,它都将无条件运行:
It is certainly best to ditch this back-compat feature and use Winforms specific support for keyboard handling, cuts down on the surprises. The best way to implement shortcut keystrokes is to override the form's ProcessCmdKey() method, it unconditionally runs regardless of the key or the state of the form:
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
If keyData = Keys.F1 Then
'' Show help
''...
Return True
End If
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
这篇关于PreviewKeyDown不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!