#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)
        {
            Utils.AttachConsole();
            Console.Write($"Starting service ");
            var instance = factory();
            Console.WriteLine(instance.GetType().Name);
            //Invoke start Method
            Console.WriteLine("Press [ENTER] to exit");
            Console.ReadLine();
            //Stop service
        }
        else
        {
            ServiceBase.Run(factory());
        }
    }

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 };
        Console.SetOut(writer);
    }

and the Interop includes:

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

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

    [DllImport("kernel32.dll")]
    internal static extern IntPtr GetStdHandle(uint nStdHandle);

    [DllImport("kernel32.dll")]
    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 🙁

EDIT:
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.