Controlling cmd.exe from Winforms

15,451

Solution 1

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).alt text

Solution 2

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.

Solution 3

You don't need to use cmd.exe for this, you can call the commands directly with Process.Start(). If you redirect StandardInput and StandardOutput you can control the process.

I have written an example as a response to another question.

Edit
I don't have a complete example for it, but you could listen to StandardOutput with the Process.OutputDataReceived event if you don't want to wait synchronously. There is an example on the MSDN page.

Share:
15,451
Stefan Steiger
Author by

Stefan Steiger

I'm an avid HTTP-header-reader, github-user and a few more minor things like BusinessIntelligence & Web Software Developer Technologies I work with: Microsoft Reporting- & Analysis Service (2005-2016), ASP.NET, ASP.NET MVC, .NET Core, ADO.NET, JSON, XML, SOAP, Thrift ActiveDirectory, OAuth, MS Federated Login XHTML5, JavaScript (jQuery must die), ReverseAJAX/WebSockets, WebGL, CSS3 C#, .NET/mono, plain old C, and occasional C++ or Java and a little Bash-Scripts, Python and PHP5 I have a rather broad experience with the following relational SQL databases T-SQL PL/PGsql including CLR / extended stored procedures/functions Occasionally, I also work with MySQL/MariaDB Firebird/Interbase Oracle 10g+ SqLite Access I develop Enterprise Web-Applications (.NET 2.0 & 4.5) and interface to systems like LDAP/AD (ActiveDirectory) WebServices (including WCF, SOAP and Thrift) MS Federated Login OAuth DropBox XML & JSON data-stores DWG/SVG imaging for architecture In my spare-time, I'm a Linux-Server-Enthusiast (I have my own Web & DNS server) and reverse-engineer with interest in IDS Systems (IntrusionDetection), WireShark, IDA Pro Advanced, GDB, libPCAP. - Studied Theoretical Physics at the Swiss Federal Institute of Technology (ETHZ).

Updated on June 14, 2022

Comments

  • Stefan Steiger
    Stefan Steiger almost 2 years

    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?