#StackBounty: #c# #visual-studio #winapi Can not attach console

Bounty: 50

I’m trying to attach a console to a Service if im running it from the debugger.
I’ve read up a couple of “working” solutions, but those seem not to really work. Here is he Code I use:

    public static void RunService(Func<ServiceBase> factory)
        if (Debugger.IsAttached)
            Console.Write($"Starting service ");
            var instance = factory();
            //Invoke start Method
            Console.WriteLine("Press [ENTER] to exit");
            //Stop service

Alloc Console is:

    public static void AttachConsole()
        var ret = NativeMethods.AllocConsole();
        IntPtr currentStdout = NativeMethods.GetStdHandle(NativeMethods.STD_OUTPUT_HANDLE);
        NativeMethods.SetStdHandle(NativeMethods.STD_OUTPUT_HANDLE, new IntPtr(7));
        TextWriter writer = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true };

and the Interop includes:

internal static class NativeMethods
    internal const uint STD_OUTPUT_HANDLE = 0xFFFFFFF5;

    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool AllocConsole();

    internal static extern IntPtr GetStdHandle(uint nStdHandle);

    internal static extern void SetStdHandle(uint nStdHandle, IntPtr handle);

What happens is, a console is created and attached, but there is no output. Can’t be to difficult, but I’m to dumb to see it 🙁

The Issue is Visual Studio, it is not the code “itself”. Without VS, I can get a console and receive the expected output there. There is some kind of redirection in VS, which I am looking to overcome here.

EDIT just for Hans – here is the “full code”

static void Main(string[] args)
    ServiceLauncher.RunService(() => new FactoryService();

The project is set to application type windows.

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.