Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

Attaching a Console to a WinForms application

4.85/5 (43 votes)
7 Feb 2012CPOL 1  
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)