William Stacey said:
Not sure if I remember this right. Don't all windows apps start with a
hidden console?
Detaching the apps default console, and attaching to "thee" Console that
started the WinForm app is a major pain that has some other issues IIRC.
Are you sure you're not thinking of Unix there? What you've described is
pretty much how it works for Unix applications that want to run without a
console, but it's definitely not how Windows works.
In Windows, you always have a standard output stream, but whether it's
attached to a console or not is usually determined by some flags in your
executable's header. (I say 'usually' because it is possible to write a
program that launches a process, hooking up whatever it likes as standard
input and output streams, but I assume we're talking about when programs are
launched in the usual way.)
The way it works is that if you are a console application you'll have a
console, if you're not, you won't. You can find out whether a given EXE is
a console app with the 'dumpbin' utility. (It's part of the Win32 SDK.)
Look at the 'subsystem' header value.
If the 'subsystem' is 3 ("Windows CUI") you're a console application. If
it's 2 ("Windows GUI") you're not.
You can't actually detach from the console once you've got it in Windows.
This is the whole reason people end up having to write two executables - a
..COM and a .EXE when they want to support both console and no-console
operation, as you describe here:
Most folks solve this by distributing two loader apps. MyApp.exe and
MyApp.com in the same directory.
If you initially had a console which you later detached from you wouldn't
need two executables. The reason for having two is so you can have one that
gets a console, and one that doesn't.
(Note that while you can create a console and attach your app to it after
launching, it'll be a whole new console window. The only way to attach to
the console of the command prompt from which you were launched is if you are
compiled as a console application.)
To answer one of Barry's original questions:
Well if you do a Console.WriteLine and there's no console, it will still
write the text to the standard output stream, whatever that is connected to.
This is because it might still be directed somewhere useful. For example,
WinDBG actually captures stdout and prints it to the debug output window for
applications it debugs. So you wouldn't necessarily want the runtime to
avoid writing console output to the standard output stream - just because
there's no console doesn't mean that output isn't being used by something.
As for the original question:
I don't think you can do this without interop. I've just looked at how
VS.NET 2005 (which has explicit support for interacting with the console
window) works it out, and it just uses the various console APIs. So you
could call the GetConsoleScreenBufferInfo API, for example, although you'd
need to get the raw console handle...
There isn't a managed API to do this.
[/QUOTE]