How can I hide a console window?

前端 未结 4 488
小蘑菇
小蘑菇 2020-12-09 17:35

Question: I have a console program that shouldn\'t be seen. (It resets IIS and deletes temp files.)

Right now I can manage to hide the window right after start like

4条回答
  •  [愿得一人]
    2020-12-09 18:31

    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CloseHandle(IntPtr handle);
    
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool FreeConsole();
    
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
    private static extern IntPtr GetStdHandle([MarshalAs(UnmanagedType.I4)]int nStdHandle);
    
    // see the comment below
    private enum StdHandle
    {
        StdIn = -10,
        StdOut = -11,
        StdErr = -12
    };
    
    void HideConsole()
    {
        var ptr = GetStdHandle((int)StdHandle.StdOut);
        if (!CloseHandle(ptr))
            throw new Win32Exception();
    
        ptr = IntPtr.Zero;
    
        if (!FreeConsole())
            throw new Win32Exception();
    }
    

    See more console-related API calls here

提交回复
热议问题