从C# WinForms应用程序向控制台输出内容

9

2
不错的帖子,但这个问题已经在这里被问过了:https://dev59.com/Km855IYBdhLWcg3wZzff - Robert Harvey
1
@RobertHarvey:除非我漏掉了什么,否则那篇帖子并没有解决重定向问题... - cedd
什么重定向问题?你的问题中并没有提到。啊,我明白了,你自己回答了。嗯,除非你还期望别人提供其他答案…… - Robert Harvey
1个回答

21

这里基本上有两件事情可以发生。

  1. 控制台输出

WinForms程序可以连接到创建它的控制台窗口(或其他控制台窗口,或者甚至是新的控制台窗口)。一旦连接到控制台窗口,Console.WriteLine()等函数将按预期工作。使用此方法的一个注意点是程序立即返回控制台窗口,然后继续写入控制台窗口,因此用户也可以在控制台窗口中输入内容。您可以使用带有/wait参数的start来处理这个问题。

启动命令语法

  1. 重定向控制台输出

当某人将您程序的输出导向其他地方时,例如:

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);
    }
}

1
谢谢,这是一个很棒的解决方案! - Michael Edwards
你可以读取命令行选项来指定是写入标准输出还是控制台。 - JoelFan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接