问题描述
我有一个外部的dll C#编写的,我从它使用的写入调试信息到控制台的组件文件学习 Console.WriteLine
。
I have an external dll written in C# and I studied from the assemblies documentation that it writes its debug messages to the Console using Console.WriteLine
.
此DLL写我的应用程序的UI交互期间安慰,所以我不作DLL直接调用,但我会捕获所有控制台输出,所以我想我并初始化的形式加载,然后获取捕获的文本后。
this DLL writes to console during my interaction with the UI of the Application, so i don't make DLL calls directly, but i would capture all console output , so i think i got to intialize in form load , then get that captured text later.
我想所有的输出重定向到一个字符串变量。
I would like to redirect all the output to a string variable.
我试过 Console.SetOut
,但其使用重定向到字符串是不容易的。
I tried Console.SetOut
, but its use to redirect to string is not easy.
推荐答案
由于好像要赶在实时控制台输出,我想通了,你可以创建自己的的TextWriter
实现,触发一个事件,每当一个写
或的WriteLine
发生在控制台
。
As it seems like you want to catch the Console output in realtime, I figured out that you might create your own TextWriter
implementation that fires an event whenever a Write
or WriteLine
happens on the Console
.
笔者是这样的:
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;
}
如果这是一个WinForm的应用程序,你可以设置的作家和消耗其在Program.cs的事件是这样的:
If it's a WinForm app, you can setup the writer and consume its events in the Program.cs like this:
/// <summary>
/// The main entry point for the application.
/// </summary>
[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");
}
static void consoleWriter_WriteEvent(object sender, Program.ConsoleWriterEventArgs e)
{
MessageBox.Show(e.Value, "Write");
}
这篇关于重定向从Windows应用程序console.writeline为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!