【问题标题】:Console output to textbox控制台输出到文本框
【发布时间】:2014-10-23 12:59:57
【问题描述】:

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

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

【问题讨论】:

  • 您的 UI 由于以下语句而冻结:tshark.WaitForExit(); 您正在阻塞 UI 线程,而进程正在运行。事实上,根据进程的输出量,您最终可能会阻止进程继续进行,因为您在 Invoke() 方法调用上陷入僵局。不可能提供一个好的答案,因为您的问题没有足够的上下文。但这将涉及不调用WaitForExit()(并且在你完成之前不释放Process对象)。

标签: c# string multithreading console


【解决方案1】:

这是我的做法:

首先你实现以下类:

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"); 之类的内容时,它都会写入您的文本框。 就是这样。注意this approach is not mine。此外,取决于您的控制台产生的输出量,它的性能可能会很差,因为它会将输出 char 写入 char

【讨论】:

  • @ondrovic 它仍然冻结吗?可能是你的输出有问题?
猜你喜欢
  • 1970-01-01
  • 2013-02-22
  • 2011-02-22
  • 1970-01-01
  • 2023-03-27
  • 2016-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多