Click here to Skip to main content
15,861,172 members
Articles / Programming Languages / C# 4.0
Tip/Trick

Attaching a Console to a WinForms application

Rate me:
Please Sign up or sign in to vote.
4.85/5 (43 votes)
7 Feb 2012CPOL 172.2K   57   25
How to have a real console window as well as your forms
When debugging a Windows Forms application, the Console class is often used (in place of the Debug class) to write to the IDE's Output window.

It is possible to attach one actual console window to the process by using the AllocConsole function from kernel32.dll and its matching FreeConsole to release it.

This is not restricted to debugging, but that's probably where it has the most use.

An example of usage:

C#
using System;
using System.Windows.Forms;

namespace FormWithConsole
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
#if DEBUG
            NativeMethods.AllocConsole();
            Console.WriteLine("Debug Console");
#endif
            Application.Run(new FormMain());
#if DEBUG
            NativeMethods.FreeConsole();
#endif
        }
    }
}


and the class containing the P/Invoke functions:

C#
using System;
using System.Runtime.InteropServices;

namespace FormWithConsole
{
    internal static class NativeMethods
    {
        // http://msdn.microsoft.com/en-us/library/ms681944(VS.85).aspx
        /// <summary>
        /// Allocates a new console for the calling process.
        /// </summary>
        /// <returns>nonzero if the function succeeds; otherwise, zero.</returns>
        /// <remarks>
        /// A process can be associated with only one console,
        /// so the function fails if the calling process already has a console.
        /// </remarks>
        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern int AllocConsole();

        // http://msdn.microsoft.com/en-us/library/ms683150(VS.85).aspx
        /// <summary>
        /// Detaches the calling process from its console.
        /// </summary>
        /// <returns>nonzero if the function succeeds; otherwise, zero.</returns>
        /// <remarks>
        /// If the calling process is not already attached to a console,
        /// the error code returned is ERROR_INVALID_PARAMETER (87).
        /// </remarks>
        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern int FreeConsole();
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO Dave Meadowcroft
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralAnother way Pin
Sergey Morenko30-Jul-12 11:52
professionalSergey Morenko30-Jul-12 11:52 
GeneralRe: Another way Pin
Jason Vogel18-Mar-13 5:57
Jason Vogel18-Mar-13 5:57 
GeneralRe: Thank you very much for the explanation. I get the idea now ... Pin
hoernchenmeister8-Feb-12 0:19
hoernchenmeister8-Feb-12 0:19 
GeneralRe: Hi You can (early in your program) implement a ConsoleTrac... Pin
wvd_vegt8-Feb-12 0:04
professionalwvd_vegt8-Feb-12 0:04 
GeneralRe: Thanks for your comment. Yes, you are right, I use Console.W... Pin
hoernchenmeister7-Feb-12 22:46
hoernchenmeister7-Feb-12 22:46 
GeneralRe: thanks ! .. I might get to test it later today :-) Pin
Garth J Lancaster7-Aug-11 13:13
professionalGarth J Lancaster7-Aug-11 13:13 
GeneralReason for my vote of 5 good one. Pin
Nikhil_S26-Feb-12 17:46
professionalNikhil_S26-Feb-12 17:46 
GeneralJust a minor remark on extern calls. When researching why my... Pin
TetheredSun6-Feb-12 22:20
TetheredSun6-Feb-12 22:20 
GeneralRe: Good point - in winDef.h BOOL is defined like: typedef i... Pin
DaveyM697-Feb-12 10:37
professionalDaveyM697-Feb-12 10:37 
GeneralJust a quick note. The console window has to be attached bef... Pin
hoernchenmeister5-Feb-12 21:30
hoernchenmeister5-Feb-12 21:30 
Just a quick note.
The console window has to be attached before any IO output is created.
I tried to put it into my app as some kind of "Developer Help", but it never worked if I used a button inside the app.

Now I attached a commandline parameter that is read in the Main() function that created the console on startup if the specific parameter is attached.
That way I get a console that shows every single WriteLine in the whole app, regadless which dll is actually working.
GeneralRe: Hi You're clearly doing something wrong (like using Console... Pin
wvd_vegt7-Feb-12 22:20
professionalwvd_vegt7-Feb-12 22:20 
GeneralHi If you use this do not forget to remove the close button... Pin
wvd_vegt26-Jan-12 1:39
professionalwvd_vegt26-Jan-12 1:39 
GeneralReason for my vote of 5 Nice tip, thanks for sharing Pin
hoernchenmeister20-Jan-12 2:41
hoernchenmeister20-Jan-12 2:41 
GeneralGreat tip, I just made a test with a WinFormApp having 2 but... Pin
hoernchenmeister20-Jan-12 2:41
hoernchenmeister20-Jan-12 2:41 
GeneralReason for my vote of 5 5ed Pin
johannesnestler18-Jan-12 4:49
johannesnestler18-Jan-12 4:49 
GeneralReason for my vote of 4 Nice tip Pin
zenwalker198519-Oct-11 3:29
zenwalker198519-Oct-11 3:29 
Generalinteresting - I was thinking about the inverse 'ConsoleWithF... Pin
Garth J Lancaster5-Aug-11 1:43
professionalGarth J Lancaster5-Aug-11 1:43 
GeneralRe: This is possible too: using System.Windows.Forms; namespace... Pin
DaveyM696-Aug-11 1:00
professionalDaveyM696-Aug-11 1:00 
GeneralReason for my vote of 5 Stumbled upon a neat trick. Although... Pin
SimulationofSai2-Mar-11 15:34
SimulationofSai2-Mar-11 15:34 
GeneralReason for my vote of 5 Think Pin
Anubhava Dimri15-Nov-10 20:49
Anubhava Dimri15-Nov-10 20:49 
GeneralInstead of calling AllocConsole in Main, call it from where ... Pin
DaveyM6928-May-10 8:05
professionalDaveyM6928-May-10 8:05 
GeneralHow to attach a console when application is already launched... Pin
MaheshBagul28-May-10 2:09
professionalMaheshBagul28-May-10 2:09 
GeneralI do it my way Pin
PIEBALDconsult2-Mar-11 15:28
mvePIEBALDconsult2-Mar-11 15:28 
GeneralTo Developer who are discourage people by giving less point Pin
Khaniya2-Apr-10 0:22
professionalKhaniya2-Apr-10 0:22 
GeneralRe: To Developer who are discourage people by giving less point Pin
DaveyM692-Apr-10 1:25
professionalDaveyM692-Apr-10 1:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.