目录
介绍
我差点忘了这段代码。
自从我需要这个以来已经有一段时间了,因为现在我没有做很多严格的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