简体   繁体   中英

can we have project type as console application for Windows services?

can we have project type as console application for Windows services in .Net? Normally for windows service we have project type as Windows Application? And what is the need to do like this?

Yes, you can. Here difference between Console application and Windows Application is in Environment.UserInteractive property. But, it does not matter if you run Console Application as Windows Service :) So, no needs to select project type as Console Application.

But, if you need a Console for debugging you can add some code to show console for Windows Application:

internal static class ConsoleAllocator
{
    [DllImport(@"kernel32.dll", SetLastError = true)]
    static extern bool AllocConsole();

    [DllImport(@"kernel32.dll")]
    static extern IntPtr GetConsoleWindow();

    [DllImport(@"user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    const int SwHide = 0;
    const int SwShow = 5;


    public static void ShowConsoleWindow()
    {
        var handle = GetConsoleWindow();

        if (handle == IntPtr.Zero)
        {
            AllocConsole();
        }
        else
        {
            ShowWindow(handle, SwShow);
        }
    }

    public static void HideConsoleWindow()
    {
        var handle = GetConsoleWindow();

        ShowWindow(handle, SwHide);
    }
}

So, you'll have a console and no need to switch project type to Console Application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM