I'm currently making a program that intercepts keystrokes from a specific keyboard (filtered using HID). Therefore, to find out which keystrokes were sent by a particular device, I used the RawInput technique inspired by this great tutorial:
http://www.codeproject.com/Articles/17123/Using-Raw-Input-from-C-to-handle-multiple-keyboard
Now it works fine: I can get a keystroke and find out which keyboard generated it.
The hard part of my project is to intercept and block keystrokes from this particular keyboard in order to avoid pressing these keys for a focused application (the focused middle foreground window presented by the OS).
Thus, the natural solution was a global low-level hook, for all current threads that have a window handle.
I used and adapted the code on this page to do this:
http://blogs.msdn.com/b/toub/archive/2006/05/03/589423.aspx
I created a new project in a visual studio to avoid interference with my work. After some research, I was able to block keystrokes in all applications by returning the value (-1) to 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 everything together (hook procedure and keypress detection), I create two threads in the final project:
1st : using RawInput to identify and attach each keystroke to a device
2nd : used to connect all windows and block keystrokes.
Topic 1 is designed to send keystrokes to block thread 2, which reads all messages sent to all applications in the window and removes keystrokes from a specific keyboard. I know for sure that these two threads are synchronized.
The problem is that the hook seems to be executed before Rawinput is executed, so I cannot identify the keyboard that sent the keystroke. I have no idea how to do this, possibly to change the type of hook (avoid using a hook with a low keyboard level, but with a keyboard hook of user space level).
Or maybe someone knows a smart way to do what I want?
I know this query is really complex, feel free to ask for details.