Reputation: 138
I need a way to get a keypress from an application which has no console or GUI windows. I'm currently polling using GetAsyncKeyState
but this uses unnecessary amounts of CPU time.
Is there a better solution?
Note: Since the application does not have a console, I cannot use getchar
or other such console only functions.
Upvotes: 0
Views: 134
Reputation: 2706
This is a low level hook so it receive events from the kernel. That means you will receive these events even if it's for another application.
#include <stdio.h>
#include <Windows.h>
LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam){
KBDLLHOOKSTRUCT *kbd = (KBDLLHOOKSTRUCT*)lParam;
switch(nCode){
case HC_ACTION:
switch(wParam){
case WM_KEYUP:
case WM_KEYDOWN:
printf("[%i %s %c]\r\n", kbd->time,
wParam == WM_KEYUP ? "Up" : "Down",
kbd->vkCode);
break;
}
break;
}
return CallNextHookEx(0, nCode, wParam, lParam);
}
int main(int argc, char** argv) {
HHOOK kbdHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, 0, 0);
MSG msg;
while (GetMessage(&msg, 0, 0, 0)) {
}
UnhookWindowsHookEx(kbdHook);
return 1;
}
Upvotes: 3