#include <windows.h>
#include <stdio.h>
// Keyboard hook handle
HHOOK keyboardHook;
// Callback function declaration for keyboard events
LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode == HC_ACTION) {
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT) lParam;
if (wParam == WM_KEYDOWN) {
// Here you can handle the key press
printf("Key Pressed: %d\n", p->vkCode);
// Example: Quit if the user presses the 'Q' key
if(p->vkCode == 'Q') {
PostQuitMessage(0);
}
}
}
// return CallNextHookEx(keyboardHook, nCode, wParam, lParam);
}
int main() {
MSG msg;
HINSTANCE hInstance = GetModuleHandle(NULL);
// Set the low-level keyboard hook
keyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, hInstance, 0);
GetMessage(&msg, NULL, 0, 0);
// Remove the keyboard hook when the application exits
UnhookWindowsHookEx(keyboardHook);
return 0;
}
In this code, when I run with GetMessage(&msg, NULL, 0, 0), character codes print to the console. When I get rid of GetMessage(&msg, NULL, 0, 0), it closes the hook right after it sets it and exits the program (i.e. nothing prints to the console). Additionally, when I use Sleep(1000) or Sleep in a while loop, nothing prints to console. So, what is GetMessage actually doing here?
For example, when it receives a message (key press), it calls the callback function? I don't understand how GetMessage connects to the hook and callback function.