保留新进程完成后保留其控制台窗口

问题描述 投票:28回答:4

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

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

这将在进程运行时使窗口保持打开状态,这很棒。但是,我也想保持窗口打开after结束,以查看潜在消息。有办法吗?

c#
4个回答
28
投票

这将打开外壳程序,启动您的可执行文件,并在过程结束时保持外壳程序窗口的打开状态

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

或简单地

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

37
投票

[capture the outputStandardOutput中的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);


1
投票

关于:“ Member Process.Start(ProcessStartInfo)不能通过实例引用进行访问;而是使用类型名称来限定它”

这为我解决了问题。...

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

0
投票

请特别注意开关/ k,因为在许多示例中通常使用/ c。

CMD / K运行命令,然后返回到CMD提示符。

CMD / C运行命令,然后终止

var p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/k yourmainprocess.exe";
p.Start();
p.WaitForExit();
© www.soinside.com 2019 - 2024. All rights reserved.