Hi guys. 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?
+2
A:
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
2009-12-23 15:30:07
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?
AZ
2009-12-23 15:39:56
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
2009-12-23 16:07:01
A:
Checkout Eric Petroelje's answer here. It shows code that can create a console at runtime.
Brian Ensink
2009-12-23 15:31:03