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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
Not easily. You could try disabling the close functionality using the techniques in this post: stackoverflow.com/questions/877839/…
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.