views:

219

answers:

3

Context : programming a c/c++ win32-mfc library

How to know whether we are in a console or a windowed app?

+1  A: 

I'm not certain about this (without having tried it myself) but you can call the GetStartupInfo function which completes a STARTUPINFO structure.

Perhaps console and windows apps set the STARTF_USESHOWWINDOW flag of the dwFlags member differently and you could distinguish them like that.

As mentioned in the comments of your question, it is usually not a good sign when a library needs to know such things - the more decoupled you can keep it the better.

Hope that helps.

Martin
+9  A: 

You can determine if there is a console currently attached to the process by calling the win32 function GetConsoleWindow. If it returns NULL then there is no console attached to the process. However this will not necessarily tell you if you are running in a windowed app or not. For example I could have a windowed app that uses AllocConsole on start-up to allocate a console for debug output in which case you would have both at the same time. The other problem I can see with what you describe is an application might have no windows and no console attached (A windows service for example).

I'm going to have to agree with litb and Martin on this one as well. If your library needs to know this then it probably isn't decoupled enough. If you are using this to determine where to send debug output for example the best approach would be to use cout or cerr and let the application that is using the library deal with redirecting the stream to where it wants it.

Kevin Loney
Ok, so the question was "bad-conditionned"; an approximative method based on GetConsoleWindow would be using EnumThreadWindows to test on each window if it is a console window, comparing its hwnd to the one obtained through GetConsoleWindow.
moala
@moala That would work.
Kevin Loney
A: 

It's a Win32 FAQ

See Win32 forum news://comp.os.ms-windows.programmer.win32 for the official method. (former answers are wrong)

When detecting the subsystem remember that when using the console subsystem you can still create windows and when in the win32 subsystem you can still have a console window so this method doesn't technically tell you anything about whether there is a gui or a console actually present.
Kevin Loney