title: Simulate key stroke in any application
body: <p>How do I simulate a key stroke in a window that is not my C# application ?</p>
  
  <p>Right now i'm using <code>SendKeys.Send()</code> but it does not work. The thing is I have a global keyboard hook so I catch the input directly from the keyboard and <code>SendKeys.Send()</code> is not seen like a real keyboard stroke.</p>
  
  <p>The best would be to simulate a real keystroke this way, no matter what is the application i'm in, my program will catch it as if someone pressed a key.</p>
  
  <p>I guess I found part of the problem. This is the event called if a key is pressed :</p>
  
  <pre><code>static void KeyBoardHook_KeyPressed(object sender, KeyPressedEventArgs e)
  {
     // Writes the pressed key in the console (it works)
     Console.WriteLine(e.KeyCode.ToString());
  
     // Check if pressed key is Up Arrow (it works and enters the condition)
     if(e.KeyCode == Keys.Up)
     {
       // Send the key again. (does not work)
       SendKeys.Send("{UP}");
     } 
  }
  </code></pre>
  
  <p>I tried it this way to :</p>
  
  <pre><code>static void KeyBoardHook_KeyPressed(object sender, KeyPressedEventArgs e)
  {
     // Writes the pressed key in the console (it works)
     Console.WriteLine(e.KeyCode.ToString());
  
     // Check if pressed key is Up Arrow (it works and enters the condition)
     if(e.KeyCode == Keys.Up)
     {
       // Send the key again. (does not work)
       PostMessage(proc.MainWindowHandle,WM_KEYDOWN, VK_UP,0);
     } 
  }
  </code></pre>
  
  <p>but it does not work either. The thing is since I send the key inside my event, will it call itself because a key has been pressed ? In case someone needs it, the code above. </p>
  
  <pre><code>[STAThread]
  static void Main(string args)
  {
    KeyBoardHook.CreateHook();
    KeyBoardHook.KeyPressed += KeyBoardHook_KeyPressed;
    Application.Run();
    KeyBoardHook.Dispose();
  } 
  </code></pre>
  
  <p>if you need the <code>KeyBoardHook</code> class I can post it too.</p>
  
  <p>My guess is that my keyboard hook is catching the low-level keyboard outputs and the <code>SendKeys</code> is just simulating a keystroke so my hook doesn't catch it. Anybody thinks of a work around ?</p>