views:

639

answers:

3

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).

+2  A: 

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.

Tadmas
A: 

You might want to try Control-UpArrow and Control-DownArrow instead of Up and Down. However this doesn't seem to work for all applications, and even on application where it does work, it may depend on where the focus is.

jdigital
A: 

You may wish to use SendInput, as keybd_event as has been superseded. The MSDN Magazine article C++ Q&A: Sending Keystrokes to Any App has a useful example.

Raj