Monthly archives: May 2007
Ever launched a forms app from the command line where you happily outputted debug code to the console from within Visual Studio, only to discover nothing is output to the command line like you expect? Me too. Really, it makes sense, though. Forms apps in .Net run on their own thread and therefore detach from the initiating command line right after you hit enter. Well how do you see all that pretty console text then? Disable application framework **shiver**? No...
You can do it using your old friend P/Invoke to access unmanaged code in kernel32.dll.
Here's the P/Invoke declarations:
Declare Function AttachConsole Lib "kernel32.dll" (ByVal dwProcessId As Int32) As Boolean
Declare Function FreeConsole Lib "kernel32.dll" () As Boolean
These functions allow you to attach and detach from an existing console session. So how do you find out which console launched your WinForms app? You don't need to. If you specify "-1" as the process ID, it will automatically attach to the console that started the application. Here's how you do it.
System.Console.Writeline("I am writing to the console!")
Really, you probably will only attach once and free once in your app, but that's just example code up there.
One caveat: Since your app is running in its own thread, it will write to the console asynchronously. This means that the user will receive a command prompt for the next command before your app writes anything to the console. The console will not block waiting for your app to exit. Be sure not to write things at strange times that will confuse the user about why strange text is appearing on the screen!
Source of information: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=983493&SiteID=1
Check out the forums! I posted screenshots of RD Tabs 2.0. Let me know what you think in the forums and don't forget to vote! :-)