绑定控制台输出目标的RichEdit [英] Bind Console Output to RichEdit

查看:176
本文介绍了绑定控制台输出目标的RichEdit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,很简单的问题。我有一大堆的Console.Writeline代码C#.dll和希望能够查看使用这个.dll表单应用程序的输出。是否有控制台输出绑定到一个RichEdit的(或其他合适的控制),一种相对简便的方法?或者,我可以嵌入表单内的实际控制台的壳呢?我已经找到了几个有点类似的问题,但在大多数情况下,人们希望能够收到控制台输入,这对我来说是没有必要的。

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 this .dll. Is there a relatively easy way of binding the console output to a RichEdit (or other suitable control)? Alternatively, can I embed an actual console shell within the form? I have found a few somewhat similar questions but in most cases people wanted to be able to recieve console input, which for me is not necessary.

感谢。

推荐答案

您可以使用Console.SetOut()来重定向输出。以下是演示的方式一个样表。 。拖放一个RichTextBox和表单上的按钮

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.

这篇关于绑定控制台输出目标的RichEdit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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