R – How to simulate key presses to any currently focused window

ckeyboard-hookwinapi

I am trying to change the keys my keyboard sends to applications. I've already created a global hook and can prevent the keys I want, but I want to now send a new key in place. Here's my hook proc:

LRESULT __declspec (dllexport) HookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    int ret;

    if(nCode < 0)
    {
        return CallNextHookEx(hHook, nCode, wParam, lParam);
    }

    kbStruct = (KBDLLHOOKSTRUCT*)lParam;

    printf("\nCaught [%x]", kbStruct->vkCode);

    if(kbStruct->vkCode == VK_OEM_MINUS)
    {
        printf(" - oem minus!");
        keybd_event(VK_DOWN, 72, KEYEVENTF_KEYUP, NULL);
        return -1;
    }
    else if(kbStruct->vkCode == VK_OEM_PLUS)
    {
        printf(" - oem plus!");
        keybd_event(VK_UP, 75, KEYEVENTF_KEYUP, NULL);
        return -1;
    }

    return CallNextHookEx(hHook, nCode, wParam, lParam);
}

I've tried using SendMessage and PostMessage with GetFocus() and GetForegroudWindow(), but can't figure out how to create the LPARAM for WM_KEYUP or WM_KEYDOWN. I also tried keybd_event(), which does simulate the keys (I know because this hook proc catches the simulated key presses), including 5 or 6 different scan codes, but nothing affects my foreground window.

I am basically trying to turn the zoom bar on my ms3200 into a scroll control, so I may even be sending the wrong keys (UP and DOWN).

Best Answer

Calling keybd_event is correct. If all you're doing is a key up, maybe the window processes the key down message instead. You really need to send a key down followed by a key up:

keybd_event(VK_UP, 75, 0, NULL);
keybd_event(VK_UP, 75, KEYEVENTF_KEYUP, NULL);

Or, better yet, send the key down when the OEM key goes down and a key up when the OEM key goes up. You can tell the down/up state by kbStruct->flags & LLKHF_UP.

Related Topic