How to redirect the Console’s output to a TextBox in C#

First let’s create a VS Windows Application Project named “ConsoleRedirection”.

In order to redirect the console’s output to a text box in a Windows Form, we need to create a new class based on the abstract StringWriter class.

In the project create a new class file, and name it “TextBoxStreamWriter.cs”. The project now looks like this:

The project's structure

The project's structure

Enter the following code into the .cs file.

using System;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace ConsoleRedirection
{
    public class TextBoxStreamWriter : TextWriter
    {
        TextBox _output = null;

        public TextBoxStreamWriter(TextBox output)
        {
            _output = output;
        }

        public override void Write(char value)
        {
            base.Write(value);
            _output.AppendText(value.ToString()); // When character data is written, append it to the text box.
        }

        public override Encoding Encoding
        {
            get { return System.Text.Encoding.UTF8; }
        }
    }
}

Make sure the abstract “Encoding” property is overridden, and also override the Write(char value) method, which is called when character data is written to the stream.

Now open the main Form class “Form1.cs”, and drag and drop a TextBox and a button into it. Name the TextBox “txtConsole”.

How the Form looks after the UI elements have been added.

How the Form looks after the UI elements have been added.

The last thing to do is to enable the redirection. Double-click on the form to open the code view. The code that needs to be inserted is in bold. As you can see, there is nothing overwhelming.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ConsoleRedirection
{
    public partial class FormConsole : Form
    {
        // That's our custom TextWriter class
        TextWriter _writer = null;

        public FormConsole()
        {
            InitializeComponent();
        }

        private void FormConsole_Load(object sender, EventArgs e)
        {
             // Instantiate the writer
             _writer = new TextBoxStreamWriter(txtConsole);
             // Redirect the out Console stream
            Console.SetOut(_writer);

            Console.WriteLine("Now redirecting output to the text box");
        }

        // This is called when the "Say Hello" button is clicked
        private void txtSayHello_Click(object sender, EventArgs e)
        {
            // Writing to the Console now causes the text to be displayed in the text box.
            Console.WriteLine("Hello world");
        }
    }
}

The full code for this article is available at http://svanryckeghem.free.fr/downloads/ConsoleRedirection.zip

About these ads

Tags:

