CSharp Windows

Hide Console Window in C#

Blog post featured image

I recently developed a silent application to monitor my little brother’s computer usage without displaying any window. Here, I’ll share my approaches for both Console Application Projects and Windows Forms Application Projects.

Hiding the Console Window

The key is to find and hide the console window handle using the ShowWindow API. While the common approach is the FindWindow API focusing on the window title, it has its flaws. Instead, I use a .NET property:

System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;

Example Program

To demonstrate, create a new Console Application project named MyHideConsole. Then, copy and paste the following code into the Program.cs file:

using System;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace MyHideConsole{
    class Program{
        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        static void Main(string[] args){
            IntPtr h = Process.GetCurrentProcess().MainWindowHandle;
            ShowWindow(h, 0);

            while (true){
                System.Threading.Thread.Sleep(1);
                //Do what you want
            }
        }
    }
}

Windows Forms Application Projects

For Windows Forms applications, the process is simpler: just avoid displaying any window. Typically, the main form is invoked in the main function. To make the application silent, simply remove the following line:

Application.Run(new MyForm());