码迷,mamicode.com
首页 > 系统相关 > 详细

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

时间:2018-11-21 21:04:59      阅读:583      评论:0      收藏:0      [点我收藏+]

标签:base   for   ati   proc   cst   exe   unsigned   buffer   获取   

方法一:

//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 <Psapi.h>

    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()<<lprocess; //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;
    }

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

标签:base   for   ati   proc   cst   exe   unsigned   buffer   获取   

原文地址:http://blog.51cto.com/4754569/2319708

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!