TextBoxWriter:用于日志记录或其他任何内容的小适配器

目录

介绍

使用这个混乱


介绍

我差点忘了这段代码。

自从我需要这个以来已经有一段时间了,因为现在我没有做很多严格的Windows开发,但是当我确实需要它时,很高兴拥有它。

我在这里展示它,以防您需要它。

没有下载。您需要的所有代码都可以从下面复制。

使用这个混乱

使用代码非常容易。只需实例化它传递目标TextBox,然后开始写入。您可能希望目标为多行且可滚动,因此不要忘记设置属性!

var tbwriter = new TextBoxWriter(textBox1);
// Now use tbwriter like any other TextWriter

这是实现它的代码:

using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

class TextBoxWriter : TextWriter
{
    TextBox _textBox;
    public TextBoxWriter(TextBox textBox)
    {
        if (null == textBox)
            throw new ArgumentNullException(nameof(textBox));
        _textBox = textBox;
    }
    public override Encoding Encoding { get { return Encoding.Default; } }
    public override void Write(char value)
    {
        try
        {
            _textBox.AppendText(value.ToString());
        }
        catch (ObjectDisposedException) { }
    }
    public override void Write(string value)
    {
        try
        {
            _textBox.AppendText(value);
        }
        catch (ObjectDisposedException) { }
    }
    public override void Write(char[] buffer, int index, int count)
    {
        try
        {
            _textBox.AppendText(new string(buffer, index, count));
        }
        catch (ObjectDisposedException) { }
    }
    public override void Write(char[] buffer)
    {
        try
        {
            _textBox.AppendText(new string(buffer));
        }
        catch (ObjectDisposedException) { }
    }
}

仅此而已!

https://www.codeproject.com/Tips/5336304/TextBoxWriter-A-Little-Adapter-for-Logging-or-What

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值