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
    {

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

        [DllImport("user32.dll")]
        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.

Vivek Maskara

I am pursuing BTech in Software Engineering from Delhi Technological University. I develop apps, create websites and blog about my app experiences.

Read more:
How to create your first Windows Phone app
How to change the App name and Tile name of your Windows phone app
Data binding in Windows Phone app – One way binding
Close