将控制台输出定向到 Windows 窗体中的文本框的好方法是什么? [英] What is a good way to direct console output to Text-box in Windows Form?

查看:28
本文介绍了将控制台输出定向到 Windows 窗体中的文本框的好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中,将控制台输出定向到 Windows 窗体中的文本框的好方法是什么?

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

如果我有一个包含 console.WriteLine 的现有程序,我是否需要在 Windows 窗体文本框中重载该函数?

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

推荐答案

创建一个写入文本框的文本编写器:

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

这篇关于将控制台输出定向到 Windows 窗体中的文本框的好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