Click here to Skip to main content
15,881,938 members
Articles / Programming Languages / C#
Tip/Trick

TextBoxWriter: A Little Adapter for Logging or Whatever

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
1 Jul 2022MIT 4.4K   5   1
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


Written By
United States United States
Just a shiny lil monster. Casts spells in C++. Mostly harmless.

Comments and Discussions

 
SuggestionThreading Pin
wmjordan3-Jul-22 20:27
professionalwmjordan3-Jul-22 20:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.