Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raw Input an alternative keyboard hook?

Quick question --

I was reading about keyboard hooks and one suggested using Raw Input to do this, yet I havn't found any example of it. For example I am using

RAWINPUTDEVICE rid[1];
rid[0].usUsagePage = 0x01;
rid[0].usUsage = 0x06;
rid[0].hwndTarget = hWnd;
rid[0].dwFlags = 0;
RegisterRawInputDevices(rid, 1, sizeof(rid[0]));

And catchign WM_INPUT fine in the applications own window, but not outside the application. Is this possible outside the application or do you have to use WH_KEYBOARD or WH_KEYBOARD_LL? MSDN didn't make it clear if Raw Input could be made globally.

EDIT: I know about Hooks but I want to know if you can do it with Raw input too!

Cheers

like image 917
KaiserJohaan Avatar asked Jan 18 '11 23:01

KaiserJohaan


2 Answers

Looking at the MSDN documentation for that stuff, there is a flag called RIDEV_INPUTSINK which is described as: "If set, this enables the caller to receive the input even when the caller is not in the foreground."

I haven't messed with that myself, but it sounds like it could be useful for getting input from beyond the application's window.

like image 82
TheUndeadFish Avatar answered Sep 19 '22 05:09

TheUndeadFish


This is how I initialize RAW INPUT to globally intercept mouse and keyboard events. The great advantage compared to hooks is you don't need a DLL. You treats the raw input events in the window procedure with WM_INPUT. For further informations : RAW INPUT

#include <Windows.h>

const USHORT HID_MOUSE    = 2;
const USHORT HID_KEYBOARD = 6;

bool HID_RegisterDevice(HWND hTarget, USHORT usage)
{
    RAWINPUTDEVICE hid;
    hid.usUsagePage = 1;
    hid.usUsage = usage;
    hid.dwFlags = RIDEV_DEVNOTIFY | RIDEV_INPUTSINK;
    hid.hwndTarget = hTarget;

    return !!RegisterRawInputDevices(&hid, 1, sizeof(RAWINPUTDEVICE));
}

void HID_UnregisterDevice(USHORT usage)
{
    RAWINPUTDEVICE hid;
    hid.usUsagePage = 1;
    hid.usUsage = usage;
    hid.dwFlags = RIDEV_REMOVE;
    hid.hwndTarget = NULL;

    RegisterRawInputDevices(&hid, 1, sizeof(RAWINPUTDEVICE));
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR cmd_line, int cmd_show)
{
    WNDCLASS wc;
    ...
    RegisterClass(&wc);

    HWND hwnd = CreateWindow(...);
    ...

    HID_RegisterDevice(hwnd, HID_KEYBOARD);
    HID_RegisterDevice(hwnd, HID_MOUSE);

    MSG msg;
    while(GetMessage(&msg, NULL, 0, 0))
    {
        ...
    }

    HID_UnregisterDevice(HID_MOUSE);
    HID_UnregisterDevice(HID_KEYBOARD);

    return (int) msg.wParam;
}
like image 43
nikau6 Avatar answered Sep 21 '22 05:09

nikau6