可能是重复问题:
如何在窗体应用程序中显示控制台输出/窗口?
是否有一种方法让C# WinForms程序写入控制台窗口?
可能是重复问题:
如何在窗体应用程序中显示控制台输出/窗口?
是否有一种方法让C# WinForms程序写入控制台窗口?
这里基本上有两件事情可以发生。
WinForms程序可以连接到创建它的控制台窗口(或其他控制台窗口,或者甚至是新的控制台窗口)。一旦连接到控制台窗口,Console.WriteLine()等函数将按预期工作。使用此方法的一个注意点是程序立即返回控制台窗口,然后继续写入控制台窗口,因此用户也可以在控制台窗口中输入内容。您可以使用带有/wait参数的start来处理这个问题。
当某人将您程序的输出导向其他地方时,例如:
yourapp > file.txt
在这种情况下连接到控制台窗口会忽略管道。要使其正常工作,可以调用Console.OpenStandardOutput()获取应将输出导向的流的句柄。这仅在输出被导向的情况下才有效,因此如果要处理这两种情况,则需要打开标准输出并将其写入,并连接到控制台窗口。这意味着输出将被发送到控制台窗口和管道,但这是我能找到的最好的解决方案。以下是我使用的代码。
// This always writes to the parent console window and also to a redirected stdout if there is one.
// It would be better to do the relevant thing (eg write to the redirected file if there is one, otherwise
// write to the console) but it doesn't seem possible.
public class GUIConsoleWriter : IConsoleWriter
{
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);
private const int ATTACH_PARENT_PROCESS = -1;
StreamWriter _stdOutWriter;
// this must be called early in the program
public GUIConsoleWriter()
{
// this needs to happen before attachconsole.
// If the output is not redirected we still get a valid stream but it doesn't appear to write anywhere
// I guess it probably does write somewhere, but nowhere I can find out about
var stdout = Console.OpenStandardOutput();
_stdOutWriter = new StreamWriter(stdout);
_stdOutWriter.AutoFlush = true;
AttachConsole(ATTACH_PARENT_PROCESS);
}
public void WriteLine(string line)
{
_stdOutWriter.WriteLine(line);
Console.WriteLine(line);
}
}