可能的重复:
如何在表单应用程序中显示控制台输出/窗口? https://stackoverflow.com/questions/4362111/how-do-i-show-console-output-window-in-a-forms-application
有没有办法让 C# winforms 程序写入控制台窗口?
这里基本上可能发生两件事。
- 控制台输出
winforms 程序可以将自身附加到创建它的控制台窗口(或者附加到不同的控制台窗口,或者如果需要的话实际上附加到新的控制台窗口)。一旦连接到控制台窗口 Console.WriteLine() 等就会按预期工作。这种方法的一个问题是程序立即将控制权返回到控制台窗口,然后继续写入,因此用户也可以在控制台窗口中键入内容。我认为您可以使用带有 /wait 参数的 start 来处理这个问题。
启动命令语法 https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.start?view=net-7.0
- 重定向控制台输出
这是当有人将程序的输出传送到其他地方时,例如。
你的应用 > file.txt
在这种情况下,连接到控制台窗口实际上会忽略管道。为了完成这项工作,您可以调用 Console.OpenStandardOutput() 来获取输出应通过管道传输到的流的句柄。这仅在输出通过管道传输时才有效,因此如果您想处理这两种情况,您需要打开标准输出并写入它并附加到控制台窗口。这确实意味着输出被发送到控制台窗口and到管道,但这是我能找到的最好的解决方案。下面是我用来执行此操作的代码。
// 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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)