0

My dll has some real-time messages which are printed out using:

Console.Writeline("XYZ Message");

I have referenced this dll in my C# Windows form application. The messages are then printed out in real-time using:

public MyClientMainForm()
{
  AllocConsole();
  InitializeComponent();
}

But using this way I am launching a separate console window for displaying the messages.

Instead of a separate Console window, I wish to re-direct these messages to a Listbox inside my Winform.

Can someone help me with a simple example for this.

David Pilkington
  • 13,528
  • 3
  • 41
  • 73
Varun
  • 3
  • 3
  • 1
    Possible duplicate of [Redirecting Console Output to winforms ListBox](http://stackoverflow.com/questions/1780606/redirecting-console-output-to-winforms-listbox) – RusArt Jan 09 '17 at 05:31

2 Answers2

0

Redirect Console.WriteLine to String Maybe, This way you can convert your output to String and from String you can convert to ListBox using listBox1.Items.Add(stringName);

Community
  • 1
  • 1
Kartik Shah
  • 143
  • 2
  • 5
  • 14
-1

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; }
}
}
rishit_s
  • 350
  • 3
  • 12
  • This answer is just copy-pasted from [Redirecting Console Output to winforms ListBox](http://stackoverflow.com/a/1780647/324260) without adding any context. – Ilian Jan 09 '17 at 05:42
  • @rishit_s Where should the extended public class ListBoxWriter : TextWriter be placed in the Winform code? And will this be fine: public partial class MyClientMainForm : Form { TextWriter writer; public MyClientMainForm() { InitializeComponent(); writer = new ListBoxWriter(MyListBox); Console.SetOut(writer); } ... }//class ends – Varun Jan 09 '17 at 06:23