问题
In C#, what is a good way to direct console output to Text-box in Windows Form?
If I have an existing program that has console.WriteLine , do I need to overload the function in Windows Form Text-box?
回答1:
Create a text writer which writes to a text box:
public class TextBoxWriter : TextWriter
{
TextBox _output = null;
public TextBoxWriter (TextBox output)
{
_output = output;
}
public override void Write(char value)
{
base.Write(value);
_output.AppendText(value.ToString());
}
public override Encoding Encoding
{
get { return System.Text.Encoding.UTF8; }
}
}
And redirect Console output to this writer:
//...
public Form()
{
InitializeComponent();
}
private void Form_Load(object sender, EventArgs e)
{
Console.SetOut(new TextBoxWriter(txtConsole));
Console.WriteLine("Now redirecting output to the text box");
}
回答2:
button_Click(object sender, EventArgs e)
{
try
{
// Do stuff
}
catch(Exception exception)
{
// Couldn't do stuff. Log the exception.
myTextBox.Text += "\n" + exception.Message;
}
}
That ought to do it.
来源:https://stackoverflow.com/questions/14802876/what-is-a-good-way-to-direct-console-output-to-text-box-in-windows-form