22 Responses to “How to redirect the Console’s output to a TextBox in C#”

  1. Peter Says:

    How can I resolved this solution for threading and beginInvoke?

    • Scott Says:

      The problem is with the textbox. You could change the class to use a simple string object and then use a mutex to add to the string and create a new get accessor to grab what new contents was copied to the string, again using the mutex for syncing. The following would be the code modes from the original poster

      Mutex bufferAccess = new Mutex();
      public TextBoxStreamWriter()
      {
      }
      public override void Write(char value)
      {
      base.Write(value);
      try
      {
      bufferAccess.WaitOne();
      output += value.ToString(); // When character data is written, append it to the text box.
      }
      catch (Exception)
      {

      }
      finally
      {
      bufferAccess.ReleaseMutex();
      }
      }
      public string GetString
      {
      get
      {
      string retVal = “”;
      try
      {
      bufferAccess.WaitOne();
      retVal = output;
      output = “”;
      }
      catch (Exception)
      {

      }
      finally
      {
      bufferAccess.ReleaseMutex();
      }
      return retVal;
      }
      }

  2. crockysam Says:

    just change the Write function to:

    public override void Write(char value) {
    MethodInvoker action = delegate { _output.AppendText(value.ToString()); };
    _output.BeginInvoke(action);
    }

    To make it compatible with cross-thread calls

  3. hint Says:

    hello,

    for your interest: here is a little sourceforge project under LGPL which does exactly that with all overloads of the Write methods:

    http://sourceforge.net/projects/consolewidget/

  4. T. J. Zelger Says:

    This is a great post and exactly what I was looking for.
    ThanX to saezndaree

  5. chris Says:

    Wicked snippet thank you :).

    • chris Says:

      for got to add, I moved:

      Console.SetOut(this);

      In to the class it self, as well as the “redirecting” statement that is appended on success. Just 1 less thing to remember when moving across project files :).

  6. Bryan Seah Says:

    hi is there anyway this can be done in an asp.net page. my friend is looking to redirect the console output to a textbox

    • saezndaree Says:

      Bryan, the TextBoxStreamWriter would work, you’d just need to change the overriden write method as follows:

      public override void Write(char value)
      {
      base.Write(value);

      _output.Text += value;
      }

      …because the ASP:TextBox control doesn’t have an AppendText() method.

      I’m not sure this is really what you want though.

  7. Redirect Console.Writeline to Textbox | Gokul's Blog Says:

    […] http://saezndaree.wordpress.com/2009/03/29/how-to-redirect-the-consoles-output-to-a-textbox-in-c/  […]

  8. gendo Says:

    I was trying to redirect the trace output of a c#-application to a TextBox and then I found your solution. Thank you!!! This makes the things soooo simple (and flexible). Using your example it looks like this:

    1. add the lines to the app.config

    2. create an instance of the CustomSource on the top of FormConsole:
    private static TraceSource _mySource = new TraceSource(“CustomSource”);

    3. and instead of Console.WriteLine(“Hello World”) use _mySource.TraceInformation(“Hello World”) or TraceEvent if you need Errors, Warnings etc.

    • gendo Says:

      …and the app.config once more (without the ‘<'s and '<'s):

      system.diagnostics
      sources
      source name="CustomSource" switchName="sourceSwitch" switchType="System.Diagnostics.SourceSwitch"
      listeners
      add name="ConsoleListener"
      add
      listeners
      source
      sources
      switches
      add name="sourceSwitch" value="Verbose"
      add
      switches
      sharedListeners
      add name="ConsoleListener" type="System.Diagnostics.ConsoleTraceListener"
      add
      sharedListeners
      trace autoflush="true" indentsize="4"
      trace
      system.diagnostics

  9. chanipoz Says:

    Thanks very much, it was very useful for me. It is also give a solution to the problem: how write to a form from another class!!

  10. API_ConsoleOut.cs – InProcess Capture of the Console Output « OWASP O2 Platform Blog Says:

    […] How to redirect the Console’s output to a TextBox in C#   (using the Console.SetOut technique) […]

  11. Dinis Cruz Says:

    Hi, using the OWASP O2 Platform, I’ve implemented a variation of this solution in an API that allows the easy viewing of the console output of the current process (in an existing control or popup window).

    See this blog post for more details: http://o2platform.wordpress.com/2011/11/26/api_consoleout-cs-inprocess-capture-of-the-console-output/

  12. Balu Says:

    thnq u for u post its too gud…
    but i have another problem is i need read the another textbox and dispay like
    wheni type my name in one text box and when click button i want to get name + say’s hello…..

    can u plz sned abut that one some arget…
    thanking u

  13. little bandit Says:

    Thanks, like your solution.

    Created link to you from Stack Overflow

    http://stackoverflow.com/questions/5221066/convert-console-writeline-into-textbox/9710492#9710492

  14. Shawn Says:

    Nice one – thanks – was a little stumped on this.

  15. Peter Says:

    Excellent explanation and really useful! I’m pretty new to C#, so the one thing I was missing was the event handler for the button: http://msdn.microsoft.com/en-us/library/aa984320(v=vs.71).aspx

  16. Normand G. Mccormick Says:

    Now open the main Form class “Form1.cs”, and drag and drop a TextBox and a button into it. Name the TextBox “txtConsole”.

  17. kemal Says:

    hai thanks a lot man

  18. Как перенаправить вывод консоли в TextBox в C# | Нюансы разработки Says:

    […] Источник: http://saezndaree.wordpress.com/2009/03/29/how-to-redirect-the-consoles-output-to-a-textbox-in-c/ […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: