Redirecting Console Output to winforms ListBox

后端 未结 2 1049
北恋
北恋 2021-02-04 19:43

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

I am now I am the process of using the library in a Windows Forms Application, and s

相关标签:
2条回答
  • 2021-02-04 20:27

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

    Note: I have not tested this.

    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; }
        }
    }
    
    0 讨论(0)
  • 2021-02-04 20:30

    Rather than try to "capture" text sent to the console, I would create a new class that handles writing the output for you. Then that new class could write to the console, as well as anyplace else you want it to go.

    If you're using .NET's Debug class, simply use two listeners: a ConsoleTraceListener and a TextWriterTraceListener.

    To make your existing code work, add:

    writer.Flush();
    

    after your Console.WriteLine() calls.

    0 讨论(0)
提交回复
热议问题