246

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?

Timwi
  • 65,159
  • 33
  • 165
  • 230

10 Answers10

358

Just go to the application's Properties and change the Output type from Console Application to Windows Application.

David Ferenczy Rogožan
  • 23,966
  • 9
  • 79
  • 68
Fahad
  • 3,733
  • 1
  • 14
  • 2
  • I feel like such a numpty, it seems so obvious when pointed out to me. I found this so hard to google. – Crouch Nov 26 '14 at 12:39
  • 17
    Even though this does not answer the OP's question, I really appreciate you giving this answer. It was exactly what I needed :) – kayleeFrye_onDeck Dec 17 '14 at 22:31
  • 9
    This is not solution, because this way window cannot be shown. – Michał Woliński Oct 18 '16 at 09:53
  • 8
    This is not a solution to what the poster asked. – KansaiRobot Nov 15 '16 at 08:41
  • 4
    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) – TheLegendaryCopyCoder Jan 19 '17 at 12:44
  • 1
    @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. – Julo Sep 05 '18 at 04:39
  • The trick was awesome to know about, it works nice and solved my problem (hard-hiding the console). Nevertheless let notice it is not the answer for the question. – David Silva-Barrera Aug 11 '21 at 10:45
  • 2
    The Console Window can be shown (and used) from *any* GUI app by using the AllocConsole API function. – JensG Sep 01 '22 at 09:30
332

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);
Timwi
  • 65,159
  • 33
  • 165
  • 230
  • 20
    The window still appears momentarily at the beginning. I guess there is no way around this, unless the application type is changed? – Ciaran Gallagher Aug 02 '11 at 14:40
  • 3
    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 Aug 11 '11 at 14:30
  • 9
    @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. – Timwi Aug 23 '12 at 17:11
  • Where do I use this code in the console application? – shawn Dec 12 '14 at 05:21
  • @shawn, the first two sections of the code you put before you want to hid/show the console. Then, the last section you put WHEN you want to hide and show. – Ahkam Nihardeen Mar 17 '15 at 08:39
  • @Timwi I can't kill the process when it is hidden. I try to "end task" in task manager, but this process appears again. How to close it? – Piotrek Nov 13 '15 at 19:32
  • @Ludwik11 In application's property, debug menu, uncheck -> "Enable Visual studio host process" and then save changes. – Sanket Patel Mar 28 '16 at 11:53
  • 10
    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. – KansaiRobot Nov 15 '16 at 09:11
  • `var handle = GetConsoleWindow();` or `IntPtr handle = GetConsoleWindow();` – DxTx Aug 18 '18 at 09:58
  • I woud suggest using an enum `enum WindowState : int { SW_HIDE = 0, SW_SHOW = 5 }` as parameter. ( see [doc](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow) for all possible values) – AntiHeadshot Dec 17 '19 at 11:51
  • It could be noted that this **will not work** for MacOS or Linux – DJ001 Jan 15 '21 at 12:23
27

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

Maiko Kingma
  • 929
  • 3
  • 14
  • 29
  • 10
    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? – Ronny D'Hoore May 24 '20 at 11:16
23

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.

Sasha
  • 8,537
  • 4
  • 49
  • 76
  • 42
    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. – Janis F Jul 03 '13 at 06:27
  • also `TopShelf` allows you to run `Consoles` as a service and this breaks that – Mr Heelis Apr 17 '18 at 16:01
  • If you want standard out to be available in a console, then you will need a console, simple as that. – Totte Karlsson Feb 20 '20 at 23:02
  • Some GUI applications can still be run from console, and it is nice to display output there - in the console. – GTAE86 Dec 14 '20 at 19:53
13

See my post here:

Show Console in Windows Application

You can make a Windows application (with or without the window) and show the console as desired. Using this method the console window never appears unless you explicitly show it. I use it for dual-mode applications that I want to run in either console or gui mode depending on how they are opened.

Community
  • 1
  • 1
Anthony
  • 901
  • 7
  • 3
  • 1
    Excellent! the easiest way to hide console is to change project type to Windows application. –  Nov 28 '16 at 09:18
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.

N T
  • 438
  • 6
  • 11
7

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
    }
}
The Jas1001
  • 73
  • 1
  • 2
  • 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();" – MoonLight Oct 26 '22 at 10:42
2

If you don't want to depends 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());
rag
  • 59
  • 1
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";
ScilsOff
  • 11
  • 2
0

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

Chan Tzish
  • 1,108
  • 9
  • 7