简体   繁体   中英

Run C# Console application in WinForms Application and Wait till it completes

I have a C# Console application which I am trying to execute from another WinForm application just like batch runner by giving the console application's .exe file like below.

Process.Start("Path of Console application exe to execute")

However I need to wait and handle the output and display the output in WinForm's richtextbox from console application once it has completed the execution. How can I achieve this?

Update

I have changed the code to Start a Process and Read using StandardOutput and BeginOutputReadLine() to Read the output asynchronously, but not able to see output in console window, instead console window is getting closed. Not sure how to solve this.

            p.StartInfo.UseShellExecute = false;
            // p.StartInfo.CreateNoWindow = True
            p.StartInfo.RedirectStandardOutput = true;

            string @out = null;

            p.StartInfo.RedirectStandardError = true;

            p.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
            {
                @out += e.Data;
            });
            p.StartInfo.FileName = currentTest;

            p.Start();

            p.BeginOutputReadLine();

            // string output = p.StandardError.ReadToEnd();
            // p.WaitForExit()

            while (!p.HasExited)
                Application.DoEvents();

            //Console.WriteLine($@"Output \n'{output.Substring(output.Length - 50)}'");
            Console.WriteLine($@"\n Error stream:  {@out}");

            Console.ReadLine();

You need to redirect stdout (and probably stderr ) so that any output comes to you, instead of a console; you may also want to redirect stdin . All of these things are available via ProcessStartInfo , with an example on MSDN . Note that if you want to display updates while the exe is running , you may need a worker thread to read incrementally from StandardOutput and StandardError , rather than ReadToEnd() - which won't return anything at all until the associated output pipe is closed.

However! If the console exe is "yours", it may be simpler to just expose the functionality you want in a library, and invoke it directly in-process. There are times when out-of-process is actively preferred, such as when you need to allow that process to go catastrophically wrong in some scenarios - but usually in-process is preferable, given free rein.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM