Show/Hide the console window of a C# console application
Asked Answered
I

10

251

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?

Impatiens answered 26/8, 2010 at 2:19 Comment(0)
I
344

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);
Impatiens answered 26/8, 2010 at 2:19 Comment(12)
The window still appears momentarily at the beginning. I guess there is no way around this, unless the application type is changed?Ulphi
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.Bionomics
@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.Impatiens
Where do I use this code in the console application?Natator
@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.Dabchick
@Impatiens 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?Trinee
@Ludwik11 In application's property, debug menu, uncheck -> "Enable Visual studio host process" and then save changes.Colligan
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.Fibroma
var handle = GetConsoleWindow(); or IntPtr handle = GetConsoleWindow();Simplistic
I woud suggest using an enum enum WindowState : int { SW_HIDE = 0, SW_SHOW = 5 } as parameter. ( see doc for all possible values)Cida
It could be noted that this will not work for MacOS or LinuxArrival
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.Ginter
I
363

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

Indorse answered 1/5, 2011 at 13:9 Comment(8)
I feel like such a numpty, it seems so obvious when pointed out to me. I found this so hard to google.Pedestrian
Even though this does not answer the OP's question, I really appreciate you giving this answer. It was exactly what I needed :)Mania
This is not solution, because this way window cannot be shown.Greenery
This is not a solution to what the poster asked.Fibroma
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)Coppola
@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.Cerelia
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.Institutive
The Console Window can be shown (and used) from any GUI app by using the AllocConsole API function.Sg
I
344

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);
Impatiens answered 26/8, 2010 at 2:19 Comment(12)
The window still appears momentarily at the beginning. I guess there is no way around this, unless the application type is changed?Ulphi
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.Bionomics
@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.Impatiens
Where do I use this code in the console application?Natator
@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.Dabchick
@Impatiens 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?Trinee
@Ludwik11 In application's property, debug menu, uncheck -> "Enable Visual studio host process" and then save changes.Colligan
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.Fibroma
var handle = GetConsoleWindow(); or IntPtr handle = GetConsoleWindow();Simplistic
I woud suggest using an enum enum WindowState : int { SW_HIDE = 0, SW_SHOW = 5 } as parameter. ( see doc for all possible values)Cida
It could be noted that this will not work for MacOS or LinuxArrival
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.Ginter
H
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

Hormuz answered 4/11, 2015 at 8:0 Comment(1)
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?Umbrageous
I
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.

Impossibility answered 15/8, 2012 at 14:42 Comment(4)
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.Rima
also TopShelf allows you to run Consoles as a service and this breaks thatArmentrout
If you want standard out to be available in a console, then you will need a console, simple as that.Puerile
Some GUI applications can still be run from console, and it is nice to display output there - in the console.Hurlburt
E
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.

Exemplificative answered 26/2, 2013 at 0:23 Comment(1)
Excellent! the easiest way to hide console is to change project type to Windows application.Calico
M
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.

Mouton answered 2/12, 2018 at 18:7 Comment(0)
C
8

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
    }
}
Canalize answered 20/11, 2021 at 15:23 Comment(1)
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();"Spivey
R
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());
Roose answered 28/6, 2013 at 7:34 Comment(1)
we have to give full path of dll file in DllImport("fullPath") /Kaufmann
F
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";
Faefaeces answered 11/2, 2015 at 17:37 Comment(0)
M
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

Malevolent answered 28/4, 2023 at 16:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.