Thursday, April 14, 2005

Console with a WinForm

Console with a WinForm

Environment: .NET, C#

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

Start a new Windows application, drop a CheckBox on the form, name it ViewConsole, and copy the following code into it.

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;    // needed to call external
                                        // application (winAPI dll)

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();
  }
}

No comments:

Post a Comment

Remember, if you want me to respond to your comment, then you need to use a Google/OpenID account to leave the comment.