3

I use this code to do something in console :

System.Diagnostics.Process Process = new System.Diagnostics.Process();
Process.StartInfo.FileName = @"MyDir\MyApp.exe";
Process.StartInfo.WorkingDirectory = @"MyDir\MyApp.exe";
Process.Start();
System.Threading.Thread.Sleep(10000);
System.Windows.Forms.SendKeys.SendWait("{ENTER}");
Process.Kill();

It is opening a program then uses SendKeys. It is being run by a user who may click on another program, so it has problems because the focus may be set to another program.

So, how can I send keys specifically to my application?

Michael Bray
  • 14,998
  • 7
  • 42
  • 68
  • 1
    As @PoweredByOrange stated, there are a lot of things that can go wrong with your approach. But...you could use the Process.MainWindowHandle() property and the SetForegroundWindow() API before sending the keys. Also, is ten seconds to allow it to load completely?...or wait for it to "finish" something? – Idle_Mind Jul 05 '13 at 20:42
  • 1
    Three are several questions on this topic already in stackoverflow. Two of them are http://stackoverflow.com/questions/10407769/directly-sending-keystrokes-to-another-process-via-hooking and http://stackoverflow.com/questions/2686865/how-can-i-send-keypresses-to-a-running-process-object – hatchet - done with SOverflow Jul 05 '13 at 20:52

1 Answers1

-1

Call PostMessage using a PInvoke:

[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true)]
static extern bool PostMessage(HandleRef hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

Pass the process' MainWindowHandle as the first arg, 0x0D as the second - see the full list of virtual key codes here and I'm pretty sure you can just pass IntPtr.Zero as the last two arguments.

PostMessage works regardless of what window is currently focused.

aevitas
  • 3,753
  • 2
  • 28
  • 39
  • The second argument is a [message ID](http://msdn.microsoft.com/en-us/library/windows/desktop/ms644927(v=vs.85).aspx#system_defined) and not a virtual key code. Also, third and fourth arguments are message parameters. See [`WM_KEYDOWRN`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms646280(v=vs.85).aspx) and [`WM_KEYUP`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms646281(v=vs.85).aspx). – Nick Hill Jul 05 '13 at 21:39