title: Low level keyboard hook & keystrokes from rawinput
body: <p>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:</p>
  
  <p><a href="http://www.codeproject.com/Articles/17123/Using-Raw-Input-from-C-to-handle-multiple-keyboard" rel="nofollow">http://www.codeproject.com/Articles/17123/Using-Raw-Input-from-C-to-handle-multiple-keyboard</a></p>
  
  <p>Now, it works great: I can get a keystroke and know which keyboard have generated it. </p>
  
  <p>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).</p>
  
  <p>So the natural solution was a low level global hook, on all current threads that have a window handle.</p>
  
  <p>I used and adapted the code from this page to do that:</p>
  
  <p><a href="http://blogs.msdn.com/b/toub/archive/2006/05/03/589423.aspx" rel="nofollow">http://blogs.msdn.com/b/toub/archive/2006/05/03/589423.aspx</a></p>
  
  <p>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:</p>
  
  <pre><code>private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)  
  {
  //Check if we have a key to pass
  
  if (
      nCode &gt;= 0 &amp;&amp; ( 
      (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);
  }
  </code></pre>
  
  <p>To put all together (the hook procedure, and the keystroke detection), I create two threads in the final project:</p>
  
  <p><strong>1st</strong> : using RawInput to identify and attach each keystroke to a device</p>
  
  <p><strong>2nd</strong> : used to hook all windows and block certains keystrokes</p>
  
  <p>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.</p>
  
  <p>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).</p>
  
  <p>Or maybe someone know a clever way to do what I want?</p>
  
  <p>I know this request is really complicated, don't hesitate to ask for more details.</p>