I want to use process to print log to richtextbox, but it does not work, I don't know why.
When I use LogWithColor, It will block the program, can't print anything.
When I use richTextBox1.AppendText, or richTextBox1.Text +=, It will print, but will auto close the program, do not print "Finished." And VS2019 Debuger can't get inside, It will cause Exception: System.InvalidOperationException”(In 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.");
}