Click here to Skip to main content
15,891,730 members
Articles / Programming Languages / C# 4.0
Alternative
Tip/Trick

Attaching a Console to a WinForms application

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
25 Feb 2012CPOL 6.4K   1  
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)


Written By
Founder eXternSoft GmbH
Switzerland Switzerland
I feel comfortable on a variety of systems (UNIX, Windows, cross-compiled embedded systems, etc.) in a variety of languages, environments, and tools.
I have a particular affinity to computer language analysis, testing, as well as quality management.

More information about what I do for a living can be found at my LinkedIn Profile and on my company's web page (German only).

Comments and Discussions

 
-- There are no messages in this forum --