Paul
Paul

Reputation: 61

Injecting commands by sending keystrokes to a command windows?

I have a command prompt window that runs a web based piece of software. I want to make a program in C# that injects commands into the running command prompt window.

Any pointers?

Thanks, Paul.

Upvotes: 6

Views: 1985

Answers (1)

Ben Schwehn
Ben Schwehn

Reputation: 4565

Quick and dirty method:

use SetFocus to set the focus to the cmd window, then use SendInput to send keystrokes to the cmd window.

You can use this P/Invoke definition to call SendInput from c#:

[DllImport("user32.dll", SetLastError=true)]
static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);

and this one for SetFocus

[DllImport("user32.dll")]
static extern IntPtr SetFocus(IntPtr hWnd);

In order to get the window handle that you required for SetFocus, you can use FindWindow or perhaps get the appropriate cmd process using Process.GetProcessesByName and then use the MainWindowHandle property.

Upvotes: 8

Related Questions