Mailing List



NerdyHearn - Blog

<< Back To All Blogs

Writing console output from a Windows form in C#

Thursday, June 25th, 2009

As simple as it seems, there is actually no way to easily write to the console
from a Windows forms application. You may also be asking yourself why would you ever want to do that, but the situation will arise if you are programming long enough.

One common use is for "command line" applications that only need to launch a window if an error occurs, or if you would like to drop debugging information from the launching console instead of to a message box or the system event viewer.

These are actually Windows Forms applications, they just may or may not actually launch a Windows form.

It is not very hard to log to the console from a windows app, but it does require binding the application to a console via a Windows SDK call.

So without further ado, here is how it is done:

static class Program
static extern bool AttachConsole(int dwProcessId);
private const int ATTACH_PARENT_PROCESS = -1;

static void Main(string[] args)
// Enable visual elements just like always

// Attach to the parent process via AttachConsole SDK call
Console.WriteLine("This is from the main program");

Application.Run(new Form1());

At this point, once you launch into Form1, you can also call Console.WriteLine and it will function exactly as if you were running a "true" console application.

Pretty snazzy huh?

ConsoleWritin' Tom Out.


CSharp Howto PInvoke

Related Blogs

Comparing XML files in C# Using Microsoft's Diff and Patch Tool
Good Ol Cross-Threaded Socket Action
Determining if a computer is a laptop or desktop in C#

Enumerating the values of an enum in C#


Tom said on Monday, July 13th, 2009 @ 6:25 PM

Hi Kenneth,

Glad to hear it worked out well!

Kenneth Lewis said on Monday, July 13th, 2009 @ 4:12 PM

Nevermind I just made it OutputType Console Application, used a ConsoleTraceListener, if I have arguments then its a console app, if not then its a windows app and it works great. :)

Kenneth Lewis said on Monday, July 13th, 2009 @ 3:54 PM

I tried doing this in my application which is a WinForms and I only call the AttachConsole if args.Length > 0 but when I do Console.WriteLine I am not seeing the output in the console window when I launched the app from the command line.


Kenneth Lewis

David said on Friday, June 26th, 2009 @ 11:30 AM

You can get a console and windows form at the same time by creating a windows form project and switching the output type in the project properties panel to Console Application... what is better about doing it your way?

Add A Comment



Email Address: (not public, used to send notifications on further comments)


Enter the text above, except for the 1st and last character:

NerdyHearn - Latest tech news relating to C#, ASP.NET, SharePoint, PHP, general development, and more. SaveMySerials - Protect yourself from theft, fire, natural disasters and more by recording your serial numbers