完成后,保持新进程的控制台窗口打开

我目前有一部分代码可以创建一个新的Process并从shell执行它。

Process p = new Process(); ... p.Start(); p.WaitForExit(); 

这样可以在进程运行时保持窗口打开,这很棒。 但是,我还希望在窗口完成保持窗口打开以查看潜在的消息。 有没有办法做到这一点?

这将打开shell,启动可执行文件并在进程结束时保持shell窗口打开

 Process p = new Process(); ProcessStartInfo psi = new ProcessStartInfo(); psi.FileName = "CMD.EXE"; psi.Arguments = "/K yourmainprocess.exe"; p.Start(psi); p.WaitForExit(); 

从StandardOutput和StandardError中 捕获输出更容易,将每个输出存储在StringBuilder中,并在过程完成时使用该结果。

 var sb = new StringBuilder(); Process p = new Process(); // redirect the output p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; // hookup the eventhandlers to capture the data that is received p.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data); p.ErrorDataReceived += (sender, args) => sb.AppendLine(args.Data); // direct start p.StartInfo.UseShellExecute=false; p.Start(); // start our event pumps p.BeginOutputReadLine(); p.BeginErrorReadLine(); // until we are done p.WaitForExit(); // do whatever you need with the content of sb.ToString(); 

您可以在sb.AppendLine语句中添加额外的格式以区分标准输出和错误输出,如下所示: sb.AppendLine("ERR: {0}", args.Data);