AttachConsole(-1), but Console.WriteLine won't output to parent command prompt?

23

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.

.net
winapi
pinvoke
console-application
asked on Stack Overflow Nov 8, 2011 by Merlyn Morgan-Graham • edited May 23, 2017 by Community

12 Answers

14

This is how I do it in Winforms. Using WPF would be similar.

static class SybilProgram
{
    [STAThread]
    static void Main(string[] args)
    {
        if (args.Length > 0)
        {
            // Command line given, display console
            if ( !AttachConsole(ATTACH_PARENT_PROCESS) )  // Attach to a parent process console (-1)
                AllocConsole(); // Alloc a new console if none available


            ConsoleMain(args);
        }
        else
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());  // instantiate the Form
        }
    }

    private static void ConsoleMain(string[] args)
    {
        Console.WriteLine("Command line = {0}", Environment.CommandLine);
        for (int ix = 0; ix < args.Length; ++ix)
            Console.WriteLine("Argument{0} = {1}", ix + 1, args[ix]);
        Console.ReadLine();
    }

    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    private static extern bool AllocConsole();

    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    private static extern bool AttachConsole(int pid);
}
answered on Stack Overflow Nov 8, 2011 by Cheeso • edited Jan 16, 2021 by Ian Boyd
1

I cannot see any significant difference between our implementations. For what it is worth, below is what I have in my application and it works fine. I also create a sample WPF application and it also worked fine.

I suspect that your issue is elsewhere. Sorry I couldn't be more help.

[STAThread]
public static void Main()
{            
    AttachProcessToConsole();    
}

private static void AttachProcessToConsole()
{
    AttachConsole(-1);
}

// Attaches the calling process to the console of the specified process.
// http://msdn.microsoft.com/en-us/library/ms681952%28v=vs.85%29.aspx
[DllImport("Kernel32.dll")]
private static extern bool AttachConsole(int processId);
answered on Stack Overflow Nov 8, 2011 by Dennis
1

Had the same problem and it appears that when running cmd.exe in Administrator mode AttachConsole() call succeeds but Console.Write() and Console.WriteLine() don't work. If you run cmd.exe normally (non-admin) everything seems to work fine.

answered on Stack Overflow Jan 23, 2013 by user2002173 • edited Jan 23, 2013 by andr
1

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.

answered on Stack Overflow Nov 2, 2014 by Andrey Bobrov
0

I had a similar situation: could not get a Windows Application to output anything in the programmatically attached console. Eventually, it turned out that I was using Console.WriteLine once before AttachConsole, and that was tampering with everything that followed after.

answered on Stack Overflow Apr 20, 2012 by Lucian Voinea
0

+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.

answered on Stack Overflow Nov 19, 2012 by takrl • edited May 23, 2017 by Community
0

I was suffering from the same problem with my application's current version (targeting .NET 4.0) but am sure AttachConsole(-1) did work as expected in earlier versions (which targeted .NET 2.0).

I found that I could get console output as soon as I removed my (custom) TraceListener from my application's .exe.config file, even though I don't know why yet.

Perhaps this is what's swallowing your console output as well...

Update

In fact I had a Console.WriteLine() in my custom trace listener's c'tor which was messing things up. After removing this line, console output after AttachConsole(-1) went back to normal.

answered on Stack Overflow Mar 25, 2013 by user2206916 • edited Mar 25, 2013 by user2206916
0

DETACHED_PROCESS and CREATE_NEW_CONSOLE is the problem here.
see https://stackoverflow.com/a/494000/883015

answered on Stack Overflow Sep 26, 2013 by Joe DF • edited May 23, 2017 by Community
0

Same problem here. I was using gflags.exe, (part of Debugging Tools for Windows) to attach a commandline WPF application to vsjitdebugger.exe (See this post). As long as my application was coupled with vsjitdebugger.exe, no output was written to the console.

From the moment I detached my application, output to the console, from where I launched my application, was restored.

answered on Stack Overflow Dec 27, 2016 by Kurt Van den Branden • edited May 23, 2017 by Community
0

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.

answered on Stack Overflow Jun 1, 2017 by nishanh • edited Jun 1, 2017 by nishanh
0

[This addresses the intended use of the question rather than being a direct answer to the question as stated.]

When wanting to write a dual-mode app (console or GUI depending on parameters), the method that I prefer is to compile as a Console app and then FreeConsole() if it turns out that GUI mode is desired.

Advantage: parent console processes will properly wait for the app to finish when running in console mode, and not wait for it in GUI mode. (Although note that some other calling apps might continue to wait for it.) In particular you won't get the next command prompt mixed up with app output text, which is what happens when you use the AttachConsole method.

Disadvantage: when running the GUI version from a non-console parent, a console window will briefly appear (until FreeConsole() is executed).

Another alternative method (that Microsoft seems to prefer) is to compile App.exe as GUI and App.com as console (despite the suffix, this is just a renamed .exe), where the latter simply calls the former, passing on all the command line args, streams, and exit codes.

answered on Stack Overflow Apr 22, 2020 by Miral
0

The problem is that to output to the console you need use a handle with the value 1. The "correct" way to get that value is to call GetStdHandle(STD_OUTPUT_HANDLE), but if you haven't got a console, that function returns 0. (On earlier release you always got 1.) The run time apparently calls GetStdHandle during startup, and even after you call AttachConsole your Console stream still has an output handle of 0. You need to call GetStdHandle(STD_OUTPUT_HANDLE) (which will return 1) after AttachConsole and then use the handle returned from that.

answered on Stack Overflow Jul 31, 2020 by Dave Bush

User contributions licensed under CC BY-SA 3.0