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 Answers
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.
2 Comments
Adrian Zanescu
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?
Paolo
Not easily. You could try disabling the close functionality using the techniques in this post: stackoverflow.com/questions/877839/…
Checkout Eric Petroelje's answer here. It shows code that can create a console at runtime.