可能重复:
How do I show console output/window in a forms application?
c#winforms程序有没有办法写入控制台窗口?
答案 0 :(得分:17)
这里基本上可以发生两件事。
winforms程序可以将自身附加到创建它的控制台窗口(或者如果需要,可以附加到不同的控制台窗口,或者实际上附加到新的控制台窗口)。一旦附加到控制台窗口,Console.WriteLine()等按预期工作。这种方法的一个问题是程序立即将控制权返回到控制台窗口,然后继续写入,因此用户也可以在控制台窗口中输入。你可以使用start和/ wait参数来处理这个问题。
当有人将程序的输出从其他地方传送出去时,例如
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);
}
}