控制台输出到文本框

时间:2014-10-23 12:59:58

标签: c# string multithreading console

我一直试图从以下内容获取控制台输出

private void List_Adapter()
    {
        using (Process tshark = new Process())
        {
            tshark.StartInfo.FileName = ConfigurationManager.AppSettings["fileLocation"];
            tshark.StartInfo.Arguments = "-D";
            tshark.StartInfo.CreateNoWindow = true;
            tshark.StartInfo.UseShellExecute = false;
            tshark.StartInfo.RedirectStandardOutput = true;

           tshark.OutputDataReceived += new DataReceivedEventHandler(TSharkOutputHandler);

            tshark.Start();

            tshark.BeginOutputReadLine();
            tshark.WaitForExit();
        }
    }

    void TSharkOutputHandler(object sender, DataReceivedEventArgs e)
    {
        this.Dispatcher.Invoke((Action)(() =>
        {
            tboxConsoleOutput.AppendText(e.Data);
        }));
    } 

但是ui只是冻结,没有信息显示我只是接近这个错误的

我找到了以下内容并且没有运气试过

No access different thread
Object different thread
Redirect Output to Textbox
Output to Textbox
Process output to richtextbox

1 个答案:

答案 0 :(得分:3)

以下是我的表现:

首先实现以下类:

public class TextBoxConsole : TextWriter
{
    TextBox output = null; //Textbox used to show Console's output.

    /// <summary>
    /// Custom TextBox-Class used to print the Console output.
    /// </summary>
    /// <param name="_output">Textbox used to show Console's output.</param>
    public TextBoxConsole(TextBox _output)
    {
        output = _output;
        output.ScrollBars = ScrollBars.Both;
        output.WordWrap = true;
    }

    //<summary>
    //Appends text to the textbox and to the logfile
    //</summary>
    //<param name="value">Input-string which is appended to the textbox.</param>
    public override void Write(char value)
    {
        base.Write(value);
        output.AppendText(value.ToString());//Append char to the textbox
    }


    public override Encoding Encoding
    {
        get { return System.Text.Encoding.UTF8; }
    }
}

现在,如果您希望将所有控制台输出写入某个文本框,请按以下方式声明:

首先创建一个文本框和名称,即&#34; tbConsole&#34;。现在你要告诉它该怎么做:

TextWriter writer = new TextBoxConsole(tbConsole);
Console.SetOut(writer);

从现在开始,每次写Console.WriteLine("Foo");之类的内容时,都会将其写入文本框。 就是这样。注意this approach is not mine。另外,根据控制台产生的输出量,它可能性能较差,因为它会将输出char写为char