根据进程名获取进程PID

//根据进程名获取PID
DWORD CBiaoBai1Dlg::GetProcessIdByProcessName(char* pszProcessName)
{
    //1.创建进程快照
    HANDLE hSnap = CreateToolhelp32Snapshot(
        TH32CS_SNAPPROCESS,            //遍历进程快照1
        0);                            //进程PID
    if (INVALID_HANDLE_VALUE == hSnap)
    {
        MessageBox("创建进程快照失败!");
        return 0;
    }

    //2.获取第一条进程快照信息
    PROCESSENTRY32  stcPe = { sizeof(stcPe) };
    if (Process32First(hSnap, &stcPe))
    {

        //3.循环遍历进程Next
        do {

            //获取快照信息
            USES_CONVERSION;
            CString ProcessName = A2T(pszProcessName);
            if (!lstrcmp(stcPe.szExeFile, ProcessName))
            {
                //4.关闭句柄
                CloseHandle(hSnap);
                return stcPe.th32ProcessID;
            }

        } while (Process32Next(hSnap, &stcPe));

    }

    //4.关闭句柄
    CloseHandle(hSnap);
    return 0;
}

 

posted @ 2020-05-03 16:47  自己的小白  阅读(5322)  评论(0编辑  收藏  举报