Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I hide a console window?

Question: I have a console program that shouldn't be seen. (It resets IIS and deletes temp files.)

Right now I can manage to hide the window right after start like this:

static void Main(string[] args)
{
    var currentProcess = System.Diagnostics.Process.GetCurrentProcess();
    Console.WriteLine(currentProcess.MainWindowTitle);

    IntPtr hWnd = currentProcess.MainWindowHandle;//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
    }

The problem is this shows the window for a blink of a second. Is there any constructor for a console program, where I can hide the window before it is shown?

And second:

I use

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

and I don't like the 32 in it. Is there any way to do this without DllImport ?
A .NET way ?

like image 461
Stefan Steiger Avatar asked Aug 25 '10 07:08

Stefan Steiger


People also ask

How do you hide a console window?

"SW_HIDE" hides the window, while "SW_SHOW" shows the window.

How do I hide the console window in python?

Simply save it with a . pyw extension. This will prevent the console window from opening.

How do I open console programs without a console window?

If you do not know what I am talking about: press Win+R, type “help” and press ENTER. A black console window will open, execute the HELP command and close again. Often, this is not desired. Instead, the command should execute without any visible window.


1 Answers

If you don't need the console (e.g. for Console.WriteLine) then change the applications build options to be a Windows application.

This changes a flag in the .exe header so Windows doesn't allocate a console session when the application starts.

like image 51
Richard Avatar answered Sep 30 '22 14:09

Richard