Redirecting console output to winforms ListBox

I created a library that flushes most of the debug text using Console.WriteLine ();

Now I am in the process of using the library in a Windows Forms application and still need access to the Console output. (To display in / RichText list)

I noticed. I can override the standard from the console in TextWriter, but how could I get this data on the display.

I tried doing something line by line

  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?

Removing unnecessary code.

+5
source share
2 answers

Another, possibly cleaner way to do this is to expand the TextWriter with your own journal, wherever you want.

. .

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; }
    }
}
+12

, "" , , , . , , .

.NET Debug, : ConsoleTraceListener TextWriterTraceListener.

, :

writer.Flush();

Console.WriteLine().

+3

All Articles