What is a good way to direct console output to Text-box in Windows Form?

白昼怎懂夜的黑 提交于 2021-02-18 08:12:05

问题


In C#, what is a good way to direct console output to Text-box in Windows Form?

If I have an existing program that has console.WriteLine , do I need to overload the function in Windows Form Text-box?


回答1:


Create a text writer which writes to a text box:

    public class TextBoxWriter : TextWriter
    {
        TextBox _output = null;

        public TextBoxWriter (TextBox output)
        {
            _output = output;
        }

        public override void Write(char value)
        {
            base.Write(value);
            _output.AppendText(value.ToString());
        }

        public override Encoding Encoding
        {
            get { return System.Text.Encoding.UTF8; }
        }
    }

And redirect Console output to this writer:

        //...

        public Form()
        {
            InitializeComponent();
        }

        private void Form_Load(object sender, EventArgs e)
        {
            Console.SetOut(new TextBoxWriter(txtConsole));
            Console.WriteLine("Now redirecting output to the text box");
        }



回答2:


button_Click(object sender, EventArgs e)
{
   try
   {
      // Do stuff
   }
   catch(Exception exception)
   {
      // Couldn't do stuff. Log the exception.
      myTextBox.Text += "\n" + exception.Message;
   }
}

That ought to do it.



来源:https://stackoverflow.com/questions/14802876/what-is-a-good-way-to-direct-console-output-to-text-box-in-windows-form

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!