AttachConsole(-1), but Console.WriteLine won't

2019-03-08 20:28发布

If I have set my program to be a Windows Application, and used the AttachConsole(-1) API, how do I get Console.WriteLine to write to the console I launched the application from? It isn't working for me.

In case it is relevant, I'm using Windows 7 x64, and I have UAC enabled. Elevating doesn't seem to solve the problem though, nor does using start /wait.

Update

Some additional background that might help:

I've just discovered that if I go to the command prompt and type cmd /c MyProgram.exe, Then console output works. The same is true if I launch a command prompt, open a cmd.exe sub-process, and run the program from that sub-shell.

I've also tried logging out and back in, running from a cmd.exe launched from the start menu (as opposed to right-click -> command prompt), and running from a console2 instance. None of those work.

Background

I've read on other sites and in several SO answers that I can call the win32 API AttachConsole to bind my Windows Application to the console that ran my program, so I can have something that is "both a console application, and a Windows application".

For example, this question: Is it possible to log message to cmd.exe in C#/.Net?.

I've written a bunch of logic to make this work (using several other APIs), and I have gotten every other scenario to work (including redirection, which others have claimed won't work). The only scenario left is to get Console.WriteLine to write to the console I launched my program with. From everything I've read this is supposed to work if I use AttachConsole.

Repro

Here's a minimal sample - Note that the project is set to be a Windows Application:

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        if (!AttachConsole(-1))
        {
            MessageBox.Show(
                new Win32Exception(Marshal.GetLastWin32Error())
                    .ToString()
                );
        }

        Console.WriteLine("Test");
    }

    [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
    private static extern bool AttachConsole(int processId);
}
  • When I run this from a command prompt, I don't get an error, but I don't get any console output either. This is the problem
  • If I add extra message boxes anywhere in the execution flow of the app, the message box gets displayed. I expect this, so all good here.
  • When I run this from Visual Studio or by double clicking on it, a message box with an error is displayed. I expect this, so no worries here (will use AllocConsole in my real app).

If I call Marshal.GetLastWin32Error after the call to Console.WriteLine, I get the error "System.ComponentModel.Win32Exception (0x80004005): The handle is invalid". I suspect that attaching to the console is causing Console.Out to get messed up, but I'm not sure how to fix it.

10条回答
做自己的国王
2楼-- · 2019-03-08 20:51

Had the same problem. Everything worked great when I launched the built .exe file, but failed to run inside the VS.

Solution:

  1. Check Enable the VS Hosting process.
  2. Run VS as administrator.

Maybe this will help other people to fix this issue.

查看更多
劫难
4楼-- · 2019-03-08 20:58

+1

I had the same problem. Console output would not show up using various flavours of AllocConsole or AttachConsole.

Check if you have disabled Enable the visual studio hosting process in your project configuration. Enabling this option magically made all console messages appear as expected for me. I'm running VS2010 and .NET4, but this post suggests the 'feature' is still there in VS2012.

查看更多
The star\"
5楼-- · 2019-03-08 21:02

I had a similar problem. To compound things, I'm using WPF w/PRISM, so I need to suppress the creation of the 'Shell' as well when in "CLI Mode," but I digress...

This was the only thing that I found that finally worked

    [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool AttachConsole(int processId);

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

    public static void InitConsole()
    {
        const int STD_OUTPUT_HANDLE = -11;

        AttachConsole(-1);

        var stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
        var safeFileHandle = new SafeFileHandle(stdHandle, true);
        var fileStream = new FileStream(safeFileHandle, FileAccess.Write);
        var standardOutput = new StreamWriter(fileStream) { AutoFlush = true };
        Console.SetOut(standardOutput);
        Console.WriteLine();
        Console.WriteLine("As seen on StackOverflow!");
    }

All calls to Console.WriteLine() output to the CLI window after the call to InitConsole().

Hope this helps.

查看更多
登录 后发表回答