Question: I want to control cmd.exe from winforms.
I DO NOT mean every command in a single process, with startupinfo, and then stop.
I mean for example start the (My) SQL or GDB command prompt, send command, receive answer, send next command, receive next answer, stop SQL command prompt
exit process.
Basically I want to write a GUI on top of any console application.
I want to have the output from cmd.exe redirected to a textfield, and the input coming from another textfield (on press enter/OK button).
I don't find any samples for this. Is there a way?
There is a nice example on CodeProject
Good luck!
-Edit: I think this is more like it, I created a simple form, 2 textboxes and three buttons. First textbox is for command entry, the second (multiline), displays the result.
The first button executes the command, the second button updates the result (because results are read async)
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
private static StringBuilder cmdOutput = null;
Process cmdProcess;
StreamWriter cmdStreamWriter;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmdOutput = new StringBuilder("");
cmdProcess = new Process();
cmdProcess.StartInfo.FileName = "cmd.exe";
cmdProcess.StartInfo.UseShellExecute = false;
cmdProcess.StartInfo.CreateNoWindow = true;
cmdProcess.StartInfo.RedirectStandardOutput = true;
cmdProcess.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);
cmdProcess.StartInfo.RedirectStandardInput = true;
cmdProcess.Start();
cmdStreamWriter = cmdProcess.StandardInput;
cmdProcess.BeginOutputReadLine();
}
private void btnExecute_Click(object sender, EventArgs e)
{
cmdStreamWriter.WriteLine(textBox2.Text);
}
private void btnQuit_Click(object sender, EventArgs e)
{
cmdStreamWriter.Close();
cmdProcess.WaitForExit();
cmdProcess.Close();
}
private void btnShowOutput_Click(object sender, EventArgs e)
{
textBox1.Text = cmdOutput.ToString();
}
private static void SortOutputHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data))
{
cmdOutput.Append(Environment.NewLine + outLine.Data);
}
}
}
}
In the screenshot you can see that I entered the cd\ command to change directory and the next command executed in this directory (dir).
You do not need interop for this. The .NET Process
class gives you all you need, simply redirect standard input stream and output stream and it is done. You can find lots of examples how to do this on the internet.
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