Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PreviewKeyDown not firing

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
like image 383
dotNET Avatar asked Sep 21 '13 07:09

dotNET


1 Answers

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
like image 140
Hans Passant Avatar answered Nov 17 '22 00:11

Hans Passant