How to create a Windows program that works both as a GUI and console application

It would be very nice to be able to make Windows applications that can act as either a GUI or console application depending on how they are used (i.e. act as a GUI application if double clicked in Windows Explorer or as a console application if called from a cmd.exe window).

Unfortunately the way Windows work, each exe application has field in the PE header that specifies which subsystem it should run under. This is set in Visual Studio by using one of the linker SUBSYSTEM option (i.e. Windows or Console). The subsystem is used by the Windows kernel to set up the execution environment for the application. If the application is built using SUBSYSTEM/Console then the kernel will connect the application to the parent console and the application’s stdout, stderr and stdin will be redirected to the parent console. If the program is built as a GUI application then the application detaches from the parent console and all output to stdout and stderr are are lost – basically the program runs, but doesn’t output anything to the parent console window.

People have attempted various hacks over the years to solve this problem. One solution proposed was to compile the program as a Windows application and then edit the PE header to mark the program as using the Console subsystem. The downside of this approach is it flashes a Console window on the screen when run as a GUI application that looks pretty unprofessional. The second hack commonly used is to create two separate binaries, for example, a and myuselessprogram.exe. The .com version is built as a Console application while the .exe is built as Windows application. When you run myuselessprogram the Windows probing rule runs the .com version first and if there is nothing on the command line then the .com version calls the .exe Windows version. While both these approaches work, they are to say less than ideal.

A better approach is use the WINAPI AttachConsole function to attach the application to the parent console and then redirect stdout, stdin and stderr back to the parent console. This actually works very well except that when the application exits the parent console can’t detect this and hence release the command prompt. The end result is the parent console just sits there until the user presses the “enter” key.

There is no really elegant solution to this problem, but as applications can simulate the keyboard being used, a simple solution is to call the SendInput API function with the “enter” key just before the application exits. This simulates the user pressing the enter key and hence releases the command prompt.

To show how this approach works I have written a small test application (see below). The main limitations is that AttachConsole is only available on Windows XP and above. It does works under Cygwin which is nice.

Update. I have added a check to make sure that the console window is in focus before sending the enter key. It is a good check to make if you are running your console program in a background script or else you will end up with lots of “enter” key presses in whatever application you actually have in focus – lots of fun if you are working on the documentation while a script runs in the background :)

Update 2. Contrary to what has been posted on Stack Overflow this approach works with STDIN too. I don’t have any need to capture STDIN with my application (just the command line parameters), but all you need to do to capture stdin is treat STDIN as is done for STDOUT (i.e just redirect STDIN to the console) in the attachOutputToConsole function.

Update 3. This is MIT licensed if this is important to you :)

Update 4. Microsoft has broken the old approach I was using in VS2015. I have updated the code to use a different way of attaching STDOUT and STRERR to the parent console. This code works with VS2015 and all earlier compliers I was able to test (VS2013, VS2008, VS2005).


 Copyright (c) 2013, 2016 Daniel Tillett
 All rights reserved.
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
 1. Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.
 2. Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following disclaimer in the documentation
 and/or other materials provided with the distribution.


#define WINVER 0x0501 // Allow use of features specific to Windows XP or later.
#define _WIN32_WINNT 0x0501
#include "windows.h"
#include "io.h"
#include "fcntl.h"
#include "stdio.h"
#include "stdlib.h"
#pragma comment(lib, "User32.lib")

