代码中用到Qt库的地方, 不使用Qt库的可以替换为自己相应的函数
方法一:
1 //Qt开源库, 通过QProcess启动系统命令“tasklist.exe”, 获取正在运行的进程
2 QProcess process;
3 process.start("tasklist.exe");
4 if(process.waitForFinished())
5 {
6 QByteArray result = process.readAll();
7 }
方法二:
1 //如果系统找不到Psapi.h
2 //需要安装microsoft sdk, https://www.microsoft.com/en-us/download/details.aspx?id=8279
3 #include <Psapi.h>
4
5 unsigned long aProcesses[1024], cbNeeded, cProcesses;
6 //枚举所有进程ID
7 if( !EnumProcesses(aProcesses,sizeof(aProcesses),&cbNeeded) )
8 {
9 qDebug()<<"text01"; //Qt开源库,输出字符串
10 }
11 QStringList lprocess; //Qt开源库,字符串列表
12
13 //计算有多少个进程
14 cProcesses = cbNeeded / sizeof(unsigned long);
15
16 for(unsigned int i = 0; i < cProcesses; i++)
17 {
18 if(aProcesses[i] == 0)
19 {
20 continue;
21 }
22 //获取已存在的进程对象句柄
23 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, aProcesses[i]);
24 wchar_t buffer[50];
25 GetModuleBaseName(hProcess, 0, buffer, 50); //获取进程名
26 CloseHandle(hProcess);
27 lprocess << QString::fromWCharArray(buffer); //Qt开源库
28 }
29 qDebug()<<lprocess; //Qt开源库
终止进程:
1 int KillProcess(LPCSTR processName)
2 {
3 PROCESSENTRY32 pe;
4 DWORD id=0;
5 HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
6 pe.dwSize = sizeof(PROCESSENTRY32);
7 if(!Process32First(hSnapshot,&pe))
8 {
9 return 0;
10 }
11
12 while(1)
13 {
14 pe.dwSize=sizeof(PROCESSENTRY32);
15 if(Process32Next(hSnapshot,&pe)==FALSE)
16 {
17 break;
18 }
19 //find processName
20 if(wcsicmp(pe.szExeFile, processName)==0)
21 {
22 id = pe.th32ProcessID;
23 break;
24 }
25 }
26 CloseHandle(hSnapshot);
27 //if(id == 0)
28 // return ;
29
30 //Kill The Process
31 HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, id );
32 if (hProcess != NULL)
33 {
34 TerminateProcess(hProcess,0);
35 CloseHandle(hProcess);
36 }
37 return 1;
38 }