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:
using System;
using System.Windows.Forms;
namespace FormWithConsole
{
static class Program
{
[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:
using System;
using System.Runtime.InteropServices;
namespace FormWithConsole
{
internal static class NativeMethods
{
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern int AllocConsole();
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern int FreeConsole();
}
}