[英]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++). 如何使用Qt(C ++)通过名称检查程序是否正在运行。
Will QProcess::pid
do the job? QProcess::pid
完成这项工作吗? I don't know how to use it. 我不知道如何使用它。 Please suggest. 请建议。
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. 据我所知,QProcess不会允许你这样做(除非你自己产生了这个过程),事实上Qt中没有任何内容。 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: 但是,Win32 API提供了一种通过EnumProcesses
功能实现EnumProcesses
功能的方法,并在Microsoft网站上提供了如何使用它的完整示例:
http://msdn.microsoft.com/en-us/library/ms682623.aspx http://msdn.microsoft.com/en-us/library/ms682623.aspx
To get you need replace PrintProcessNameAndID with the following function: 为了满足您需要使用以下函数替换PrintProcessNameAndID:
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: 一个快速和肮脏的方式做到这一点是只检查的输出tasklist
,像:
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 (ie 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. 使用EnumProcesses
可能是一种更好的方式(即更“纯粹”;当然更高性能),但只要不在大循环中调用EnumProcesses
可以“足够好”。 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";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.