Last active
September 5, 2018 09:24
-
-
Save polarstars/24e3b22ce7513df4a895dce777c205c5 to your computer and use it in GitHub Desktop.
如何在Form中重定向Console输出到文件 #C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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