Tuesday, August 21, 2007

Hide console window in console application

          As you all know when you execute an console application it will load command prompt and shows out put. There are amny situation in which you do not want this console window to be dislayed to user while your application runing. You can do that by calling some unmanaged functions. I have used following method to do that which is posted by Brendan Grant on MSDN.

using System.Runtime.InteropServices;

[DllImport("user32.dll")]
public static extern IntPtr
FindWindow(string lpClassName, string lpWindowName);

[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

IntPtr hWnd = FindWindow(null, title);

 if (hWnd != IntPtr.Zero)
 {
       if (!visible)
          //Hide the window                    
          ShowWindow(hWnd, 0); // 0 = SW_HIDE               
       else
          //Show window again                   
          ShowWindow(hWnd, 1); //1 = SW_SHOWNORMA          
}

Fig - (1) Code to hide console window in console application

Happy Programming !!!

8 comments:

Unknown said...

This code works but the problem is it still shows the console window for a fraction of time before closing it.

Anonymous said...

All you have to do is change the output type to a Windows Application rather than a Console Application. This is stop the console window from showing when running the application.

There is no need for all this code? What a load of rubbish, this doesn't even do the job properly.

Anonymous said...

Daniel Coe, you are a LEGEND :)

Anonymous said...

But what if you want to change the output type programatically.

Anonymous said...

But what if you want to change the output type programatically.

Anonymous said...

best solution is in project property set out type to window application. It works well for me.---vinay

Anonymous said...

I set Output type to "Windows" and it worked for me.
Thanks alot :)

Anonymous said...

How to hide multiple windows of same name