Trying to install a global keyboard hook.
The call to SetWindowsHookEx is successful as it returns a valid hook handle, however, the Keyboard Callback function never gets called whenever a key is pressed, not even in the current process ! No error is ever produced, just nothing happens !
The same code works well in x32 bit platforms.
Also, it is worth noting that a low level mouse hook (WH_MOUSE_LL) installed in the same fashion works fine in x64bit ... Only the WH_KEYBOARD_LL is the one that doesn't work !
What is going on ? Is this a known bug or something ?
The call to SetWindowsHookEx is successful as it returns a valid hook handle, however, the Keyboard Callback function never gets called whenever a key is pressed, not even in the current process ! No error is ever produced, just nothing happens !
The same code works well in x32 bit platforms.
Also, it is worth noting that a low level mouse hook (WH_MOUSE_LL) installed in the same fashion works fine in x64bit ... Only the WH_KEYBOARD_LL is the one that doesn't work !
What is going on ? Is this a known bug or something ?
Code:
Option Explicit
Type KBDLLHOOKSTRUCT
vkCode As Long
scanCode As Long
flags As Long
time As Long
dwExtraInfo As Long
End Type
Declare PtrSafe Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" (ByVal idHook As Long, ByVal lpfn As LongPtr, ByVal hmod As LongPtr, ByVal dwThreadId As Long) As LongPtr
Declare PtrSafe Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As LongPtr) As Long
Declare PtrSafe Function CallNextHookEx Lib "user32" (ByVal hHook As LongPtr, ByVal ncode As Long, ByVal wParam As LongPtr, lParam As Any) As LongPtr
Declare PtrSafe Function GetModuleHandle Lib "kernel32" Alias "GetModuleHandleA" (ByVal lpModuleName As String) As LongPtr
Dim KeyboardHandle As LongLong
Sub HookKeyboard()
Const WH_KEYBOARD_LL = 13&
If KeyboardHandle = 0 Then
KeyboardHandle = SetWindowsHookEx(WH_KEYBOARD_LL, AddressOf KeyboardCallback, GetModuleHandle(vbNullString), 0&)
Debug.Print "hHook = " & KeyboardHandle & _
vbCrLf & "Err.LastDllError = " & Err.LastDllError ' <== Success --Valid hook handle
End If
End Sub
Sub UnhookKeyboard()
If KeyboardHandle <> 0 Then
UnhookWindowsHookEx KeyboardHandle
KeyboardHandle = 0
End If
End Sub
Private Function KeyboardCallback(ByVal Code As Long, ByVal wParam As LongLong, lParam As KBDLLHOOKSTRUCT) As LongLong
Const HC_ACTION = 0&
If Code = HC_ACTION Then
Debug.Print "This never gets called !!!"
End If
KeyboardCallback = CallNextHookEx(ByVal KeyboardHandle, ByVal Code, ByVal wParam, ByVal lParam)
End Function