// Attach output of application to parent console
static BOOL attachOutputToConsole(void) {
HANDLE consoleHandleOut, consoleHandleError;

if (AttachConsole(ATTACH_PARENT_PROCESS)) {
  // Redirect unbuffered STDOUT to the console
  consoleHandleOut = GetStdHandle(STD_OUTPUT_HANDLE);
  if (consoleHandleOut != INVALID_HANDLE_VALUE) {
    freopen("CONOUT$", "w", stdout);
    setvbuf(stdout, NULL, _IONBF, 0);
  else {
    return FALSE;
  // Redirect unbuffered STDERR to the console
  consoleHandleError = GetStdHandle(STD_ERROR_HANDLE);
  if (consoleHandleError != INVALID_HANDLE_VALUE) {
    freopen("CONOUT$", "w", stderr);
    setvbuf(stderr, NULL, _IONBF, 0);
  else {
    return FALSE;
  return TRUE;
//Not a console application
return FALSE;

// Send the "enter" to the console to release the command prompt 
// on the parent console
static void sendEnterKey(void) {
 INPUT ip;
 // Set up a generic keyboard event.
 ip.type = INPUT_KEYBOARD; = 0; // hardware scan code for key = 0; = 0;

 // Send the "Enter" key = 0x0D; // virtual-key code for the "Enter" key = 0; // 0 for key press
 SendInput(1, &ip, sizeof(INPUT));

 // Release the "Enter" key = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release
 SendInput(1, &ip, sizeof(INPUT));

int WINAPI WinMain(HINSTANCE hInstance, 
HINSTANCE hPrevInstance, 
PSTR lpCmdLine, 
INT nCmdShow) {
int argc = __argc;
char **argv = __argv;
BOOL console;
int i;

//Is the program running as console or GUI application
console = attachOutputToConsole();

if (console) {
    // Print to stdout
    printf("Program running as console application\n");
    for (i = 0; i < argc; i++) {
         printf("argv[%d] %s\n", i, argv[i]);

    // Print to stderr
    fprintf(stderr, "Output to stderr\n");
else {
    MessageBox(NULL, "Program running as Windows GUI application",
    "Windows GUI Application", MB_OK | MB_SETFOREGROUND);

// Send "enter" to release application from the console
// This is a hack, but if not used the console doesn't know the application has
// returned. The "enter" key only sent if the console window is in focus.
if (console && (GetConsoleWindow() == GetForegroundWindow())){
return 0;

Solved: Problem with Skype number always engaged (busy)

I decided to get a skype number as a replacement for my landline number. I found that no matter what skype setting I used on my mac laptop the phone number was always engaged (busy). It turns out that the problem is due to the fact that I also had skype installed on my windows box. It seems that if you are logged in on two different machines skype will always take the settings from windows over osx. Any changes you make on the osx side are overridden by whatever settings you have on the windows box. As soon as I changed the settings on the windows box everything started working.

Now all I need to do is figure out how to get the 2 hours of my life back that I wasted on working this out :)

Voyager Estate Cabernet Sauvignon Merlot 2007

Over in Western Australia 2007 was the “vintage of the century” – I can’t say the same for Eastern Australia where 2007 was probably one of worst for at least 20 years. I managed to get (and drink) a couple of bottles of the 2007 Voyager Estate Shiraz and they were fantastic. I hadn’t had a chance to try the Cab Sav from the same year, but I noticed a few bottles of the 2007 Voyager Estate Cabernet Sauvignon Merlot for sale at my local Dan Murphys so I thought I would take a chance. At $50 a bottle this is a little above my normal limit, but given the year and maker I thought they might be worth the risk so I bought a couple of bottles. A good great decision as the wine is really outstanding. If you like WA cab savs then I think that you will not find better for the price right now. This wine is definitely worth the cost.


Price $50
Value $90+

Update Nov 2013. I saw this for sale a week ago out of cellar release and they wanted $115 for it!

Install R on CentOS 5 x64 using yum

I recently had the fun of installing R on my development box. While you can install from source I wanted to be able to install using yum. R is not in the standard packages, but it is in the epel repository (Extra Packages for Enterprise Linux 5 – x86_64).

Steps for Installing R
1. Make sure that you have epel in your yum repositories (use yum listrepo to check). If not add epel to your yum repos (see here for instructions how to do this).
2. Install R and dependencies using yum install R-core R-2*
3. Enter R (just type R) and update all the default package using update.packages(). You will need to choose the nearest mirror to you.
4. Install the packages you need using install.packages(“package_name”, dependencies = TRUE)
5. Quit R using q()

Hope this saves someone a little time.

If you are behind a proxy server then use the following (change for your proxy setting) after starting R
You can check if correct by
then update by

Langmeil Orphan Bank Shiraz 2009

The Barrosa had a reasonably good year in 2009 and one of the best wines I have from that vintage is the Langmeil Orphan Bank Shiraz 2009. I found it on the Dan Murphys “wall of death” (i.e. off the main floor and hidden away in a corner). I was intrigued by the story on the back of the bottle about them saving some of the original 19th C. shiraz vines from the ravages of the 80s vine pull. I thought I would buy a bottle even though it is a bit outside of my normal price range ($42). I am certainly glad I did as it is worth every cent. I have had $80 wines that are nowhere as good as this. Highly recommended.

Orphan Bank

Price $42.75
Value >$75

Taltarni Pyrenees Shiraz 2009

Another great pyrenees shiraz that only cost me $22 a bottle. My only complaint is Taltarni is still using corks with this wine! Come on Taltarni it is 2012 – a cork these days is about as desirable as a hypercolour t-shirt.


Price $22.00
Value +$35.00

Update Nov 2013. I saw some of this for sale a couple of weeks ago at my local DM – the only downside is it is now $30 a bottle.

Irvine Springhill Merlot 2009

I am not overly fond of straight merlot wines (Château Pétrus is a little outside my price range) as they tend towards being lolly water. One real exception to this is the Eden Valley 2009 Irvine Spinghill Merlot. This is simply a great wine – soft, smooth and full of flavour. It is easy to pair up with food and best of all it is a total bargain at under $17 a bottle. For the price I don’t think I have had a better wine all year. This is certainly a wine you can afford to stock up on.

Irvine Merlot

Price $16.90
Value >$25.00

Update Jan 2014. I have recently tried the 2012 vintage and it is great too – I would say even better than the 2009. Still the same great low price.

Mount Pleasant Rosehill Hunter Valley Shiraz 2009

A longer overdue post on some good wines. I have had a few (well more than a few) in the last couple of months, but life has intervened and I have just not had time to write about any of them. One that I should write about is the 2009 Mount Pleasant ‘Rosehill’ Hunter Valley Shiraz. I have a very soft spot for Hunter wines in general and for ‘Rosehill’ in particular. The 1991 Rosehill was one of the first ‘good’ wines I can remember drinking and I have drunk a lot of the great vintages of this wine over the years. The only problem is Rosehill is typical of all Hunter wines in being totally vintage dependent. To say the Hunter Valley does not have a reputation for consistency is a massive understatement. If it was not for its geographical location a couple of hours north of Sydney then I am sure that all the vineyards in the Hunter would have become coal mines long ago. Despite this when the conditions are right (unfortunately far too rarely) it can give birth to some of the best wines in Australia.

The upside to all this inconstancy is that no Hunter wine can command the prices that it should when a good vintage comes along. The 2009 vintage is a great vintage and is one of those years where there are many hunter bargains to be found. There is probably no greater bargain than the 2009 Rosehill. This is a traditional hunter shiraz at a price ($26) far below where it should be for the actual wine in the bottle. My advice is run (don’t walk) and buy as much of this wine as your wallet (or wife) will let you. Bargain of the year so far.


Cost: $26
Value: +$50

Clonakilla O’Riada Shiraz 2009

Tim Kirk from Clonakilla is one of the better Australian winemakers (just a slight understatement). Clonikilla flagship Shiraz is rightly considered one of the best Australian wines, but at $100 a bottle is a little outside my budget. Last year I saw a new wine from Clonikilla – the O’Riada Shiraz at $35. The second wines of great winemakers in good years are normally bargains and this wine was the perfect example of this theory. The 2009 vintage is everything you could wish for at this price and is better than most wines I have had that cost more than twice the price. I was only able to grab 3 bottles and Dan Murphys were not able to get any more in for me (unfortunately the 2010 is not anywhere near as good). I had my last bottle tonight with roast rib eye and it was perfect – smooth, powerful and in harmony with the meal. Now if only I could get more :(


Cost: $35
Value: >$70

New iPad

On a bit of a impulse I decided to try my luck getting a new iPad at BigW on Friday morning (I was driving past around the time they open). While there were quite a few apple desperadoes ahead of me in the queue (I was last in line), I thought it might be worth the wait. Luckily they still had the model I wanted (32G wifi black) by the time they got down to me so I bought it.

I didn’t get much chance to play with it yesterday (work), but I have had a bit of a chance today. I already have the version 1 iPad. I can say the only important difference between the two is the screen. While this might not seem that important the new screen is immaculate – so much that it makes the old iPad seem like something out of the 80s. I can’t stress enough how much better the new screen is than the old. If like me you use your iPad mostly to read then the new iPad is not just an incremental upgrade, it is revolutionary. It is a shame that Steve didn’t live to see it released as I am sure this is what he always had in mind what the iPad should be – maybe Apple’s stock will reach $700 yet.