There is a case when we need to use same library code in both console application and windows form application. This is fine if there are no messages displayed in the output window (usually the progress / log messages). one way is to create a log file in a predefined folder (TEMP) and open it after process is complete. Here is one method that can be used to capture the console output and redirected to a text box in the windows form application.
Steps
- Create a new class as given in the snippet
- Take the temp reference of default output stream of 'Console' class and set new stream output that captures and shows the output in the text box
- Once new stream is set, all the console output is displayed in the referenced text box
- After work is done, restore the output stream to default
// Create a class for capture
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Utils
{
public class StringRedir : StringWriter
{
private TextBox outBox;
public StringRedir(ref TextBox textBox)
{
outBox = textBox;
}
public override void WriteLine(string x)
{
outBox.Text += x + "\r\n";
outBox.Refresh();
}
}
}
The stream object is used to capture the output. the method WriteLine is overriden to set the text to the text box control. other methods can also be added as required.
// Usage: Initialize the capture to your textbox control TextWriter tmp = Console.Out; Console.SetOut(new StringRedir(ref textBox1));
TextWriter tmp is used to store the reference of the default output stream. It can be then used to restore the output stream to default one.
// Usage: release the console capture Console.SetOut(tmp);
The above logic has been referenced from following links:
http://social.msdn.microsoft.com/Forums/en/winformsdatacontrols/thread/2e827551-6cbc-4b3d-a04f-e4dc6c262ae1
http://saezndaree.wordpress.com/2009/03/29/how-to-redirect-the-consoles-output-to-a-textbox-in-c/
http://social.msdn.microsoft.com/Forums/en/winformsdatacontrols/thread/2e827551-6cbc-4b3d-a04f-e4dc6c262ae1
http://saezndaree.wordpress.com/2009/03/29/how-to-redirect-the-consoles-output-to-a-textbox-in-c/
Comments
Post a Comment