<< 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");
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.
Calling .NET WebService From PHP
Creating a dynamic SharePoint settings DropDown using a ToolPart
Awesome .NET 4: Named and Optional Parameters for Classes and Methods
Reading Digital Signatures from InfoPath Forms in MOSS 2007 and WSS 3.0 Workflow
Creating a PDF with C# and iTextSharp
Tom said on Monday, July 13th, 2009 @ 6:25 PM
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.
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: