I am trying to write a simple global keyboard hook program to redirect some keys. For example, when the program is executed, I press \'a\' on the keyboard, the program can d
Your callback function execute twice because of WM_KEYDOWN
and WM_KEYUP
.
When you down a key of your keyboard, windows calls the callback function with WM_KEYDOWN
message and when you release the key, windows calls the callback function with WM_KEYUP
message. That's why your callback function execute twice.
You should change your switch statement to this:
switch (wParam)
{
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
case WM_KEYUP:
case WM_SYSKEYUP:
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;
if (fEatKeystroke = (p->vkCode == 0x41)) //redirect a to b
{
printf("Hello a\n");
if ( (wParam == WM_KEYDOWN) || (wParam == WM_SYSKEYDOWN) ) // Keydown
{
keybd_event('B', 0, 0, 0);
}
else if ( (wParam == WM_KEYUP) || (wParam == WM_SYSKEYUP) ) // Keyup
{
keybd_event('B', 0, KEYEVENTF_KEYUP, 0);
}
break;
}
break;
}
About your second question, I think you have already got from @Ivan Danilov answer.