Bind Console Output to RichEdit

前端 未结 2 1651
北荒
北荒 2021-01-06 11:55

So pretty straightforward question. I have a c# .dll with a whole lot of Console.Writeline code and would like to be able to view that output in a forms application using th

2条回答
  •  渐次进展
    2021-01-06 12:09

    You can use Console.SetOut() to redirect the output. Here's a sample form that demonstrates the approach. Drop a RichTextBox and a button on the form.

    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
            button1.Click += button1_Click;
            Console.SetOut(new MyLogger(richTextBox1));
        }
        class MyLogger : System.IO.TextWriter {
            private RichTextBox rtb;
            public MyLogger(RichTextBox rtb) { this.rtb = rtb; }
            public override Encoding Encoding { get { return null; } }
            public override void Write(char value) {
                if (value != '\r') rtb.AppendText(new string(value, 1));
            }
        }
        private void button1_Click(object sender, EventArgs e) {
            Console.WriteLine(DateTime.Now);
        }
    }
    

    I assume it won't be very fast but looked okay when I tried it. You could optimize by overriding more methods.

提交回复
热议问题