Alex Rivera | Logout

Controlling cmd.exe from Winforms

Asked 2010-11-05T16:01:47.383
11

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?

Edit
Report

1 Answer

0

This is the perfect answer:

using System;
using System.Windows.Forms;


namespace WindowsConsole
{


    public partial class Form1 : Form
    {
        System.Diagnostics.Process spdTerminal;
        System.IO.StreamWriter swInputStream;


        public delegate void fpTextBoxCallback_t(string strText);
        public fpTextBoxCallback_t fpTextBoxCallback;


        public Form1()
        {
            fpTextBoxCallback = new fpTextBoxCallback_t(AddTextToOutputTextBox);
            InitializeComponent();
        } // End Constructor


        public void AddTextToOutputTextBox(string strText)
        {
            this.txtOutput.AppendText(strText);
        } // End Sub AddTextToOutputTextBox


        private void btnQuit_Click(object sender, EventArgs e)
        {
            swInputStream.WriteLine("exit");
            swInputStream.Close();
            //spdTerminal.WaitForExit();
            spdTerminal.Close();
            spdTerminal.Dispose();
            Application.Exit();
        } // End Sub btnQuit_Click


        private void ConsoleOutputHandler(object sendingProcess, System.Diagnostics.DataReceivedEventArgs outLine)
        {
            if (!String.IsNullOrEmpty(outLine.Data))
            {
                //this.Invoke(new fpTextBoxCallback_t(AddTextToOutputTextBox), Environment.NewLine + outLine.Data);
                if(this.InvokeRequired)
                    this.Invoke(fpTextBoxCallback, Environment.NewLine + outLine.Data);
                else
                    fpTextBoxCallback(Environment.NewLine + outLine.Data);
            } // End if (!String.IsNullOrEmpty(outLine.Data))

        } // End Sub ConsoleOutputHandler


        private void btnExecute_Click(object sender, EventArgs e)
        {
            if (this.spdTerminal.HasExited)
            {
                MessageBox.Show("You idiot, you have terminated the process", "Error");
                return;
            } // End if (this.spdTerminal.HasExited)

     
answered 2010-11-07T16:02:40.620

Your Answer