可能重复:
How do I show console output/window in a forms application?输出写入到控制台从C#WinForms应用程序
是否有一个C#的WinForms程序写入到控制台窗口的方法吗?
可能重复:
How do I show console output/window in a forms application?输出写入到控制台从C#WinForms应用程序
是否有一个C#的WinForms程序写入到控制台窗口的方法吗?
基本上有两件事情可以在这里发生。
可能的是一个WinForms程序本身附加到(如果需要或到不同的控制台窗口中,或实际上对新控制台窗口)创建它的控制台窗口。一旦连接到控制台窗口Console.WriteLine()等按预期工作。这种方法的一个问题是,程序立即将控制权交还给控制台窗口,然后继续写入,以便用户也可以在控制台窗口中输入。你可以用/ 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);
}
}
谢谢,这是一个很好的解决方案! –
您可以读取命令行选项来指定是写入标准输出还是控制台 – JoelFan
尼斯后,但它已经在这里问:http://stackoverflow.com/questions/4362111/how-do-i-show-console-output-window-in-a-forms-application –
@RobertHarvey:除非我错过了一些东西,那篇文章没有解决重定向问题...... – cedd
什么重定向问题?你在这个问题上没有提到任何有关这方面的事情。啊,我明白了;你自我回答。那么,除非你希望别人提供额外的答案...... –