Simulate key stroke in any application

phadaphunk picture phadaphunk · Dec 28, 2012 · Viewed 11.4k times · Source

How do I simulate a key stroke in a window that is not my C# application ?

Right now i'm using SendKeys.Send() but it does not work. The thing is I have a global keyboard hook so I catch the input directly from the keyboard and SendKeys.Send() is not seen like a real keyboard stroke.

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.

I guess I found part of the problem. This is the event called if a key is pressed :

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}");
   } 
}

I tried it this way to :

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);
   } 
}

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.

[STAThread]
static void Main(string args)
{
  KeyBoardHook.CreateHook();
  KeyBoardHook.KeyPressed += KeyBoardHook_KeyPressed;
  Application.Run();
  KeyBoardHook.Dispose();
} 

if you need the KeyBoardHook class I can post it too.

My guess is that my keyboard hook is catching the low-level keyboard outputs and the SendKeys is just simulating a keystroke so my hook doesn't catch it. Anybody thinks of a work around ?

Answer

Simon Mourier picture Simon Mourier · Dec 28, 2012

I suggest you use this very cool library that masks all the complexity for you, the Windows Input Simulator available here: http://inputsimulator.codeplex.com/

I believe it's based on the Windows' SendInput function.