Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

winapi

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.

like image 933
Kos Avatar asked Jan 25 '12 19:01

Kos


People also ask

How do you determine what just ran on Windows console?

Once you have opened the Command Prompt window and started executing commands, Windows will save the history for your active session. To see the list of recently executed commands in CMD, press the F7 key. This will open a pop-up inside CMD showing the list of recently executed commands.


2 Answers

You can use GetConsoleWindow, GetWindowThreadProcessId and GetCurrentProcessId methods.

1) First you must retrieve the current handle of the console window using the GetConsoleWindow function.

2) Then you get the process owner of the handle of the console window.

3) Finally you compare the returned PID against the PID of your application.

Check this 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 my own console, press enter to exit" << endl;         cin.get();     }     else     {         cout << "This Console is not mine, good bye" << endl;        }       return 0; } 
like image 62
RRUZ Avatar answered Oct 05 '22 12:10

RRUZ


The typical test is:

 if( isatty( STDOUT_FILENO )) {         /* this is a terminal */ } 
like image 38
William Pursell Avatar answered Oct 05 '22 10:10

William Pursell