AllocConsole在Visual Studio中不打印

Bob*_*der 2 c# console visual-studio-2010

我想在调试程序时创建一个控制台窗口并在其上打印一些信息.VS 2010没有为我提供为程序设置不同输出类型的选项,具体取决于它是处于调试模式还是发布模式,因此我采用手动创建控制台窗口,如下所示:

[DllImport("kernel32.dll")]
public static extern Int32 AllocConsole();

static void Main()
{
#if DEBUG
    AllocConsole();
#endif
....
Run Code Online (Sandbox Code Playgroud)

弹出窗口打开一个控制台窗口,但没有任何内容写入它.我尝试了一堆其他的pinvoke(AttachConsole等......)什么也没做.然后我终于尝试在Visual Studio之外运行应用程序,并且控制台窗口工作.显然Visual Studio正在吃掉我所有的Console.WriteLines!

我怎样才能解决这个问题?

Dav*_*ray 5

遇到同样的问题,这里有一些代码,看起来在调用后为我恢复控制台输出AllocConsole:

    private static void OverrideRedirection()
    {
        var hOut = GetStdHandle(STD_OUTPUT_HANDLE);
        var hRealOut = CreateFile("CONOUT$", GENERIC_READ | GENERIC_WRITE, FileShare.Write, IntPtr.Zero, FileMode.OpenOrCreate, 0, IntPtr.Zero);
        if (hRealOut != hOut)
        {
            SetStdHandle(STD_OUTPUT_HANDLE, hRealOut);
            Console.SetOut(new StreamWriter(Console.OpenStandardOutput(), Console.OutputEncoding) { AutoFlush = true });
        }
    }
Run Code Online (Sandbox Code Playgroud)

P/Invokes如下:

    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern IntPtr GetStdHandle(int nStdHandle);

    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern bool SetStdHandle(int nStdHandle, IntPtr hHandle);

    public const int STD_OUTPUT_HANDLE = -11;
    public const int STD_INPUT_HANDLE  = -10;
    public const int STD_ERROR_HANDLE  = -12;

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern IntPtr CreateFile([MarshalAs(UnmanagedType.LPTStr)] string         filename,
                                           [MarshalAs(UnmanagedType.U4)]     uint           access,
                                           [MarshalAs(UnmanagedType.U4)]     FileShare      share,
                                                                             IntPtr         securityAttributes,
                                           [MarshalAs(UnmanagedType.U4)]     FileMode       creationDisposition,
                                           [MarshalAs(UnmanagedType.U4)]     FileAttributes flagsAndAttributes,
                                                                             IntPtr         templateFile);

    public const uint GENERIC_WRITE = 0x40000000;
    public const uint GENERIC_READ  = 0x80000000;
Run Code Online (Sandbox Code Playgroud)

  • 我不能对这个回复给予足够的支持;神奇的`CONOUT$` 和`CONIN$` 文件是Windows 中文档最差的部分之一,确实应​​该引起更多关注。可以在以下链接中找到关于它们的 MSDN 小文档:https://msdn.microsoft.com/en-us/library/windows/desktop/ms682075(v=vs.85).aspx (3认同)