Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Low level keyboard hook & keystrokes from rawinput

Currently, I'm making a program that intercept keystrokes from a specific keyboard (filtered using its HID). So to know which keystrokes have been sent by a specific device, I used the RawInput technic, inspired by this great tutorial:

http://www.codeproject.com/Articles/17123/Using-Raw-Input-from-C-to-handle-multiple-keyboard

Now, it works great: I can get a keystroke and know which keyboard have generated it.

The difficult part of my project is to intercept and block keystrokes from this specific keyboard, to avoid these keystrokes to reach the focused application (focused mean the foreground window brought by the OS).

So the natural solution was a low level global hook, on all current threads that have a window handle.

I used and adapted the code from this page to do that:

http://blogs.msdn.com/b/toub/archive/2006/05/03/589423.aspx

I created a new project in visual studio to avoid putting the mess in my work. After some research, I was able to block keystrokes on all applications, by returning the value (-1) in the callback function:

private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)  
{
//Check if we have a key to pass

if (
    nCode >= 0 && ( 
    (wParam == (IntPtr)WM_KEYDOWN) || (wParam == (IntPtr)WM_KEYUP) ) 
    )
{
    int vkCode = Marshal.ReadInt32(lParam);
    if ((Keys)vkCode == Form1.KeysToIgnore)
    {
        return (IntPtr)(-1);
    }
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}

To put all together (the hook procedure, and the keystroke detection), I create two threads in the final project:

1st : using RawInput to identify and attach each keystroke to a device

2nd : used to hook all windows and block certains keystrokes

Thread 1 is designed to send keystroke to block to the thread 2, that read all messages sent to all window application and trash keystrokes from a specific keyboard. I precise that these two threads are synchronized.

The problem is that the hook seems to be executed before the execution of Rawinput, so I can't identify the keyboard that sent the keystroke. I have no idea how to do that, maybe to change the type of hook (avoid using low level keyboard hook, but using a user-space level keyboard hook).

Or maybe someone know a clever way to do what I want?

I know this request is really complicated, don't hesitate to ask for more details.

like image 635
Louisbob Avatar asked Oct 25 '12 19:10

Louisbob


1 Answers

Ok, Silence Dogood give me a good clue:

The library Interception is perfect for my use. You can find it here:

https://github.com/oblitum/Interception

like image 149
Louisbob Avatar answered Sep 20 '22 04:09

Louisbob