Updated on 2022-07-01
Adapt a TextBox to make it writeable like any other text based I/O
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.
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);
// Now use tbwriter like any other TextWriter
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!