Redirect Console window output to a TextBox in C#

[example]

This example captures output sent to the Console window and displays it in a TextBox control. It is based on an excellent reply by user Servy on Stack Overflow.

The Console object has a SetOut method that lets you change the TextWriter object to which it sends output. To redirect the output, you create a TextWriter subclass and then make the Console object send output to it.

The following code shows the TextBoxWriter class.

public class TextBoxWriter : TextWriter
{
    // The control where we will write text.
    private Control MyControl;
    public TextBoxWriter(Control control)
    {
        MyControl = control;
    }

    public override void Write(char value)
    {
        MyControl.Text += value;
    }

    public override void Write(string value)
    {
        MyControl.Text += value;
    }

    public override Encoding Encoding
    {
        get { return Encoding.Unicode; }
    }
}

This method overrides the TextWriter base class’s Write method and Encoding property. The Write(char value) method and the property are marked as abstract, so you must override them in any derived class. Overriding Write(string value) makes output more efficient.

The two versions of the Write method simply append their parameters to the control’s Text property. As in Servy’s example, the writer’s control is a generic Control, so this will work with a TextBox, Label, or other reasonable control.

When the program starts, the following Form_Load event handler installs the new writer.

// Install a new output TextWriter for the Console window.
private void Form1_Load(object sender, EventArgs e)
{
    TextBoxWriter writer = new TextBoxWriter(txtConsole);
    Console.SetOut(writer);
}

This code creates a new TextBoxWriter associated with the form’s TextBox named txtConsole. It then passes the writer into the Console object’s SetOut method.

When you enter text in the form’s TextBox and click Write, the following code executes.

// Write to the Console window.
private void btnWrite_Click(object sender, EventArgs e)
{
    Console.WriteLine(txtOutput.Text);
    txtOutput.Clear();
}

This code simply writes your text into the Console object and then clears the input TextBox.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in console and tagged , , , , , , , , . Bookmark the permalink.

One Response to Redirect Console window output to a TextBox in C#

  1. Pingback: Write Console window output to multiple places in C# - C# HelperC# Helper

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.