How to hide the Console Application in C#

By FoxLearn 6/8/2024 3:07:47 AM   9.07K
To hide a console application in C#, you can utilize the ShowWindow function from the user32.dll library to hide the console window programmatically.

How to hide the Console Application in C#

Open your Visual Studio, then Click New Project, then select Visual C# on the left, then Windows and then select Console Application. Name your project "HideConsole" and then click OK

Adding code to Program class as shown below.

[DllImport("Kernel32.dll")]
private static extern IntPtr GetConsoleWindow();
[DllImport("User32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int cmdShow);

static void Main(string[] args)
{
    Console.WriteLine("Press any key to hide me.");
    Console.ReadKey();
    // Get the handle to the console window
    IntPtr hWnd = GetConsoleWindow();
    if (hWnd != IntPtr.Zero)
    {
        // Hide the console window
        ShowWindow(hWnd, 0);
        Thread.Sleep(5000);//5s
        // Show the console window
        ShowWindow(hWnd, 1);
    }
    Console.ReadKey();
}

This code hides the console window immediately after the program starts running. However, the console window is still running in the background. If you need to hide the window at a specific point in your application, you can call ShowWindow(hWndConsole, SW_HIDE) at that point.

VIDEO TUTORIAL

Related