控制台输出到文本框

3

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

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);
        }));
    } 

但是用户界面被冻结了,没有显示任何信息,我是否处理不当?
我已经找到以下内容并尝试过,但没有成功: 无法访问不同的线程
不同线程的对象
将输出重定向到文本框
输出到文本框
将进程输出到 RichTextBox

您的UI界面因为这个语句而冻结:tshark.WaitForExit();。您正在阻塞UI线程,以使进程运行。实际上,取决于该过程产生了多少输出,您最终可能会阻止该进程继续运行,因为您在Invoke()方法调用上死锁了。无法提供好的答案,因为问题中没有足够的上下文。但它将涉及不调用WaitForExit()(并且在完成操作后不释放Process对象)。 - Peter Duniho
1个回答

4

我是这样做的:

首先,你需要实现以下类:

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; }
    }
}

现在,如果你想让所有的控制台输出都写入到一个特定的文本框中,你需要按照以下方式声明它。
首先创建一个文本框并命名为"tbConsole"。现在你想告诉它该做什么:
TextWriter writer = new TextBoxConsole(tbConsole);
Console.SetOut(writer);

从现在开始,每次您编写像Console.WriteLine("Foo");这样的内容时,它都将被写入您的文本框中。 就是这样。请注意此方法不是我发明的。另外,根据您的控制台产生的输出量,它可能会具有较差的性能,因为它按char逐个写入输出。

1
@ondrovic 它是否仍然冻结?也许是你的输出有问题? - チーズパン

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接