I want to capture ctrl/alt/etc key ups and downs, no matter which control on my form gets the keyup or keydown event. Since I have about 100 controls on my form, it would be really ugly if I were to add code to each individual control. How can I accomplish this without having to do that?
PS: What's the difference between SetWindowsHook
and SetWindowsHookEx
?
You need to set the KeyPreview property of each Form to True. Subsequently, you can catch the keyboard events at the form level, in addition to the individual control level:
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
Debug.Print "Form_KeyDown"
End Sub
Private Sub Form_KeyPress(KeyAscii As Integer)
Debug.Print "Form_KeyPress"
End Sub
Private Sub Form_KeyUp(KeyCode As Integer, Shift As Integer)
Debug.Print "Form_KeyUp"
End Sub
Essentially, the form gets a "preview" of each keyboard event before the control, e.g.
Form_KeyDown
Control_KeyDown
Form_KeyUp
Control_KeyUp
As for SetWindowsHook & SetWindowsHookEx, the former is the original Win16 API call, and the latter is the Win32 and Win64 API call. SetWindowsHook is deprecated, and isn't in the current MSDN library, as far as I know.
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