Show/Hide the console window of a C# console application

前端 未结 8 2273
走了就别回头了
走了就别回头了 2020-11-22 10:13

I googled around for information on how to hide one’s own console window. Amazingly, the only solutions I could find were hacky solutions that involved FindWindow()

8条回答
  •  鱼传尺愫
    2020-11-22 10:51

    You could do the reversed and set the Application output type to: Windows Application. Then add this code to the beginning of the application.

    [DllImport("kernel32.dll", EntryPoint = "GetStdHandle", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public static extern IntPtr GetStdHandle(int nStdHandle);
    
    [DllImport("kernel32.dll", EntryPoint = "AllocConsole", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public static extern int AllocConsole();
    
    private const int STD_OUTPUT_HANDLE = -11;
    private const int MY_CODE_PAGE = 437;
    private static bool showConsole = true; //Or false if you don't want to see the console
    
    static void Main(string[] args)
    {
        if (showConsole)
        {
            AllocConsole();
            IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
            Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle(stdHandle, true);
            FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);
            System.Text.Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE);
            StreamWriter standardOutput = new StreamWriter(fileStream, encoding);
            standardOutput.AutoFlush = true;
            Console.SetOut(standardOutput);
        }
    
        //Your application code
    }
    

    This code will show the Console if showConsole is true

提交回复
热议问题