Hide Console Window in C#

I just made a silent application to check how much time my brother stay on his computer. But, I needed to make an application that doesn’t show any window. Now, I show you my personal solutions to do this for the Console Application Projects and for the Windows Forms Application Projects.

#
 
Console Application Projects

We must find the handle of the console window, and then hide it using the ShowWindow API. Search this handle, is usually done with the FindWindow API that look only the window title. But this is a bad way to do this. On the contrary, I used a .NET property:

System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
Now, I want to show you a simple program that use this property. Create a new Console Application project and call it MyHideConsole, now past this code to 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

This time, it is quite simple. To have a silent application you just don’t show any window! The main form is called in the main function, you must just remove this line:

Application.Run(new MyForm());

6 responses to “Hide Console Window in C#

  1. Eastwood

    Peferct shot! Thanks for your post!

  2. gab

    how will you reshow the console again?

    1. miro.mannino

      just recall the ShowWindow with the value 5 (i.e. SW_SHOW) instead of 0 (i.e. SW_HIDE)

  3. Melika

    thank you so much! that simple program help me greatly! thanks!

  4. Sameh

    While(true) may enter your application to an endless loop

    1. miro.mannino

      Ehehe yes of course it does. It was just as an example! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *