A Windows Forms Console App
That sounds like an oxymoron don’t it?
When you create a new console project, VS.Net takes care of wiring up your app to attach to an existing console, if there is one, or creates a new one, if necessary. Right off the bat you can read from and write to the console window, and everything just works beautifully.
But what if you want to write a Windows Forms app that can also be executed from a command-line? For example, say you want to run in “console mode” if any command-line arguments are passed to the exe, otherwise you want to launch a form as normal. You may be surprised to discover that a Windows Forms app does not automatically create its own console window, so reading from or writing to the console won’t work. Give it a try if you don’t believe me.
Here’s the way around the problem. In your Windows Forms app, when you’ve determined, through whatever devices are appropriate, that the time has arrived to run in console mode, you can use these two Win API methods.
[DllImport(“kernel32.dll”, SetLastError = true)]
private static extern bool AttachConsole(int dwProcessId);
[ DllImport(“kernel32.dll”, SetLastError = true)]
private static extern bool FreeConsole();
AttachConsole attaches to an existing process’s console, or, if -1 is specified, attaches to the existing console window (for example the console used to launch your app, which is usually the one you want to attach to). After you’ve called AttachConsole you can use the System.Console like you normally would.
FreeConsole “detaches” from your app from a console window. You should call this when your app is finished reading/writing to/from a console.