[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Redirect Console window output to a TextBox in C#

[Redirect Console window output to a TextBox in C#]

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 the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.