简体   繁体   中英

KeyDown Event Key Not Work - VB.net

KeyDown event does not work, pressing escape the form does not close

Private Sub DataTable_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
    If e.KeyCode = Keys.Escape Then
        Me.Close()
    End If
End Sub

Well, sure it works, the event is just not very like to fire. Keystrokes raise the KeyDown event on the control with the focus. That will only ever be your form when it has no controls that can get the focus. A fairly unlikely scenario.

If you already have a Button labeled "Cancel" that closes the form then set the form's CancelButton property .

If you don't have such a button then it gets to be pretty unlikely that the user will figure out by himself that the Escape key is useful. He will most likely use the Close button in the upper right corner. You can nevertheless make it work by overriding the ProcessCmdKey() method. Like this:

Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
    If keyData = Keys.Escape Then
        Me.Close()
        Return True
    End If
    Return MyBase.ProcessCmdKey(msg, keyData)
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM