252

I googled around for information on how to hide one’s own console window. Amazingly, the only solutions I could find were hacky solutions that involved FindWindow() to find the console window by its title. I dug a bit deeper into the Windows API and found that there is a much better and easier way, so I wanted to post it here for others to find.

How do you hide (and show) the console window associated with my own C# console application?

9 Answers 9

371

If you just want the application to run in headless mode (without a GUI) altogether, go to the application's Properties menu in Visual Studio via Project --> <Project Name> Properties and change the Output type from Console Application to Windows Application:

Screenshot of application properties window showing the Output type of "Windows Application" selected

Sign up to request clarification or add additional context in comments.

4 Comments

This is not solution, because this way window cannot be shown.
While great, this solution does not allow you to programmatically control when to show and hide the console. Lets say you accept a console param which when set you want to hide your console (i.e. silent mode, verbose=false)
@Lenny: This works because GUI application do not open a console window. To show a Window each GUI application creates a window and then show it. Since the former console application lack the code to create window, no window will be displayed. I use this principle in another "Alarm clock" (timer) type application. First I show a "set parameters window", the close the window (not hide, but close). And as timer elapses a new window is displayed.
The Console Window can be shown (and used) from any GUI app by using the AllocConsole API function.
345

Here’s how:

using System.Runtime.InteropServices;

[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();

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

const int SW_HIDE = 0;
const int SW_SHOW = 5;

var handle = GetConsoleWindow();

// Hide
ShowWindow(handle, SW_HIDE);

// Show
ShowWindow(handle, SW_SHOW);

13 Comments

The window still appears momentarily at the beginning. I guess there is no way around this, unless the application type is changed?
It would be nice if there was a way around that. That way I can show the console when I am in debug mode, but just run my program and exit (with no window) when I am in normal run mode.
@Vaccano: It is possible to make your application a console application in Debug mode only by editing the csproj file manually. Visual Studio doesn’t have GUI to do this, but it will honour the setting if you edit the csproj file correctly.
This is a very nice answer but I might add that one more option to add is const int SW_SHOWMINIMIZED = 2; and then ShowWindow(handle, SW_SHOWMINIMIZED); In this way the console starts not hidden , just minimized.
With the Windows Terminal application, SW_HIDE only minimizes the window (which means it is identified as the console window...). There are other posts suggesting a call to SetForegroundWindow followed by getting a new handle from GetForegroundWindow is the fix, but that doesn't work either.
|
28

You could do the reversed and set the Application output type to: Windows Application. Then add this code to the beginning of the application.

[DllImport("kernel32.dll", EntryPoint = "GetStdHandle", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr GetStdHandle(int nStdHandle);

[DllImport("kernel32.dll", EntryPoint = "AllocConsole", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int AllocConsole();

private const int STD_OUTPUT_HANDLE = -11;
private const int MY_CODE_PAGE = 437;
private static bool showConsole = true; //Or false if you don't want to see the console

static void Main(string[] args)
{
    if (showConsole)
    {
        AllocConsole();
        IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
        Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle(stdHandle, true);
        FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);
        System.Text.Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE);
        StreamWriter standardOutput = new StreamWriter(fileStream, encoding);
        standardOutput.AutoFlush = true;
        Console.SetOut(standardOutput);
    }

    //Your application code
}

This code will show the Console if showConsole is true

1 Comment

It indeed shows the console with a blinking cursor, but neither Console.WriteLine("text") nor standardOutput.WriteLine("text") shows anything in my case. Is something missing?
22

Why do you need a console application if you want to hide console itself? =)

I recommend setting Project Output type to Windows Application instead of Console application. It will not show you console window, but execute all actions, like Console application do.

3 Comments

Because there might come a time when I do actually want to show it. Like, the console application tries to perform stuff and doesn't bother anyone aslong as it is successful. If not, it pops up and offers me a CLI.
also TopShelf allows you to run Consoles as a service and this breaks that
If you want standard out to be available in a console, then you will need a console, simple as that.
11

"Just to hide" you can:

Change the output type from Console Application to Windows Application,

And Instead of Console.Readline/key you can use new ManualResetEvent(false).WaitOne() at the end to keep the app running.

1 Comment

This appears to repeat the answer posted 7 years prior: stackoverflow.com/questions/3571627/… please only post new answers if you have new solutions to provide.
9

Following from Timwi's answer, I've created a helper class to wrap the needed code:

using System;
using System.Runtime.InteropServices;
static class ConsoleExtension {
    const int SW_HIDE = 0;
    const int SW_SHOW = 5;
    readonly static IntPtr handle = GetConsoleWindow();
    [DllImport("kernel32.dll")] static extern IntPtr GetConsoleWindow();
    [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd,int nCmdShow);

    public static void Hide() {
        ShowWindow(handle,SW_HIDE); //hide the console
    }
    public static void Show() {
        ShowWindow(handle,SW_SHOW); //show the console
    }
}

1 Comment

for those who don't know how to use this, simply add this class, and call it within your main code like this, "ConsoleExtension.Hide();" or to show "ConsoleExtension.Show();"
2

If you don't want to depend on window title use this :

[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
IntPtr h = Process.GetCurrentProcess().MainWindowHandle;
ShowWindow(h, 0);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormPrincipale());

1 Comment

we have to give full path of dll file in DllImport("fullPath") /
1

To change the Output type from Console Application to Windows Application when using csc compiler add -target:winexe to the csc.exe command like that: C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe -out:example.exe -target:winexe example.cs

Comments

0

If you don't have a problem integrating a small batch application, there is this program called Cmdow.exe that will allow you to hide console windows based on console title.

Console.Title = "MyConsole";
System.Diagnostics.Process HideConsole = new System.Diagnostics.Process();
HideConsole.StartInfo.UseShellExecute = false;
HideConsole.StartInfo.Arguments = "MyConsole /hid";
HideConsole.StartInfo.FileName = "cmdow.exe";
HideConsole.Start();

Add the exe to the solution, set the build action to "Content", set Copy to Output Directory to what suits you, and cmdow will hide the console window when it is ran.

To make the console visible again, you just change the Arguments

HideConsole.StartInfo.Arguments = "MyConsole /Vis";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.