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

后端 未结 5 1084
粉色の甜心
粉色の甜心 2020-12-01 00:50

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 s
5条回答
  •  盖世英雄少女心
    2020-12-01 01:25

    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 
    using namespace std;
    #if       _WIN32_WINNT < 0x0500
      #undef  _WIN32_WINNT
      #define _WIN32_WINNT   0x0500
    #endif
    #include 
    #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;
    }
    

提交回复
热议问题