Skip to content
October 11, 2006 / Bob Black

A Windows Forms Console App

That sounds like an oxymoron don’t it? 

When you create a new console project, VS.Net takes care of wiring up your app to attach to an existing console, if there is one, or creates a new one, if necessary. Right off the bat you can read from and write to the console window, and everything just works beautifully.

But what if you want to write a Windows Forms app that can also be executed from a command-line? For example, say you want to run in “console mode” if any command-line arguments are passed to the exe, otherwise you want to launch a form as normal. You may be surprised to discover that a Windows Forms app does not automatically create its own console window, so reading from or writing to the console won’t work. Give it a try if you don’t believe me.

Here’s the way around the problem. In your Windows Forms app, when you’ve determined, through whatever devices are appropriate, that the time has arrived to run in console mode, you can use these two Win API methods.

[DllImport(“kernel32.dll”, SetLastError = true)]
private static extern bool AttachConsole(int dwProcessId);

[ DllImport(“kernel32.dll”, SetLastError = true)]
private static extern bool FreeConsole();

AttachConsole attaches to an existing process’s console, or, if -1 is specified, attaches to the existing console window (for example the console used to launch your app, which is usually the one you want to attach to). After you’ve called AttachConsole you can use the System.Console like you normally would.

Example: AttachConsole(-1);

FreeConsole “detaches” from your app from a console window. You should call this when your app is finished reading/writing  to/from a console.

Example: FreeConsole();

Have fun! 



Leave a Comment
  1. Jesse / Oct 25 2008 4:51 pm

    Thanks for posting this, Bob, it was very helpful.

  2. Raif Atef / Jan 11 2009 3:43 pm

    This however creates a dependency in your app on XP since it isn’t available on Win2000 or any others before.

  3. Padmasri / Sep 3 2009 5:36 am


    AttachConsole wroks fine in debug mode but it doesnt work in Release mode…If you have any idea please let me know….

    Thanks and Regards,

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: