Using the Windows API:
You can use the GetConsoleProcessList API function (available only in Windows XP / 2003 and later only ). It returns a list of processes connected to the current console. When your program starts in "no console" mode, your program is the only process connected to the current console. When your program starts from another process that already has a console, more than one process will be connected to the current console.
In this case, we do not need a list of process identifiers returned by the function, we only care about the returned counter.
Sample program (I used Visual C ++ with the console application template):
#include "stdafx.h" #include <iostream> #include <Windows.h> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { DWORD procIDs[2]; DWORD maxCount = 2; DWORD result = GetConsoleProcessList((LPDWORD)procIDs, maxCount); cout << "Number of processes listed: " << result << endl; if (result == 1) { system("pause"); } return 0; }
We only need to specify up to 2 processes, because we only need 1 or more than 1 .
Using the Windows APIs present in Windows 2000:
GetConsoleWindow returns the handle of the console window associated with the current process (if any). GetWindowThreadProcessId can tell you which process created the window. And finally, GetCurrentProcessId tells you the identifier of the current process. You can draw some useful conclusions based on this information:
#include "stdafx.h" #include <iostream> #include <Windows.h> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { HWND consoleWindow = GetConsoleWindow(); if (consoleWindow != NULL) { DWORD windowCreatorProcessId; GetWindowThreadProcessId(consoleWindow, &windowCreatorProcessId); if (windowCreatorProcessId == GetCurrentProcessId()) { cout << "Console window was created by this process." << endl; system("pause"); } else cout << "Console window was not created by this process." << endl; } else cout << "No console window is associated with this process." << endl; return 0; }
This method seems a little less accurate than the first, but I think in practice it should work equally well.
tcovo source share