重定向c中richtext框上的进程输出

本文关键字:进程 输出 richtext 重定向 | 更新日期: 2023-09-27 18:28:03

我想从应用程序重定向c#中richtext框上的进程输出。但问题是,过程的输出在很长一段时间后才被显示出来,直到过程完成它的工作。

这是我的代码-

        StringBuilder outputBuilder = new StringBuilder();
        ProcessStartInfo processStartInfo = new ProcessStartInfo();
        processStartInfo.CreateNoWindow = true;
        processStartInfo.RedirectStandardOutput = true;
        processStartInfo.RedirectStandardInput = true;
        processStartInfo.UseShellExecute = false;
        //processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        processStartInfo.WorkingDirectory = strHMIModelAppFolder;
        processStartInfo.FileName = ConfigurationHandlerInstance.GetHMIModelApplication();
        Process process = new Process();
        process.StartInfo = processStartInfo;
        process.EnableRaisingEvents = true;
        process.OutputDataReceived += new DataReceivedEventHandler
        (
            delegate(object objSender, DataReceivedEventArgs eventArgs)
            {
                outputBuilder.Append(eventArgs.Data);
                outputBuilder.Append(Environment.NewLine);
                this.SetText(outputBuilder.ToString());
            }
        );
        process.Exited += new EventHandler(ProcExited);
        process.Start();
        process.BeginOutputReadLine();
        //process.WaitForExit();
        //while (!process.HasExited)
        //{
        //    Application.DoEvents();
        //}
        // use the output
        string output = outputBuilder.ToString();
        this.SetText(output);

重定向c中richtext框上的进程输出

您需要在生成输出时读取输出,如下所示:

proc.Start();
while (!proc.StandardOutput.EndOfStream) {
    string line = proc.StandardOutput.ReadLine();
    outputBuilder.Append(line);
    outputBuilder.Append(Environment.NewLine);
    this.SetText(outputBuilder.ToString());
}