Hide Console Window in C# Console Application
- Hi, How can I hide the console window in my Console Application project ?
Answers
Try this:
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);
...
//Sometimes System.Windows.Forms.Application.ExecutablePath works for the caption depending on the system you are running under.
IntPtr hWnd = FindWindow(null, "Your console windows caption"); //put your console window caption here
if(hWnd != IntPtr.Zero)
{
//Hide the window
ShowWindow(hWnd, 0); // 0 = SW_HIDE
}
if(hWnd != IntPtr.Zero)
{
//Show window again
ShowWindow(hWnd, 1); //1 = SW_SHOWNORMA
}
All Replies
You can Pinvoke a call to FindWindow() to get a handle to your window and then call call ShowWindow() to hide the window.
Before pasting some code though I’ve got to ask though... if you do not want your window visible, have you considered building your app into a Windows Service that will always be hidden from view?
- I know windows service writing. but I want to hide Console window (black window).
Try this:
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);
...
//Sometimes System.Windows.Forms.Application.ExecutablePath works for the caption depending on the system you are running under.
IntPtr hWnd = FindWindow(null, "Your console windows caption"); //put your console window caption here
if(hWnd != IntPtr.Zero)
{
//Hide the window
ShowWindow(hWnd, 0); // 0 = SW_HIDE
}
if(hWnd != IntPtr.Zero)
{
//Show window again
ShowWindow(hWnd, 1); //1 = SW_SHOWNORMA
}
- I m writing a Windows Console application in C#. Where should I put this code ? main class or somewhere else ?
Don't put ReadLine();
Hope this helps,
Hi,
When we run a external process using Process Class console window(black window) displayed.
I don want to display that black window than wat shd i do for that?
- Check out ProcessStartInfo.CreateNoWindow
Hello,
Thanks in advance to anyone that can help.
The mini-project i'm doing (while the development server is down) is to build a Command Prompt (basically) with some text formatting abilities. I might go wild and try to throw in some more groovy windows on the application and maybe even an autocomplete. This is all for a buddy at work.
I have managed to hide the black console window and had the output stream fill a label on a Windows application. As I run the process ("cmd", "/c dir") the label fills up nicely, but I can't seem to find a way to continue running commands as you would normally through the prompt while keeping the same process.
Yes I am relatively new to this, apologies if I have missed something obvious.
Timmy
- Well I managed to hide the console in VS2005 C# Express by changing the output type under Application in the project properties to Windows Application.
- This is exactly right, Thanks Brandon for this usefull post.Below is the exact C# code for showing/hiding the method in a Console Application.
using System.Runtime.InteropServices;
namespace MyConsoleApp {
class Program {
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName,string lpWindowName);
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[STAThread()]
static void Main(string[] args)
{
Console.Title = "MyConsoleApp";
if (args.StartWith("-w"))
{
// hide the console window
setConsoleWindowVisibility(false, Console.Title);
// open your form
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);Application.Run( new frmMain() );
}
// else don't do anything as the console window opens by default
}
public static void setConsoleWindowVisibility(bool visible, string title)
{
// below is Brandon's code
//Sometimes System.Windows.Forms.Application.ExecutablePath works for the caption depending on the system you are running under.
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
}
}
}
} I get this compiler response:
Microsoft (R) Visual C# 2005 Compiler version 8.00.50727.42
for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727
Copyright (C) Microsoft Corporation 2001-2005. All rights reserved.fatal error CS0009: Metadata file 'c:\WINDOWS\system32\user32.dll' could not be
opened -- 'An attempt was made to load a program with an incorrect
format. 'what is this incorrect format it speaks of?
- I have written and tested this code in VS.NET 2005 Pro , WindowsXP SP2.
It appears that you may have a .net framework or VisualStudio install corruption.
Check that you can add a reference to this dll manually (does the .tlb file creates properly in /bin/debug ?); then try to clean then rebuild solution.
Have you somewhat patched your user32.dll library or are you using a special software that may have patched it (for XP themes, etc); I'm just guessing there... cos if so, maybe that the C# compiler can't link with this patched version .
The code is right, we've deployed our app that uses it throughout our LAN...
If it's still not working, check Google for this error code and message...
Good luck
Mat set the ProcessInfo Object 's property name CreateNoWindow to true;
ProcessInfo prcInfo = new ProcesInfo("cmd.exe","/c dir");
prcInfo.CreateNoWindow = true;
What worked for me was -
Create a Windows Application in Visual Studio.
Inside of the Program.cs instead of running a windows application/Form - instead just instantiate your class there.
Normally after creating a Windows Application in VS your main method in the Program.cs file will look something like this:
Application
.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1());I comment out that and in its place I put my class that I want to instantiate and run - like this:
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false); //Application.Run(new Form1()); Class1 myClass = new Class1();myClass.RunThisPuppy();
Hope this helps!
This almost works. You also need:
prcInfo.UseShellExecute = false;
Set Project Properties> Application > output Type: to "Windows Application"
Thanks and Regards
Amar Chaudhary- Proposed As Answer bySomnath Paul Saturday, May 31, 2008 5:36 AM
- Thanks Amar, that tip worked in a flash :-)
Regards,
Vinod Jai Nair
Vinod J Nair - This worked for us. We converted a Windows Application to Console. We needed it to run as console when a command line argument gets passed. Else it should work as normal windows app.
Thanks - Ashik_007, would you be kind enough to specify which advice worked. My task is, I think, identical to yours: Show a normal Windows Forms interface, unless a command line parameter is passed, in which case use console output only.
I can easily create a new console output using the Win32 function AllocConsole, but I would prefer the output of the program to be displayed within the existing command console if one exists.
Thanks - Thanks Sibcool, your advice worked !! (Which is the same as Amar's advice later on). The problem I was facing is, when I was running any external application inside my program it was not showing the console window because I had already done ProgramInfo.UseShellExecute = false; But running my application itself from outside was causing a window. (Like as a scheduled task etc.)
Ben, I don't know if I understand it properly, but your console application will still take command line arguments if you change the output type to 'Windows Application'. My application works with a thousand type of arguments and it is now a windows application. :)
Piyush Soni,Tata Consultancy Services, India just to say thanks to Amar and sibcool 's contributions! Rebuilding the application into a windows service could have taken some time. i have battling to solve this. You saved my day!
SA, Joburg- Thanks a lot to Amar and Sibcool. That's exactly what i was looking for.
Now IT Wiz, SA Joburg Thanx Amar..
Its working ...- Hi,
This code works with few changes to it.
But, when my application runs, it starts and stops immediately. The console window flashes for a moment and goes off, and the application stops running.
Could anybody help me with this ..what could be the possible solution for it...??
Thanks in advance,
Abhinav - Either run it from within an existing command window, or add a line like this to the end of Main():
Console.ReadLine(); - Thanks for the quick response. The thing is, i really dont want the console window to show up...but the solution should be running.
My point here is, I want to keep the application running in the background, without any window coming up.
Here is the code that i copied from above with few modifications :
class Program
{
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[STAThread()]
static void Main(string[] args)
{
Console.Title = "MyHiddenConsole";
string arg;
for (int i = 0; i < args.Length; i++)
{
arg = args[i];
if (arg.StartsWith("-w"))
{
setConsoleWindowVisibility(false, Console.Title);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form());
Application.Run();
}
}
}
public static void setConsoleWindowVisibility(bool visible, string title)
{
IntPtr hWnd = FindWindow(null,title);
if(hWnd!=IntPtr.Zero)
{
if(!visible)
ShowWindow(hWnd,0);
else
ShowWindow(hWnd, 1);
}
}
}
WIth this code, it runs, starts and stops immediately..! Console window flashes and goes back.
How do i keep the application running with no window at all?
Thanks.
- GO to your Console Application Project Properties window
Select 'Application'
Select the value 'Windows Application' for the 'Output Type' dropdown.
Now run.. You will not see the console window Sometimes the FindWindow approach of getting the window handle doesn't work, especially if you have multiple instances of the same application running - instead, you might want to use:
Process.GetCurrentProcess().MainWindowHandle;- Sibcool's idea is really cool. I used it and it is working and fantastic thing is that no code is required.
- I've ran plenty of forms applications without showing the form, but I started my project out as a console app thinking it would be smaller or use less resources or something like that. After searching everywhere on how to not bring up the console window with no luck, I ended up here. The solution is that simple, just use a forms app and don't show the form. I'm not sure if it uses more memory or anything, but I'll take it instead of the headache I got trying to find the answer for a console window.I bet it's not using anything more though because the Enable Application Framework is unchecked to allow the use of a Sub Main() (I'm using vb.net) and I don't even have a form, it's just a module.Well thanks for the reminder to just do it this way...
- You know - unless you are using a client earlier then Windows 2000, you don't need to use the old FindWindow approach:
[DllImport("kernel32"] public static extern IntPtr GetConsoleWindow(); ... IntPtr hConsole = GetConsoleWindow(); If (IntPtr.Zero != hConsole) { // we have a console associated. }HTH
Tom Shelton - In my consol application, i am trying to catch the windows shut down , cntrl+c press etc. After i made the project to widows application , then the consol window is not coming up. But i am not able to catch the cntrl+C press . Here is my code
Initally i was able to catch ctrl+C , though the window shutdown is not detectedpublic class ConsoleCtrl { public enum ConsoleEvent { CTRL_C = 0, // From wincom.h CTRL_BREAK = 1, CTRL_CLOSE = 2, CTRL_LOGOFF = 5, CTRL_SHUTDOWN = 6 } public delegate void ControlEventHandler(ConsoleEvent consoleEvent); public event ControlEventHandler ControlEvent; public ConsoleCtrl() { SetConsoleCtrlHandler(new ControlEventHandler(Handler), true); } private void Handler(ConsoleEvent consoleEvent) { if (ControlEvent != null) ControlEvent(consoleEvent); } [DllImport("kernel32.dll")] static extern bool SetConsoleCtrlHandler(ControlEventHandler e, bool add); } private static void Logger(ConsoleCtrl.ConsoleEvent consoleEvent) { Console.WriteLine(consoleEvent); count++; if (count == 10) { Environment.Exit(0); } }
- makdutakdu,
I was having the same problem and I couldn't any help online about this.
I finally found a workaround today.
- Leave your project as Console Application like it was.
- Create another Console Application project and call it "[Your App] Launcher".
- Change its Output setting as Windows Application.
- Open the Program.cs, it should look like this:
That's the only workaround I found.class Program { static void Main(string[] args) { Process proc = new Process(); proc.StartInfo.CreateNoWindow = true; proc.StartInfo.UseShellExecute = false; proc.StartInfo.FileName = @"[Your other console app]"; proc.Start(); } }
Hope it works for you!
Paulo- Proposed As Answer byMr. Javaman Friday, January 29, 2010 6:55 PM
- Thanks for the method. I will give this a try
- Hello makdutakdu,
No need to write any code. Just go the "Project--Properties--Application Tab" and then from the "Output type" drop-down, just select "Windows Application". That's it. It will never flash any black window for you anymore.

