Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

TextBoxWriter: A Little Adapter for Logging or Whatever

5.00/5 (1 vote)
1 Jul 2022MIT 4.8K  
Adapt a TextBox to make it writeable like any other text based I/O
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!

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

Here's the code to make it go:

C#
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

License

This article, along with any associated source code and files, is licensed under The MIT License