Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 528
Paul Avatar asked May 13 '11 09:05

Paul


People also ask

How do you give a command in a computer?

You can open the Command Prompt by pressing ⊞ Win + R to open the Run box and typing cmd . Windows 8 users can also press ⊞ Win + X and select Command Prompt from the menu.

How do you type a command window?

Press Win + R to open the Run box, then type "cmd" and hit Enter to open it. Press Win + X (or right-click the Start button) and choose Command Prompt from the menu. Depending on your Windows settings, this may show Windows PowerShell or Windows Terminal instead.

How do I run something from the command line?

Type "start [filename.exe]" into Command Prompt, replacing "filename" with the name of your selected file. Replace "[filename.exe]" with your program's name. This allows you to run your program from the file path.

Is PowerShell same as cmd?

PowerShell is a more advanced version of cmd. It is not only an interface but also a scripting language that is used to carry out administrative tasks more easily. Most of the commands executed on cmd can be run on PowerShell as well.


1 Answers

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.

like image 50
Ben Schwehn Avatar answered Sep 20 '22 01:09

Ben Schwehn