Rune Bune’s Blog

Games, Gadgets, Code & Tech

Use a .NET Windows Form as a Console application also

Posted by runebune on May 10, 2010


Some times I want to command line my windows form applications and get the output from it direct to the command line. This is nice to have when I want to batch or run the program with-in another program.

I use it if I have some methods I want to use in both a Windows Form and command line application and I don’t want to write separate applications or wrappers.

I don’t want to make a Console application and start a Windows Form, because the console windows will always be visible. I want a Windows Form application to also work as a Console application with arguments and output.

To do this I had to use the kernel32.dll as shown below:

[DllImport(“kernel32.dll”, SetLastError = true)]
private static extern bool AttachConsole(int processId);

[ DllImport(“kernel32.dll”, SetLastError = true)]
private static extern bool ReleaseConsole();

DllImport namespace is System.Runtime.InteropServices

AttachConsole(int processID) takes the console process ID to which it will output to, -1 is current.
ReleaseConsole() releases the attached console.
Example:
[STAThread]
static void Main(string[] args)

{
  try
  {
    if (args.Length == 0)
    {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new WindowsTestForm(args));
    }
    else
    {
      AttachConsole(-1);
      WindowsTestForm testForm= new WindowsTestForm (args);
    }
  }
  catch (Exception)
  {

  }
  finally
  {
    ReleaseConsole();
  }
}

#region Use Console in Windows Forms

[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool AttachConsole(int dwProcessId);

[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool ReleaseConsole();

#endregion

Leave a comment