Vb.net captures keys pressed on the keyboard on the form rather than the textbox Control
I 've been struggling with how to implement this problem. Today I accidentally discovered the keypriview attribute on the form.
After searching for relevant information, find out that it is used to capture the keys pressed on the keyboard of the form. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Authorization/ydLUx + HLycq1z9bV4rj2uabE3KGjPC9wPg0KPHA + authorization + DQo8cHJlIGNsYXNzPQ = "brush: java;"> Private Sub form_keypress (sender As Object, e As KeyEventArgs) Handles Me. keyDown If e. keyCode = Keys. escape Then Dim messge As New MSG messge. head. text = "about to exit system" messge. msgP. text = "press enter to exit the system. esc returns... "messge. show () End If e. keyCode = Keys. f4 Then Dim messge As New MSG messge. head. text = "F4" messge. msgP. text = "you pressed F4" messge. show () End If e. keyCode = Keys. f5 Then Dim messge As New MSG messge. head. text = "F5" messge. msgP. text = "you pressed F5" messge. show () End If End Sub
This allows you to easily capture all keys on the keyboard.
Esc example:
F4 example
F5 example
Here is another example: handles me. keypress
Private Sub form_keypress (sender As Object, e As KeyPressEventArgs) Handles Me. keyPress If e. keyChar = ChrW (27) Then Dim messge As New MSG messge. head. text = "about to exit system" messge. msgP. text = "press enter to exit the system. esc returns... "messge. show () End If e. keyChar = Chr (115) Then Dim messge As New MSG messge. head. text = "F4" messge. msgP. text = "you pressed F4" messge. show () End If e. keyChar = Chr (116) Then Dim messge As New MSG messge. head. text = "F5" messge. msgP. text = "you pressed F5" messge. show () End If End Sub
However, unfortunately this method cannot capture F1-F12, as well as some special keys such as shift
Of course, handles me. keyup can also be used.