Skip to content

Instantly share code, notes, and snippets.

@polarstars
Last active September 5, 2018 09:24
Show Gist options
  • Save polarstars/24e3b22ce7513df4a895dce777c205c5 to your computer and use it in GitHub Desktop.
Save polarstars/24e3b22ce7513df4a895dce777c205c5 to your computer and use it in GitHub Desktop.
如何在Form中重定向Console输出到文件 #C#
public class ConsoleWriterEventArgs : EventArgs
{
public string Value { get; private set; }
public ConsoleWriterEventArgs(string value)
{
Value = value;
}
}
public class ConsoleWriter : TextWriter
{
public override Encoding Encoding { get { return Encoding.UTF8; } }
public override void Write(string value)
{
if (WriteEvent != null) WriteEvent(this, new ConsoleWriterEventArgs(value));
base.Write(value);
}
public override void WriteLine(string value)
{
if (WriteLineEvent != null) WriteLineEvent(this, new ConsoleWriterEventArgs(value));
base.WriteLine(value);
}
public event EventHandler<ConsoleWriterEventArgs> WriteEvent;
public event EventHandler<ConsoleWriterEventArgs> WriteLineEvent;
}
[STAThread]
static void Main()
{
using (var consoleWriter = new ConsoleWriter())
{
consoleWriter.WriteEvent += consoleWriter_WriteEvent;
consoleWriter.WriteLineEvent += consoleWriter_WriteLineEvent;
Console.SetOut(consoleWriter);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
static void consoleWriter_WriteLineEvent(object sender, Program.ConsoleWriterEventArgs e)
{
//MessageBox.Show(e.Value, "WriteLine");
//保存e.Value到文件既可
}
static void consoleWriter_WriteEvent(object sender, Program.ConsoleWriterEventArgs e)
{
//MessageBox.Show(e.Value, "Write");
//保存e.Value到文件既可
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment