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 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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With