Adapt a TextWriter to work on top of a TextBox to facilitate easier logging or otherwise adapting textual I/O to a GUI window.
Introduction
I almost forgot about this code.
It has been awhile since I needed this, because I don't do a lot of strictly Windows development these days, but when I did need it, it was nice to have.
I'm presenting it here in case you need it.
There is no download. All the code you need is copyable from below.
Using this Mess
It's very easy to use the code. Just instantiate it passing the target TextBox
in and then start writing. You'll want the target to be multiline and scrollable probably so don't forget to set the properties!
var tbwriter = new TextBoxWriter(textBox1);
Here's the code to make it go:
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) { }
}
}
That's all there is to it!
History
- 1st July, 2022 - Initial submission