我有一个应用程序,它等待用户的命令(如cmd)。当用户按Enter确认其命令时,程序启动名为 work()的方法。此方法启动进程,其输出重定向到richtextbox。我正在使用Invoke实时将输出写入richtextbox。但我的问题是,即使在方法结束后,程序的输出也会显示出来。如何等待输出结束然后用提示写新行? 我欢迎任何建议,并抱歉我的英语。
呼叫方法
if (e.KeyChar == (char)13) //Enter
{
work();
richTextBoxOutput.AppendText(prompt + " ");
}
METHOD WORK()
StringBuilder output = new StringBuilder();
Process proc = new Process();
proc.StartInfo.FileName = command;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.Arguments = arguments;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.WorkingDirectory = workingDirectory;
proc.StartInfo.CreateNoWindow = true;
proc.OutputDataReceived += new DataReceivedEventHandler(
(s, e) =>
{
if (richTextBoxOutput.InvokeRequired)
{
richTextBoxOutput.Invoke(new Action(() => richTextBoxOutput.AppendText(e.Data + "\n")));
}
else
richTextBoxOutput.AppendText(e.Data + "\n");
}
);
proc.ErrorDataReceived += new DataReceivedEventHandler((s, e) => { richTextBoxOutput.AppendText(e.Data + "\n"); });
proc.Start();
proc.BeginOutputReadLine();
this.setTitle("Working ...");
while (!proc.HasExited)
{
Application.DoEvents(); // This keeps your form responsive by processing events
}