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

5.00/5 (1 vote)
25 Feb 2012CPOL 6.5K  
To not having spoiled the client code with #if DEBUG, you might use the following:[STAThread]static void Main(){ Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); try { Debugging.DebugSetupConsole(); ...
To not having spoiled the client code with #if DEBUG, you might use the following:

C#
[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    try
    {
        Debugging.DebugSetupConsole();
        Application.Run(new FormMain());
    }
    finally
    {
        Debugging.DebugCleanupConsole();
    }
}


and the Debugging class:

C#
public abstract partial class Debugging
{
    private abstract partial class NativeMethods
    {
        // http://msdn.microsoft.com/en-us/library/ms681944(VS.85).aspx
        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern int AllocConsole();

        // http://msdn.microsoft.com/en-us/library/ms683150(VS.85).aspx
        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern int FreeConsole();
    }

    private static bool _consoleOk = false;
    [Conditional("DEBUG")]
    public static void DebugSetupConsole()
    {
        _consoleOk = NativeMethods.AllocConsole() == 0;
        Console.WriteLine("Debug Console");
    }
    [Conditional("DEBUG")]
    public static void DebugCleanupConsole()
    {
        if (_consoleOk) 
        {
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();

            NativeMethods.FreeConsole();
        }
    }
}

License

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