首页 > 代码库 > Qt实现的根据进程名来结束进程
Qt实现的根据进程名来结束进程
1、头文件及实现部分:
1 #include <windows.h> 2 #include <tlhelp32.h> 3 #include "psapi.h" 4 #pragma comment(lib,"psapi.lib") 5 6 #include <QtCore/QCoreApplication> 7 #include <QProcess> 8 9 int TerminateProcess(QString ProcessName, QString sPathName = "") 10 { 11 int result = 0; 12 QString processName; 13 14 //提升进程权限 15 HANDLE hToken; 16 TOKEN_PRIVILEGES tkp; 17 int n = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &hToken); 18 LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &tkp.Privileges[0].Luid); 19 tkp.PrivilegeCount = 1; 20 tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; 21 n = AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0); 22 CloseHandle(hToken); 23 24 HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) ; 25 PROCESSENTRY32 pInfo; 26 pInfo.dwSize = sizeof(pInfo); 27 Process32First(hSnapShot, &pInfo); 28 do 29 { 30 //遍历任务的所有进程 31 processName = (QString::fromUtf16(reinterpret_cast<const unsigned short *>(pInfo.szExeFile))); 32 if (processName == ProcessName) 33 { 34 //找到该进程 取出pid 35 int nPID = pInfo.th32ProcessID; 36 37 //已知pid获取路径 38 TCHAR wcPath[MAX_PATH] = {0}; 39 HANDLE hProcess = 0; 40 hProcess = OpenProcess(PROCESS_ALL_ACCESS , FALSE, nPID); 41 GetModuleFileNameEx(hProcess, NULL, wcPath, MAX_PATH); 42 CloseHandle(hProcess); 43 QString path = QString::fromUtf16(reinterpret_cast<const ushort *>(wcPath)); 44 45 //如果使用默认参数 直接根据进程名终止进程 否则根据程序路径结束 46 if (sPathName.compare("") == 0 || path == sPathName) 47 { 48 QString cmd; 49 cmd = QString("taskkill /F /PID %1 /T").arg(nPID); 50 QProcess p(0); 51 p.start(cmd); 52 p.waitForStarted(); 53 p.waitForFinished(); 54 result ++; 55 } 56 } 57 } while(Process32Next(hSnapShot, &pInfo)); 58 CloseHandle(hSnapShot); 59 return result; 60 }
2、使用:
int main(int argc, char *argv[]) { //QCoreApplication a(argc, argv); TerminateProcess("QQ.exe"); //return a.exec(); }
Qt实现的根据进程名来结束进程
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。