Raulp
Raulp

Reputation: 8136

Redirecting Continuous Output from a console to RichtextBox in C# Windows Form

I used this code to log the output from the exe in command prompt to RIchTextBox.

    ProcessStartInfo psi = new ProcessStartInfo("adb.exe", "devices");
    psi.UseShellExecute = false;
    psi.RedirectStandardOutput = true;
    psi.CreateNoWindow = true;
    var proc = Process.Start(psi);

     string s =  proc.StandardOutput.ReadToEnd();

    proc.WaitForExit();

    richTextBox1.Text = s;

This is basically android command to get the list of connected devices. This works fines as it has just two lines. If the output of the exe is continous data how it can be logged efficiently.

I replaced the command with adb.exe logcat but it hangs and nothing comes on the RichTextBox. How can I log this coninous output on the RichetxtBox?

Upvotes: 1

Views: 486

Answers (1)

Caius Jard
Caius Jard

Reputation: 74605

It's because you call ReadToEnd on the output stream; C# will keep reading it and reading it and only finish reading it when the stream closes. At that point your code carries on. Your task is more complex than you realize. To read incrementally you need something like:

        ProcessStartInfo psi = new ProcessStartInfo
        {
            FileName = Properties.Settings.Default.CommandLineFfmpegPath,
            Arguments = string.Format(
                Properties.Settings.Default.CommandLineFfmpegArgs,
                OutputPath
            ),
            WindowStyle = ProcessWindowStyle.Hidden,
            CreateNoWindow = true,
            UseShellExecute = false,
            RedirectStandardOutput = true
        };

        var proc = System.Diagnostics.Process.Start(psi);
        proc.OutputDataReceived += proc_OutputDataReceived;
        proc.ErrorDataReceived += proc_ErrorDataReceived;
        proc.BeginOutputReadLine();

And you need an event handler that will be called every time there is some data (but it will need to make sure it doesn't cause a cross thread violation), something like:

    void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        if (richTextbox1.InvokeRequired)
            richTextbox1.Invoke((MethodInvoker) delegate {this.Text += e.Data;});
        else
            richTextbox1.Text += e.Data;
    }

I'm not sure I'd use something as heavy as a richtextbox for this.. You probably aren't formatting (unless the console output is colored and youre gonna reinterpret the color codes) so a textbox would do fine.

Oh, and you probably don't want to jam your UI thread by WaitForExit either

Upvotes: 3

Related Questions