簡體   English   中英

新進程完成后保持控制台窗口打開

[英]Keep console window of a new Process open after it finishes

我目前有一部分代碼可以創建一個新的 Process 並從 shell 執行它。

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

這在進程運行時保持窗口打開,這很棒。 但是,我還希望完成保持窗口打開以查看潛在消息。 有沒有辦法做到這一點?

更容易捕獲StandardOutputStandardError 的輸出,將每個輸出存儲在 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);

這將打開外殼,啟動您的可執行文件並在進程結束時保持外殼窗口打開

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();

在開關 /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();

關於:“無法使用實例引用訪問成員 Process.Start(ProcessStartInfo);改為使用類型名稱對其進行限定”

這為我解決了問題......

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM