Qt实现的根据进程名来结束进程

1、头文件及实现部分:

#include <windows.h>
#include <tlhelp32.h>
#include   "psapi.h"
#pragma   comment(lib,"psapi.lib")

#include <QtCore/QCoreApplication>
#include <QProcess>

int TerminateProcess(QString ProcessName, QString sPathName = "")
{
    int result = ;
    QString processName;

    //提升进程权限
    HANDLE hToken;
    TOKEN_PRIVILEGES tkp;
    int n = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &hToken);
    LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &tkp.Privileges[].Luid);
    tkp.PrivilegeCount = ;
    tkp.Privileges[].Attributes = SE_PRIVILEGE_ENABLED;
    n = AdjustTokenPrivileges(hToken, FALSE, &tkp, , (PTOKEN_PRIVILEGES)NULL, );
    CloseHandle(hToken);

    HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, ) ;
    PROCESSENTRY32 pInfo;
    pInfo.dwSize = sizeof(pInfo);
    Process32First(hSnapShot, &pInfo);
    do
    {
        //遍历任务的所有进程
        processName = (QString::fromUtf16(reinterpret_cast<const unsigned short *>(pInfo.szExeFile)));
        if (processName == ProcessName)
        {
            //找到该进程 取出pid
            int nPID = pInfo.th32ProcessID;

            //已知pid获取路径
            TCHAR wcPath[MAX_PATH] = {};
            HANDLE hProcess = ;
            hProcess = OpenProcess(PROCESS_ALL_ACCESS , FALSE, nPID);
            GetModuleFileNameEx(hProcess, NULL, wcPath, MAX_PATH);
            CloseHandle(hProcess);
            QString path = QString::fromUtf16(reinterpret_cast<const ushort *>(wcPath));

            //如果使用默认参数 直接根据进程名终止进程 否则根据程序路径结束
            if (sPathName.compare("") ==  || path == sPathName)
            {
                QString cmd;
                cmd = QString("taskkill /F /PID %1 /T").arg(nPID);
                QProcess p();
                p.start(cmd);
                p.waitForStarted();
                p.waitForFinished();
                result ++;
            }
        }
    } while(Process32Next(hSnapShot, &pInfo));
    CloseHandle(hSnapShot);
    return result;
}

2、使用:

int main(int argc, char *argv[])
{
    //QCoreApplication a(argc, argv);
    TerminateProcess("QQ.exe");
    //return a.exec();
}

 

原创文章,作者:365开发网,如若转载,请注明出处:https://www.365codes.com/788.html

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注