重定向控制台输出到的WinForms列表框 [英] Redirecting Console Output to winforms ListBox

查看:251
本文介绍了重定向控制台输出到的WinForms列表框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了大多数转储使用Console.WriteLine其调试文本库();

I have built a library that dumps most of its debug text using Console.WriteLine();

我现在我使用该库在Windows的过程中窗体应用程序,并且仍然需要访问控制台输出。 (要显示一个列表/富文本框)

I am now I am the process of using the library in a Windows Forms Application, and still need access to the Console output. ( To Display in a List/RichText box )

我发现我可以重写标准输出控制台的一个TextWriter的,但我怎么会那么得到这个数据到显示器。

I Noticed I can override the standard out of the console to a TextWriter, but how would I then get this data into the display .

我试着做沿着

  public partial class Form1 : Form
  {
    Timer T;
    MemoryStream mem;
    StreamWriter writer; 


    public Form1()
    {

        InitializeComponent();
        mem = new MemoryStream(1000);
        writer = new StreamWriter(mem);
        Console.SetOut(writer);

        T = new Timer();
        T.Interval = 250; // yes this probally is to short.
        T.Tick += new EventHandler(T_Tick);
        T.Start();


        Console.WriteLine("output");
        Console.WriteLine("AnotherLine");
    }

    void T_Tick(object sender, EventArgs e)
    {
        string s = Encoding.Default.GetString(mem.ToArray());
        string[] Lines = s.Split(Environment.NewLine.ToCharArray());
        Output.Items.Clear(); // Output is a listbox 
        foreach (string str in Lines)
            Output.Items.Add(str);
    }
}

但无济于事。有任何想法吗?

but to no avail. Any ideas?

不需要的code删除。

Unneeded code removed.

推荐答案

另外,可能是干净的方式来做到这一点是的TextWriter扩展与自己的记录,无论你想它。

Another, probably cleaner way to do this is to extend TextWriter with your own that logs to wherever you'd like it to.

注:我没有测试过这种

public class ListBoxWriter : TextWriter
{
    private ListBox list;
    private StringBuilder content = new StringBuilder();

    public ListBoxWriter(ListBox list)
    {
    	this.list = list;
    }

    public override void Write(char value)
    {
    	base.Write(value);
    	content.Append(value);
    	if (value == '\n')
    	{
    		list.Items.Add(content.ToString());
    		content = new StringBuilder();
    	}
    }

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

这篇关于重定向控制台输出到的WinForms列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