Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I capture key ups/downs no matter what control on my form is the target?

Tags:

keypress

hook

vb6

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?

like image 587
TimFoolery Avatar asked Dec 26 '22 21:12

TimFoolery


1 Answers

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.

like image 184
Mark Bertenshaw Avatar answered Apr 06 '23 17:04

Mark Bertenshaw