控制台没有显示打印输出

本文关键字:打印 输出 显示 控制台 | 更新日期: 2023-09-27 18:13:19

我使用WPF应用程序的控制台来打印调试信息。控制台是这样打开的:

static class DebugConsole //Console window handling class
{
    [DllImport("Kernel32")]
    private static extern bool AllocConsole();
    [DllImport("Kernel32")]
    private static extern bool FreeConsole();
    [DllImport("Kernel32")]
    private static extern IntPtr GetConsoleWindow();
    [DllImport("Kernel32")]
    private static extern int GetConsoleOutputCP();
    public static bool HasConsole
    {
        get { return GetConsoleWindow() != IntPtr.Zero; }
    }
    static public void Open() //Open console window
    {
        AllocConsole();
        Console.WriteLine("test");
    }
}

. .同时在编辑器的另一部分…

    public MainWindow() //This gets executed when the application starts
    {
        DebugConsole.Open();
        InitializeComponent();                               
    }

当我用上面的代码启动应用程序时,一切都如预期的那样工作。打开控制台窗口,并在控制台中打印出单词"test"。

但是,如果我将MainWindow()代码更改为:

    public MainWindow() //This gets executed when the application starts
    {
        Console.WriteLine("test1");
        DebugConsole.Open();
        InitializeComponent();                               
    }

并运行应用程序…

预期输出:控制台打开,它将包含两行文本

test1
test

实际输出:控制台打开,它根本不包含任何文本。事实上,我可以使用控制台。在代码中写入所有我想要的内容,控制台仍然为空。它只有在没有主机的情况下才有效。在打开控制台之前,使用WriteLine。

为什么会发生这种情况?我怎么修理它?

控制台没有显示打印输出

初始化控制台后打印。开关Console.WriteLine("test1")DebugConsole.Open()

编辑:

当您使用Console.Writeline而不初始化控制台时,我认为它返回NullStream()(就像您在Unix上将数据重定向为null一样),但是当您调用open时,您的写入方法使用真正的标准输出。因此,默认情况下使用的流是NullStream(),否则它就是标准输出。查看参考源