How to Hide or Show Console Windows from WPF App

This post shows how to hide or show console window from your WPF app. The use case for this could be when your WPF app triggers some function that makes the console window visible. You might need to hide the console window programmatically from your WPF app.

If you are using a external functions from C++ app in your C# app then that might trigger a console window to be opened. From user’s point of view they won’t like to see the console window. It makes sense to hide the console window. Here’s how it can be done.

Step 1: Add a Native Methods class to expose the external C++ functions

Add the following class to your project.

static class NativeMethods

        public static extern IntPtr GetConsoleWindow();

        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

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

The DllImport method uses the following namespace.

using System.Runtime.InteropServices;

If the namespace is not available in your project then add a reference to it by using the Add Reference option.

Step 2: Get the console window

To get a reference to the active console window use the following code snippet. You can put the code after the InitializeComponent() call in the constructor of the MainPage.xaml.cs.

var handle = NativeMethods.GetConsoleWindow();

Step 3: Hide or Show the Console Window

To hide the console window use the following code.

// Hide
NativeMethods.ShowWindow(handle, NativeMethods.SW_HIDE);

Similarly to show the console windows use the following code.

// Show
NativeMethods.ShowWindow(handle, NativeMethods.SW_SHOW);

That’s it. Run the project to see if it works.