tags:

views:

627

answers:

4

I have to create a console application which needs certain parameters. If they are missing or wrong I print out an error message.

Now the problem: If someone starts the program from the explorer by double-clicking the console window disappears immediately. (But the application is not entirely useless from the explorer, you could drag files onto it and it would work)

I could always wait for a keypress, but I don't want that if the user did start it from the command line.

Is there some way to distinguish between these situations?

+3  A: 

I believe cmd.exe sets the CMDCMDLINE and CMDEXTVERSION environemntal variables when it starts. So if these are set your program was most probably started from a shell.

This isn't foolproof but it's something.

It's also possible to determine your parent PID in a few convoluted and possibly unreliable ways, or so I gather. You may want to look into that.

Artelius
I tried the environment variables, and they don’t exist, neither when run from cmd.exe nor when run outside it. However, typing `echo %cmdcmdline%` does produce something, so the variable is apparently only valid in cmd.exe itself, not its child processes.
Timwi
A: 

How about waiting for a keystroke when you display the error message, and not other times?

Martin Plante
+4  A: 

See http://support.microsoft.com/kb/99115, "INFO: Preventing the Console Window from Disappearing".

The idea is to use GetConsoleScreenBufferInfo to determine that the cursor has not moved from the initial 0,0 position.

This quite original :) Although this is a hack it does exactly what I need and it's far more simple then getting the PPID.
DR
Anders
+2  A: 

GetConsoleTitle()

I've seen code which performs

if(!GetConsoleTitle(NULL, 0) && GetLastError() = ERROR_SUCCESS {
// Console
} else {
// GUI
}

BUT... I've found that AttachConsole() is more helpful

In C++ (off the top of my head, and I'm no C++ programmer)

if(AttachConsole(ATTACH_PARENT_PROCESS)=FALSE){
// GUI
} else {
// Console, and you have a handle to the console that already exists.
}

Is more effective. Additionally, if you find yourself in a GUI environment and would like to stay there as long as you can, but later find something catastrophic has happened that could really use a dump to a console window (you can't be arsed writing an edit box window to lot it to or attach to the NT System log and throw up a MessageBox()) well then you can AllocConsole() later on in the process, when GUI methods have failed.

bobsobol