Reply to thread

That article doesn't take advantage of the new .NET 2.0 features in System.Diagnostics.Process. I've just completed a project involving this sort of stuff, so here's some code:


[code]

System.Diagnostics.Process newProcess;


private void StartSomething()

{

            //build processstartinfo object

            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();

            psi.RedirectStandardOutput = true;

            psi.UseShellExecute = false;

            psi.EnableRaisingEvents = true;


            psi.FileName = <replace with filename here>;


            newProcess = new System.Diagnostics.Process();

            newProcess.StartInfo = psi;


            newProcess.Start();


            newProcess.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(newProcessOutputHandler);

            newProcess.BeginOutputReadLine();

}


        private void newProcessOutputHandler(object sender, System.Diagnostics.DataReceivedEventArgs e)

        {

            //do stuff here. Use e.Data to get the outputted line

        }


//to determine if something has exited, use newProcess.HasExited, or listen in on the Exited event of the newProcess object

[/code]


Now I assume that you want to do something useful with the outputted lines, something like display them in a text box. Note that the eventhandler runs in a different thread to the UI thread, hence in order to do something to the UI, you need to use delegates/callbacks. Here's some more code (from MSDN) to do that:


[code]

        delegate void WriteConsoleOutputCallback(string output);


        private void WriteToConsoleOutputBox(string text)

        {

            // InvokeRequired required compares the thread ID of the

            // calling thread to the thread ID of the creating thread.

            // If these threads are different, it returns true.

            if (this.txtConsoleOutput.InvokeRequired)

            {

                WriteConsoleOutputCallback callBack = new WriteConsoleOutputCallback(WriteToConsoleOutputBox);

                this.Invoke(callBack, new object[] { text });

            }

            else

            {

                txtConsoleOutput.Text += Environment.NewLine + text;

                txtConsoleOutput.SelectionStart = txtConsoleOutput.Text.Length;

                txtConsoleOutput.ScrollToCaret();

            }

        }

[/code]


This code assumes you have a textbox called txtConsoleOutput and it has the multiline property enabled.


To use the above code, just change the event handler in the initial code to:

[code]

        private void newProcessOutputHandler(object sender, System.Diagnostics.DataReceivedEventArgs e)

        {

            WriteToConsoleOutputBox(e.Data);

        }

[/code]


HTH


Sam


Top Bottom