Starting a GUI application as a console

Console vs. GUI

GUIs are nice and pretty but clicking around is just not what we developpers do… They also bring quite daunting disadvantages:

  • relatively slow
  • cannot be controlled / run in the background
  • painful to automate

As a developper there will come a time where for testing a new cool feature you are going to have to start your GUI, maybe load a configuration, probably click around a few times and wait for your result and this might not sound too bad, but you will do it again and again and again… and again. And this will cost you a lot of time.

Consoles are maybe quite ugly to look at, but they are the right place to look at when you want something to get done efficiently. Do yourself / your users a favor and implement a console version of your program, this will come very handy when you will test your application. Do not let your bad mouse aiming be your bottleneck!

The code

In this implementation you start with a WPF project, you must then create a new WpfApp1.Program class and set it as your Start Object in the project properties. You can then:

  • start the program as a standard GUI application by double-clicking the executable or calling it from the console without parameters: WpfApp1.exe
  • you can also start it as a console application if you pass any parameters: WpfApp1.exe param1 param2 param3


using System.Windows;

namespace WpfApp1
    public partial class MainWindow : Window
        public MainWindow()


using System;
using System.Runtime.InteropServices;

namespace WpfApp1
    public static class Program
        public static extern void AllocConsole();

        public static extern void FreeConsole();

        static extern bool AttachConsole(uint dwProcessId);

        public static void Main(string[] args)
            bool madeConsole = false;
            if (args.Length > 0)
                if (!AttachToConsole())
                    Console.WriteLine("Had to create a console");
                    madeConsole = true;

                Console.WriteLine("Now I'm a console app!");
                Console.WriteLine("Press any key to exit");

                if (madeConsole)

        public static bool AttachToConsole()
            const uint ParentProcess = 0xFFFFFFFF;
            if (!AttachConsole(ParentProcess))
                return false;

            Console.WriteLine("Attached to console!");
            return true;



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s