2

I have a windows forms application and i want to open a console on demand (when i press a button for example) that i can interact with using the standard Console class. Is there a way to do this?

Adrian Zanescu
  • 7,907
  • 6
  • 35
  • 53

2 Answers2

6

Yes there is you'll need a litte bit on interop with Win32 to do it.

public class ConsoleHelper
{
    public static int Create()
    {
        if (AllocConsole())
            return 0;
        else
            return Marshal.GetLastWin32Error();
    }

    public static int Destroy()
    {
        if (FreeConsole())
            return 0;
        else
            return Marshal.GetLastWin32Error();
    }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressUnmanagedCodeSecurity]
    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool AllocConsole();


    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressUnmanagedCodeSecurity]
    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool FreeConsole();
}

Now you can call Create() to create console window associated with your app.

Paolo
  • 22,188
  • 6
  • 42
  • 49
  • 1
    thanks. it worked. now i have another problem. if the spawned console is closed my whole application goes down. Is there a way to prevent that? – Adrian Zanescu Dec 23 '09 at 15:39
  • Not easily. You could try disabling the close functionality using the techniques in this post: http://stackoverflow.com/questions/877839/stop-a-net-console-app-from-being-closed/878334#878334 – Paolo Dec 23 '09 at 16:07
0

Checkout Eric Petroelje's answer here. It shows code that can create a console at runtime.

Community
  • 1
  • 1
Brian Ensink
  • 11,092
  • 3
  • 50
  • 63