Friday, February 3, 2012

Write to a console window from a Windows application

Ever wondered how you could write out to a separate console window from your Windows application rather than writing to a log file? You might need to do that for a number of reasons – mostly related to debugging. Here’s how you do it:

Predefined APIs are available in kernel32.dll that will allow you to write to a console.

AllocConsole

FreeConsole

AttachConsole

AllocConsole() attaches your process to a console window where the process’ standard output will be redirected. A process can be associated with only one console, so the AllocConsole() function fails if the calling process is already associated with a console. FreeConsole() is used to detach the process from the current console and AttachConsole() can be used to attach associate a console with the current process.

The following shows a sample usage of the feature.
private void button1_Click(object sender, EventArgs e)
{
    new Thread(new ThreadStart(delegate()
    {
        AllocConsole();
        for (uint i = 0; i < 1000000; ++i)
        {
            Console.WriteLine("Hello " + i);
        }

        FreeConsole();
    })).Start();
}

You’ll need to import the AllocConsole and FreeConsole API from kernel32.dll.
[DllImport("kernel32.dll")]
public static extern bool AllocConsole();

[DllImport("kernel32.dll")]
public static extern bool FreeConsole();

And you can always make it Conditional if you want to use it only while debugging.
private void button1_Click(object sender, EventArgs e)
{
    new Thread(new ThreadStart(delegate()
    {
        AllocateConsole();
        for (uint i = 0; i < 1000000; ++i)
        {
            Console.WriteLine("Hello " + i);
        }

        DeallocateConsole();
    })).Start();
}

[Conditional("DEBUG")]
private void AllocateConsole()
{
    AllocConsole();
}

[Conditional("DEBUG")]
private void DeallocateConsole()
{
    FreeConsole();
}

No comments:

Post a Comment