65.9K
CodeProject is changing. Read more.
Home

Console and WinForm together for easy debugging

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.05/5 (12 votes)

Jan 2, 2005

viewsIcon

81576

downloadIcon

2

Using a console in a Windows application to easily generate log and/or debug information.

Introduction

Often, you need a console window together with a WinForm application. It can be very handy for debugging purposes whilst developing, but also for a (temporary) logging of some data. It is very simple to do. Following program demonstrates it, using P/Invoke.

The only things you have to add to your project are following:

public class Win32
{
        [DllImport("kernel32.dll")]
        public static extern Boolean AllocConsole();
        [DllImport("kernel32.dll")]
        public static extern Boolean FreeConsole();
}

In the using clause, you have to add this, which is needed to call external applications like in this case the win32 API DLL.

using System.Runtime.InteropServices;

Testing the code

To test it, start a new Windows application, drop a CheckBox on the form, name it ViewConsole and copy following code:

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;   // needed to call external application

namespace WindowsApplication1
{
    partial class Form1: Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void ViewConsole_CheckedChanged(object sender, EventArgs e)
        {
            if (ViewConsole.Checked)
                Win32.AllocConsole();
            else
                Win32.FreeConsole();
        }
    }

    public class Win32
    {
        [DllImport("kernel32.dll")]
        public static extern Boolean AllocConsole();
        [DllImport("kernel32.dll")]
        public static extern Boolean FreeConsole();
    }
}