简体   繁体   English

如何将dll中的Console.Writeline()消息重定向到Winform列表框

[英]How to Re-direct Console.Writeline() messages from a dll to Winform listbox

My dll has some real-time messages which are printed out using: 我的dll有一些实时消息,这些消息使用以下命令打印出来:

Console.Writeline("XYZ Message");

I have referenced this dll in my C# Windows form application. 我在C#Windows窗体应用程序中引用了该dll。 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. 我希望将这些消息Listbox到Winform中的Listbox ,而不是单独的控制台窗口。

Can someone help me with a simple example for this. 有人可以帮我举一个简单的例子。

重定向Console.WriteLine到String也许是这样,您可以使用listBox1.Items.Add(stringName);将输出转换为String,然后从String转换为ListBox listBox1.Items.Add(stringName);

Another, probably cleaner way to do this is to extend TextWriter with your own that logs to wherever you'd like it to. 另一种可能更干净的方法是使用自己的TextWriter扩展日志,将其记录到您想要的任何位置。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM