Qt应用程序如何监测另一个程序状态?(windows系统)

以前在做项目时有用过QProcess启动一个应用程序。 在按下按钮的槽函数中调用QProcess的start函数即可,非常的简单。但是这次不一样了,被调用的程序,并非我的程序启动的。我需要先
判断它是否已经启动了。那么如何判断呢?

查看帮助文档发现QProcess有个state()函数可以返回进程的状态。

Q Process::ProcessState QProcess::state () const
Returns the current state of the process.

enum QProcess::ProcessState
This enum describes the different states of QProcess .
Constant Value Description
QProcess::NotRunning 0 The process is not running.
QProcess::Starting 1 The process is starting, but the program has not yet been invoked.
QProcess::Running 2 The process is running and is ready for reading and writing.
可是我发现没办法获得这个进程, 因为这个程序不是由我启动的。只能想别的办法了,想想平时经常使用任务管理器关闭进程。那是不是只要查询管理器中有没有要启动的进程就可以了? 测试发现启动任务管理器也没用,无法获取进程列表,而且弹出一个任务管理器也不是我们想要的。
无奈只能求助万能的网友,认识了tasklist这东西,不仅可以查询进程还能杀死进程。
Qt应用程序如何监测另一个程序状态?(windows系统)_第1张图片
那么如何使用呢?查看帮助 tasklist -FI "imagename eq xxx.exe" 这个命令可以显示进程名为xxx.exe的信息。

看看代码如何写:
QProcess* process = new QProcess;
process->start("tasklist" ,QStringList()<<"/FI"<<"imagename eq xxx.exe");
process->waitForFinished();
QString outputStr = QString::fromLocal8Bit(process->readAllStandardOutput());

最后通过输出的信息来判断是否已启动程序。如果没有启动则提示:


更多详细内容请查看: fearlazy.com


你可能感兴趣的:(Qt学习乱记)