This is the WH_KEYBOARD_LL code which works for me.
#include <Windows.h>
#include <iostream>
using namespace std;
HHOOK _hook;
KBDLLHOOKSTRUCT kbdStruct;
LRESULT __stdcall HookCallback(int nCode, WPARAM wParam, LPARAM lParam) {
cout << nCode;
return CallNextHookEx(_hook, nCode, wParam, lParam);
}
void SetHook() {
if (!(_hook = SetWindowsHookEx(WH_KEYBOARD_LL, HookCallback, NULL, 0))) {
cout << "SetWindowsHookEx Fail";
}
}
void ReleaseHook() {
UnhookWindowsHookEx(_hook);
}
int main() {
SetHook();
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
// do something here
}
return 0;
}
However when I change the SetWindowsHookEx line to if (!(_hook = SetWindowsHookEx(WH_KEYBOARD, HookCallback, NULL, GetCurrentThreadId())))
, it does not work.
I have 3 questions.
How do I get
WH_KEYBOARD
hook to work?If I replace the comment inside the loop, with a
cout
, I don't see any console output. So I am confused, does the body of the loop execute at all?I also read that inside the loop of
GetMessage
, I should add a call toDispatchMessage
. What's the difference betweenDispatchMessage
andCallNextHookEx
? I read the docs about both of them, but couldn't understand.