Search code examples
c++qtprocessqt-creatorqprocess

How to check if a program is running by its name with Qt (C++)


How to check if a program is running, by its name, with Qt (C++).

Will QProcess::pid do the job? I don't know how to use it. Please suggest.


Solution

  • As far as I know QProcess won't allow you to do that (unless you've spawned the process yourself) and in fact nothing in Qt will. However Win32 API provides a way to achieve what you want through EnumProcesses function and a complete example of how to use it is provided at Microsoft website:

    http://msdn.microsoft.com/en-us/library/ms682623.aspx

    To get you need replace PrintProcessNameAndID with the following function:

    bool matchProcessName( DWORD processID, std::string processName)
    {
        TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
    
        // Get a handle to the process.
    
        HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
                                       PROCESS_VM_READ,
                                       FALSE, processID );
    
        // Get the process name.
    
        if (NULL != hProcess )
        {
            HMODULE hMod;
            DWORD cbNeeded;
    
            if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), 
                 &cbNeeded) )
            {
                GetModuleBaseName( hProcess, hMod, szProcessName, 
                                   sizeof(szProcessName)/sizeof(TCHAR) );
            }
        }
    
        // Compare process name with your string        
        bool matchFound = !_tcscmp(szProcessName, processName.c_str() );
    
        // Release the handle to the process.    
        CloseHandle( hProcess );
    
        return matchFound;
    }