且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

重定向控制台输出到的WinForms列表框

更新时间:2023-12-05 13:33:58

另外,可能是干净的方式来做到这一点是的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; }
    }
}