none
Hide Console Window in C# Console Application

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

             }

     

    Wednesday, August 16, 2006 4:55 PM

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?

    Wednesday, August 16, 2006 4:32 PM
  • I know windows service writing. but I want to hide Console window (black window).
    Wednesday, August 16, 2006 4:42 PM
  • 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

             }

     

    Wednesday, August 16, 2006 4:55 PM
  • I m writing a Windows Console application in C#. Where should I put this code ?  main class or somewhere else ?
    Wednesday, August 16, 2006 5:17 PM
  • Don't put ReadLine();

    Hope this helps,

    Friday, August 18, 2006 3:47 PM
  • 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?

    Tuesday, April 17, 2007 10:32 AM
  • Check out ProcessStartInfo.CreateNoWindow

    • Proposed as answer by mikem4a1 Tuesday, June 11, 2013 7:13 PM
    • Unproposed as answer by mikem4a1 Tuesday, June 11, 2013 7:13 PM
    Tuesday, April 17, 2007 10:48 AM
  • 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

    Tuesday, April 17, 2007 3:15 PM
  • 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.
    • Proposed as answer by Zippanova Tuesday, May 24, 2011 9:31 PM
    Friday, May 18, 2007 7:58 AM
  • 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          
                 }       
            }
        }
    }
    Wednesday, June 13, 2007 2:00 AM
  • 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?

     

    Wednesday, June 13, 2007 7:55 PM
  • 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

    Saturday, June 16, 2007 3:11 PM
  • set the ProcessInfo Object 's property name CreateNoWindow  to true;

     

    ProcessInfo prcInfo = new ProcesInfo("cmd.exe","/c dir");

    prcInfo.CreateNoWindow = true;

    Wednesday, June 20, 2007 11:03 AM
  • 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!

     

    Friday, October 19, 2007 7:19 PM
  • This almost works. You also need:

     

     prcInfo.UseShellExecute = false;

     

     

    • Proposed as answer by Umar Kashmiri Friday, October 08, 2010 7:08 AM
    Wednesday, March 26, 2008 7:53 PM

  • Set Project Properties> Application > output Type: to "Windows Application"


    Thanks and Regards
    Amar Chaudhary
    • Proposed as answer by Somnath Paul Saturday, May 31, 2008 5:36 AM
    Friday, May 02, 2008 5:49 AM
  • Thanks Amar, that tip worked in a flash :-)

    Regards,
    Vinod Jai Nair
    Vinod J Nair
    Saturday, May 31, 2008 12:09 AM
  • 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
    Thursday, June 05, 2008 5:26 AM
  • 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
    Tuesday, August 05, 2008 8:35 PM
  • 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
    Monday, May 11, 2009 4:00 PM
  • 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

     

    Tuesday, June 30, 2009 4:46 PM
  • Thanks a lot to Amar and Sibcool. That's exactly what i was looking for.

    Now IT Wiz, SA Joburg
    Tuesday, June 30, 2009 4:49 PM
  • Thanx Amar..
    Its working ...

    Wednesday, July 29, 2009 9:26 AM
  • 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
    Friday, August 14, 2009 6:32 PM
  • Either run it from within an existing command window, or add a line like this to the end of Main():

    Console.ReadLine();
    Friday, August 14, 2009 6:41 PM
  • 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.

     
    Friday, August 14, 2009 7:00 PM
  • 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
    Wednesday, August 26, 2009 1:59 PM
  • 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;

    Friday, September 25, 2009 3:46 PM
  • Sibcool's idea is really cool. I used it and it is working and fantastic thing is that no code is required.
    Saturday, December 12, 2009 8:33 AM
  • 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...

    Monday, January 04, 2010 3:23 AM
  • 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
    Monday, January 04, 2010 4:39 AM
  • 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
     public 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);
                }
            }
    Initally i was able to catch ctrl+C , though the window shutdown is not detected
    Thursday, January 14, 2010 7:24 AM
  • 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:

    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();
            }
        }
    That's the only workaround I found.
    Hope it works for you!

    Paulo
    • Proposed as answer by Mr. Javaman Friday, January 29, 2010 6:55 PM
    Thursday, January 21, 2010 9:46 PM
  • Thanks for the method. I will give this a try
    Wednesday, January 27, 2010 11:19 AM
  • 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.
    Saturday, January 30, 2010 8:40 AM
  • Just Try this.

     

    oProcess.StartInfo.CreateNoWindow = true;
    oProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

    Sunday, March 21, 2010 2:57 PM
  • Its so simple.

    Jst go to the Project tab in Visual studio IDE.

    Select Properties of the solution "ur solution name Properties"

    Then select Application tab (which is selected default).

    In that select the Output type dropdown colum it will be console application, you need to select Windows Application.

    Now clean the solution.

    Build the solution.

    Debug.

    The console window doesn't appears now.

    Enjoy.

    Have a cup cake or chocs.

    go to bed.

    Have sweet dreams about your appraisal.

    Wednesday, March 23, 2011 7:51 AM
  • Raja...perfect.

    I use a lot of sqlcmd scripts and the results were ultimate ugliness until.

    oProcess.StartInfo.CreateNoWindow = true;
    oProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

    Like much of this, you just have to know the magic words.

     

    Thanks

    Wednesday, August 03, 2011 7:35 PM
  • FindWindow is cool...

    but we can use Process type:

    ShowWindow((int)Process.GetCurrentProcess().MainWindowHandle, 0);

    • Proposed as answer by dbooksta Tuesday, September 04, 2012 1:04 PM
    Tuesday, September 04, 2012 5:47 AM
  • This is the exact code to use.  Unfortunately, you do see the console window for a brief moment before it is hidden, but this is the way to hide it.  Hope this helped.

    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);

     

                                //Your Code Goes Here

              

            }

        }

    }
    Saturday, November 17, 2012 3:44 AM