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

旧街凉风 提交于 2019-12-03 02:59:04

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;
}

A quick and dirty way to do it would be to just check the output of tasklist, something like:

bool isRunning(const QString &process) {
  QProcess tasklist;
  tasklist.start(
        "tasklist",
        QStringList() << "/NH" 
                      << "/FO" << "CSV" 
                      << "/FI" << QString("IMAGENAME eq %1").arg(process));
  tasklist.waitForFinished();
  QString output = tasklist.readAllStandardOutput();
  return output.startsWith(QString("\"%1").arg(process));
}

Using EnumProcesses is probably a better way (i.e. more "pure"; certainly more performant), but this may be "good enough" as long as this isn't being called in a big loop or something. The same idea could also be ported to other platforms as well, although obviously the command tool and parsing logic would be different.

 //How to Run App
 bool ok = QProcess::startDetached("C:\\TTEC\\CozxyLogger\\CozxyLogger.exe");
 qDebug() <<  "Run = " << ok;


 //How to Kill App
 system("taskkill /im CozxyLogger.exe /f");
 qDebug() << "Close";

enter image description here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!