QT 查找程序路径并打开程序,然后查找程序PID,最后关闭这个程序进程

一、查找程序路径
通过window系统注册表,查询程序路径位置,比如我要启动百度管家
QT 查找程序路径并打开程序,然后查找程序PID,最后关闭这个程序进程_第1张图片

//公司名称
QCoreApplication::setOrganizationName(QString("Baidu"));
//软件名称
QCoreApplication::setApplicationName(QString("BaiduYunGuanjia"));
QSettings settings(QSettings::NativeFormat, QSettings::UserScope,
              QCoreApplication::organizationName(),QCoreApplication::applicationName());

m_localBaiduPath = settings.value("installDir").toString();
m_localBaiduVersion = settings.value("Version").toString();

二、打开程序
博客:QT Process基本使用
三、查找程序PID

int MainWindow::processPid(const char *processName)
{
    PROCESSENTRY32 pe32;
    pe32.dwSize=sizeof(pe32);
    HANDLE hProcessSnap=::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
    BOOL bMore=::Process32First(hProcessSnap,&pe32);
    while(bMore) {
        int len= WideCharToMultiByte(CP_ACP, 0, pe32.szExeFile, wcslen(pe32.szExeFile),
                                     NULL, 0, NULL, NULL);
        char* m_char = new char[len+1];
        WideCharToMultiByte(CP_ACP, 0, pe32.szExeFile, wcslen(pe32.szExeFile),
                            m_char, len, NULL, NULL);
        m_char[len]='\0';

        if(strcmp(processName, m_char) == 0) {
            return pe32.th32ProcessID;
        }

        bMore=::Process32Next(hProcessSnap,&pe32);

        delete[] m_char;
    }

    return 0;
}

int pid = processPid("baiduyunguanjia.exe");

四、关闭进程

void MainWindow::exitProcesses()
{
    PROCESSENTRY32 pe32;
    pe32.dwSize=sizeof(pe32);
    HANDLE hProcessSnap=::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
    BOOL bMore=::Process32First(hProcessSnap,&pe32);
    while(bMore) {
        int len= WideCharToMultiByte(CP_ACP, 0, pe32.szExeFile, wcslen(pe32.szExeFile),
                                     NULL, 0, NULL, NULL);
        char* m_char = new char[len+1];
        WideCharToMultiByte(CP_ACP, 0, pe32.szExeFile, wcslen(pe32.szExeFile),
                            m_char, len, NULL, NULL);
        m_char[len]='\0';

        if(strcmp("baiduyunguanjia.exe", m_char) == 0) {
            HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, pe32.th32ProcessID);
            if(hProcess != NULL) {
                TerminateProcess(hProcess, 0);
            }
        }

        bMore=::Process32Next(hProcessSnap,&pe32);

        delete[] m_char;
    }
}

你可能感兴趣的:(QT)