Qt获取所有进程、终止某个进程

Qt获取所有进程、终止某个进程

代码中用到Qt库的地方, 不使用Qt库的可以替换为自己相应的函数

方法一:

    //Qt开源库, 通过QProcess启动系统命令“tasklist.exe”, 获取正在运行的进程
    QProcess process;
    process.start("tasklist.exe");
    if(process.waitForFinished())
    {
        QByteArray result = process.readAll();

方法二:

    //如果系统找不到Psapi.h
    //需要安装microsoft sdk, https://www.microsoft.com/en-us/download/details.aspx?id=8279
    #include 

    unsigned long aProcesses[1024], cbNeeded, cProcesses;
    //枚举所有进程ID
    if( !EnumProcesses(aProcesses,sizeof(aProcesses),&cbNeeded) )
    {
        qDebug()<<"text01"; //Qt开源库,输出字符串
    }
    QStringList lprocess;   //Qt开源库,字符串列表

    //计算有多少个进程
    cProcesses = cbNeeded / sizeof(unsigned long);

    for(unsigned int i = 0; i < cProcesses; i++)
    {
        if(aProcesses[i] == 0)
        {
            continue;
        }
        //获取已存在的进程对象句柄
        HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, aProcesses[i]);
        wchar_t buffer[50];
        GetModuleBaseName(hProcess, 0, buffer, 50); //获取进程名
        CloseHandle(hProcess);
        lprocess << QString::fromWCharArray(buffer); //Qt开源库
    }
    qDebug()<//Qt开源库

终止进程:

    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;
    }

转载于:https://www.cnblogs.com/jiushishuai/p/9452096.html

你可能感兴趣的:(Qt获取所有进程、终止某个进程)