I’m writing an application which dumps some diagnostics to the standard output.
I’d like to have the application work this way:
- If it is run from a standalone command prompt (via
cmd.exe) or has standard output redirected/piped to a file, exit cleanly as soon as it finished, - Otherwise (if it is run from a window and the console window is spawned automagically), then
additionally wait for a keypress before exiting (to let the user read the diagnostics) before the window disappears
How do I make that distinction? I suspect that examining the parent process could be a way but I’m not really into WinAPI, hence the question.
I’m on MinGW GCC.
You can use
GetConsoleWindow,GetWindowThreadProcessIdandGetCurrentProcessIdmethods.First you must retrieve the current handle of the console window using the
GetConsoleWindowfunction.Then you get the process owner of the handle of the console window.
Finally you compare the returned PID against the PID of your application.
Check this sample (VS C++)