【发布时间】:2021-08-02 01:57:43
【问题描述】:
我想用进程将日志打印到richtextbox,但它不起作用,我不知道为什么。
当我使用 LogWithColor 时,它会阻塞程序,无法打印任何东西。
当我使用richTextBox1.AppendText 或richTextBox1.Text += 时,它会打印,但会自动关闭程序,不要打印“Finished”。而且VS2019 Debuger进不去,会导致Exception: System.InvalidOperationException”(在 System.Windows.Forms.dll 中)
public readonly string ffmpegExe = @"C:\Users\jared\AppData\Local\ffmpeg-4.4-full_build\bin\ffmpeg.exe";
private void OutputHandler(object sendingProcess, DataReceivedEventArgs oneLine)
{
// LogWithColor(richTextBox1, Color.Black, oneLine.Data); // does not work
// richTextBox1.AppendText(oneLine.Data); // it print, but I don’t know why the program will be closed auto
}
private void ErrorHandler(object sendingProcess, DataReceivedEventArgs oneLine)
{
LogWithColor(richTextBox1, Color.Red, oneLine.Data); // does not work
// richTextBox1.AppendText(oneLine.Data); // it print, but I don’t know why the program will be closed auto
}
private delegate void LogWithColorDelegate(RichTextBox rtb, Color color, string text);
private void LogWithColor(RichTextBox rtb, Color color, string text)
{
if (InvokeRequired)
{
if (rtb.IsHandleCreated)
{
rtb.Invoke(new LogWithColorDelegate(LogWithColor),
new object[] { rtb, color, text });
}
}
else
{
rtb.AppendText(Environment.NewLine);
rtb.SelectionColor = color;
rtb.AppendText(text);
// rtb.Text += Environment.NewLine + text; // still does not work
}
}
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(ffmpegExe) || !File.Exists(ffmpegExe))
{
return;
}
LogWithColor(richTextBox1, Color.Black, "Start..."); // work properly.
using (Process p = new Process())
{
// RunCommand(p, ffmpegExe, "-h");
// ffmpeg.exe -h
p.StartInfo.FileName = ffmpegExe;
p.StartInfo.Arguments = "-h";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.EnableRaisingEvents = true; // update for user9938 comment
p.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
p.ErrorDataReceived += new DataReceivedEventHandler(ErrorHandler);
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
}
LogWithColor(richTextBox1, Color.Black, "Finished.");
}
【问题讨论】:
-
How do I get output from a command to appear in a control on a Form in real-time?。请参阅代码中的注释和一些 cmets。 -- 这是否可行取决于您开始的程序如何写入标准输出。尝试不同的选择。 -- 另请参阅与
Process.SynchronizingObject相关的注释。我会避免WaitForExit()。 -
你错过了
EnableRaisingEvents。以下内容可能会有所帮助:stackoverflow.com/questions/68208059/… -
@user9938 对不起,它仍然不起作用。我已经尝试过了。
标签: c# process synchronization