c++ - How to check if the program is run from a console? -



c++ - How to check if the program is run from a console? -

i'm writing application dumps diagnostics standard output.

i'd have application work way:

if run standalone command prompt (via cmd.exe) or has standard output redirected/piped file, exit cleanly finished, otherwise (if run window , console window spawned automagically), additionally wait keypress before exiting (to allow user read diagnostics) before window disappears

how create distinction? i suspect examining parent process way i'm not winapi, hence question.

i'm on mingw gcc.

you can utilize getconsolewindow, getwindowthreadprocessid , getcurrentprocessid methods.

1) first must retrieve current handle of console window using getconsolewindow function.

2) process owner of handle of console window.

3) compare returned pid against pid of application.

check sample (vs c++)

#include "stdafx.h" #include <iostream> using namespace std; #if _win32_winnt < 0x0500 #undef _win32_winnt #define _win32_winnt 0x0500 #endif #include <windows.h> #include "wincon.h" int _tmain(int argc, _tchar* argv[]) { hwnd consolewnd = getconsolewindow(); dword dwprocessid; getwindowthreadprocessid(consolewnd, &dwprocessid); if (getcurrentprocessid()==dwprocessid) { cout << "i have own console, press come in exit" << endl; cin.get(); } else { cout << "this console not mine, bye" << endl; } homecoming 0; }

c++ c winapi

Comments

Popular posts from this blog

delphi - blogger via idHTTP : error 400 bad request -

c++ - compiler errors when initializing EXPECT_CALL with function which has program_options::variables_map as parameter -

How do I check if an insert was successful with MySQLdb in Python? -