使用 STDOUT 打印语句将控制台附加到 C# Windows 应用程序

Attaching Console to C# Windows Application with STDOUT Print Statements

我有一个 C# GUI 应用程序,它也支持服务器端脚本的命令行模式。我的应用程序关闭输入参数的数量,如果 > 0,则附加父控制台。

[DllImport("kernel32.dll")]
static extern bool AttachConsole(int dwProcessId);
private const int ATTACH_PARENT_PROCESS = -1;

[STAThread]
static void Main(string[] args)
{
    bool runningFromConsole = args.Length > 0 && AttachConsole(ATTACH_PARENT_PROCESS);
    if(runningFromConsole)
        // Handle input arguments
    else
        // Launch GUI
}

我能够使用 Console.Out.WriteLine("Text"); 成功地将文本写入控制台,但该行不会作为 STDOUT(或 STDERR,如果我使用 Console.Error.WriteLine("Text"))发送到控制台。

当 运行 我的应用程序在本地时,这没什么大不了的,但是当 运行 在构建服务器上时,应用程序 returns 不注册。现在,我正在通过创建一个补充日志文件来解决这个问题,一旦我的应用程序完成 运行,我就会 type application.log 到控制台。

有没有办法将打印到控制台的强制文本作为 STDOUT/STDERR 发送?

AttachConsole 的行为并不像您期望的那样,您经常需要做的是 AllocConsole 并更改您的 stdio 句柄以使用该控制台。

我可以验证这个问题的可接受答案在这种情况下有效,因为我已经使用过它:No console output when using AllocConsole and target architecture x86