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

I want to capture the ctrl / alt / etc keys and the ups and downs, regardless of which control in my form receives the keyup or keydown event. Since I have about 100 controls in my form, it would be very ugly if I added code for each individual control. How can I accomplish this without doing this?

PS: What is the difference between SetWindowsHook and SetWindowsHookEx ?

+4
source share
1 answer

You need to set the KeyPreview property for each True form. Subsequently, you can catch 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 in front of the control, for example

 Form_KeyDown Control_KeyDown Form_KeyUp Control_KeyUp 

As for SetWindowsHook and SetWindowsHookEx, the first is the original Win16 API, and the latter is a call to Win32 and Win64 API. As far as I know, SetWindowsHook is deprecated and is not in the current MSDN library.

+10
source

All Articles