【问题标题】:Console not showing printed output控制台不显示打印输出
【发布时间】:2014-09-06 22:00:37
【问题描述】:

我在我的 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

实际输出:控制台打开,它根本不包含任何文本。事实上,我可以在代码中使用我想要的所有 Console.WriteLine 并且控制台保持为空。只有在没有使用 Console.WriteLine 的情况下,它才会在控制台打开之前起作用。

为什么会这样?我该如何解决?

【问题讨论】:

  • 我能够创建一个包含您的代码的小型控制台应用程序,并且我得到了您期望的输出(第一行为 test1,第二行为 test)。您是否尝试过在 MainWindow() 方法上设置断点以确保它按预期执行?我会尝试单步执行以逐行查看输出。

标签: c# wpf console .net-4.5


【解决方案1】:

在初始化控制台后打印。切换Console.WriteLine("test1")DebugConsole.Open()

编辑: 当您在不初始化控制台的情况下使用Console.Writeline 时,我认为它会返回NullStream()(就像在Unix 上将数据重定向到null 时一样),但是当您调用open 时,您的写入方法会使用真正的标准输出。 所以默认使用的流是 NullStream() 否则它是标准输出。 检查reference source

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-04
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    • 1970-01-01
    相关资源
    最近更新 更多