Print console output in RichEdit

Pretty simple question. I have C # .dll with a range of Console.Writeline code and you want to view this output in a forms application using this .dll. Is there a relatively simple way to bind console output to RichEdit (or another suitable control)? Alternatively, is it possible to insert a real console shell into a form? I found several similar questions, but in most cases, people wanted to get console input, which is not needed for me.

Thank.

+3
source share
2 answers

You can use Console.SetOut () to redirect the output. Here is a sample form demonstrating the approach. Drop the RichTextBox and button in 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 guess it won't be very fast, but it looked fine when I tried. You can optimize by overriding more methods.

+4
source

IMO, it would be better to reorganize the existing code, replacing the existing one Console.WriteLinewith some central method in your code, and then repeat this method, presumably providing another TextWriter:

private static TextWriter output = Console.Out;
public static TextWriter Output {
   get {return output;}
   set {output = value ?? Console.Out;}
}
public static void WriteLine(string value) {
    output.WriteLine(value);
}
public static void WriteLine(string format, params string[] args) {
    output.WriteLine(format, args);
}

Or (simpler and less hacky re static field), just pass it TextWriterinto your existing code and write to it?

+3
source

Source: https://habr.com/ru/post/1765474/


All Articles