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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With