Console.WriteLine() inside a Windows Service?

后端 未结 5 1850
广开言路
广开言路 2020-12-09 14:40

I am currently using TopShelf with a Console Application to create a Windows Service. When I run the code as a console application I use a few Console.WriteLine() to output

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-09 15:35

    Also want to display a help depending on command line.
    My solution is to open a new console.

    internal static class NativeMethods
    {
        [DllImport("user32.dll")]
        internal static extern bool SetForegroundWindow(IntPtr hWnd);
    
        [DllImport("user32.dll")]
        internal static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
    
        [DllImport("kernel32.dll")]
        internal static extern bool AllocConsole();
    
        [DllImport("kernel32.dll")]
        internal static extern IntPtr GetConsoleWindow();
    }
    
    public static void ShowWindow(IntPtr hWnd, ShowWindowCommand cmd = ShowWindowCommand.Restore)
    {
        NativeMethods.SetForegroundWindow(hWnd);
        NativeMethods.ShowWindowAsync(hWnd, (int)cmd);
    }
    
    public static void ShowConsoleWindow()
    {
        var handle = NativeMethods.GetConsoleWindow();
    
        if (handle == IntPtr.Zero)
            NativeMethods.AllocConsole();
        else
            ShowWindow(handle, ShowWindowCommand.Show);
    }
    

    ShowWindowCommand is just an enum built from here
    https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow

提交回复
热议问题