65.9K
CodeProject is changing. Read more.
Home

Attaching a Console to a WinForms application

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Feb 25, 2012

CPOL
viewsIcon

6521

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:
[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    try
    {
        Debugging.DebugSetupConsole();
        Application.Run(new FormMain());
    }
    finally
    {
        Debugging.DebugCleanupConsole();
    }
}
and the Debugging class:
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();
        }
    }
}