c# - 控制台输出到文本框

标签 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

最佳答案

我是这样做的:

首先你实现下面的类:

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

关于c# - 控制台输出到文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26528695/

相关文章:

c - C 中的树遍历和串联崩溃

c - 读取一个字符串并将其放入C中的(int)中

c# - 线程顺序同步

c# - 将应用程序作为控制台应用程序运行并传递参数,否则作为 Win Form 应用程序运行

c# - ASP.NET MVC ApplicationDbContext 创建

java - 实现一个算法来确定字符串是否包含所有唯一字符(大于 U+FFFF 的字符)

java - 以正确的方式实现 Event-Dispatch-Thread

java - 如何使用 Java 中的多线程实现 2D 方阵乘法?

c# - 使用 C# 驱动程序不工作查询 mongodb

c# - TimHeuer 的 FloatableWindow 问题