window Qt 进程是否存在 查找所有进程 以及杀死进程

#include 
#include "tlhelp32.h"
#include 
using namespace std;

/*这是unicode*/

//判断进程是否存在 
BOOL IsExistProcess(const char*  szProcessName)
{
	PROCESSENTRY32 processEntry32;
	HANDLE toolHelp32Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (((int)toolHelp32Snapshot) != -1)
	{
		processEntry32.dwSize = sizeof(processEntry32);
		if (Process32First(toolHelp32Snapshot, &processEntry32))
		{
			do
			{
				int iLen = 2 * wcslen(processEntry32.szExeFile);
				char* chRtn = new char[iLen + 1];
				//转换成功返回为非负值
				wcstombs(chRtn, processEntry32.szExeFile, iLen + 1);
				if (strcmp(szProcessName, chRtn) == 0)
				{
					return TRUE;
				}
			} while (Process32Next(toolHelp32Snapshot, &processEntry32));
		}
		CloseHandle(toolHelp32Snapshot);
	}
	//
	return FALSE;
}

//通过进程名来杀死进程
int KillProcess(LPCSTR processName)
{
    PROCESSENTRY32 pe;
    DWORD id=0;
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
    pe.dwSize = sizeof(PROCESSENTRY32);
    if(!Process32First(hSnapshot,&pe))
    {
        return 0;
    }

    while(1)
    {
        pe.dwSize=sizeof(PROCESSENTRY32);
        if(Process32Next(hSnapshot,&pe)==FALSE)
        {
            break;
        }
        //find processName
        if(wcsicmp(pe.szExeFile, processName)==0)
        {
            id = pe.th32ProcessID;
            break;
        }
    }
    CloseHandle(hSnapshot);
    //if(id == 0)
    //  return ;

    //Kill The Process
    HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, id );
    if (hProcess != NULL)
    {
        TerminateProcess(hProcess,0);
        CloseHandle(hProcess);
    }
    return 1;
}

QT下获取所有进程
//Qt开源库, 通过QProcess启动系统命令“tasklist.exe”, 获取正在运行的进程
    QProcess process;
    process.start("tasklist.exe");
    if(process.waitForFinished())
    {
        QByteArray result = process.readAll();
         qDebug() << result;
    }
QT结束进程
// notepad.exe 为需要关闭的进程名
  QString c = "taskkill /im notepad.exe /f";
  p.execute(c);
  p.close();

 

你可能感兴趣的:(Qt,c++)