Redirecting Console.WriteLine() to Textbox

前端 未结 4 1650
死守一世寂寞
死守一世寂寞 2020-12-04 18:08

I\'m building this application in Visual Studio 2010 using C#.

Basically there are 2 files, form1.cs (which is the windows form) and program.cs (where all the logic

4条回答
  •  执笔经年
    2020-12-04 19:05

    Start by creating a new TextWriter that is capable of writing to a textbox. It only needs to override the Write method that accepts a char, but that would be ungodly inefficient, so it's better to overwrite at least the method with a string.

    public class ControlWriter : TextWriter
    {
        private Control textbox;
        public ControlWriter(Control textbox)
        {
            this.textbox = textbox;
        }
    
        public override void Write(char value)
        {
            textbox.Text += value;
        }
    
        public override void Write(string value)
        {
            textbox.Text += value;
        }
    
        public override Encoding Encoding
        {
            get { return Encoding.ASCII; }
        }
    }
    

    In this case I've had it just accept a Control, which could be a Textbox, a Label, or whatever. If you want to change it to just a Label that would be fine.

    Then just set the console output to a new instance of this writer, pointing to some textbox or label:

    Console.SetOut(new ControlWriter(textbox1));
    

    If you want the output to be written to the console as well as to the textbox we can use this class to create a writer that will write to several writers:

    public class MultiTextWriter : TextWriter
    {
        private IEnumerable writers;
        public MultiTextWriter(IEnumerable writers)
        {
            this.writers = writers.ToList();
        }
        public MultiTextWriter(params TextWriter[] writers)
        {
            this.writers = writers;
        }
    
        public override void Write(char value)
        {
            foreach (var writer in writers)
                writer.Write(value);
        }
    
        public override void Write(string value)
        {
            foreach (var writer in writers)
                writer.Write(value);
        }
    
        public override void Flush()
        {
            foreach (var writer in writers)
                writer.Flush();
        }
    
        public override void Close()
        {
            foreach (var writer in writers)
                writer.Close();
        }
    
        public override Encoding Encoding
        {
            get { return Encoding.ASCII; }
        }
    }
    

    Then using this we can do:

    Console.SetOut(new MultiTextWriter(new ControlWriter(textbox1), Console.Out));
    

提交回复
热议问题