【问题标题】:Writing output to the console from a c# winforms application [duplicate]从c#winforms应用程序将输出写入控制台[重复]
【发布时间】:2012-12-21 09:54:03
【问题描述】:

可能重复:
How do I show console output/window in a forms application?

有没有办法让 c# winforms 程序写入控制台窗口?

【问题讨论】:

  • 不错的帖子,但这里已经有人问过了:stackoverflow.com/questions/4362111/…
  • @RobertHarvey:除非我遗漏了什么,否则该帖子不会解决重定向问题...
  • 什么重定向问题?你在你的问题中没有说什么。啊,我明白了;你自己回答。好吧,除非您期望其他人提供其他答案...

标签: c# windows winforms console


【解决方案1】:

这里基本上会发生两件事。

  1. 控制台输出

winforms 程序可以将自己附加到创建它的控制台窗口(或附加到不同的控制台窗口,或者如果需要,甚至附加到新的控制台窗口)。一旦附加到控制台窗口 Console.WriteLine() 等按预期工作。这种方法的一个问题是程序立即将控制权返回给控制台窗口,然后继续对其进行写入,因此用户也可以在控制台窗口中键入。我认为您可以使用带有 /wait 参数的 start 来处理这个问题。

Link to start Command syntax

  1. 重定向控制台输出

这是当有人将您的程序的输出输出到其他地方时,例如。

你的应用 > 文件.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);
    }
}

【讨论】:

  • 谢谢,这是一个很好的解决方案!
  • 您可以读取命令行选项来指定是写入标准输出还是控制台
猜你喜欢
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多