码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 根据进程名找到对应Pid

时间:2016-12-29 07:28:01      阅读:324      评论:0      收藏:0      [点我收藏+]

标签:bool   filename   top   not   images   spi   span   for   ssi   

// FileName: FindProcessPid.cpp

// Function: Find Pid by ProcessName

#include <string.h>
#include <stdio.h>
#include <Windows.h>
#include <tlhelp32.h>    //CreateToolhelp32Snapshot


#define ArraySize(ptr)    (sizeof(ptr) / sizeof(ptr[0]))


BOOL FindProcessPid(LPCSTR ProcessName, DWORD& dwPid);


int main()
{
    LPCSTR ListApps[]{
        "QQ.exe", "chrome.exe"
    };
    // StopMyService();
    DWORD dwPid = 0;

    for (int i = 0; i < ArraySize(ListApps); i++)
    {
        if (FindProcessPid(ListApps[i], dwPid))
        {
            printf("[%s] [%d]\n", ListApps[i], dwPid);
        }
        else
        {
            printf("[%s] [Not Found]\n", ListApps[i]);
        }
    }
    return 0;
}

BOOL FindProcessPid(LPCSTR ProcessName, DWORD& dwPid)
{
    HANDLE hProcessSnap;
    PROCESSENTRY32 pe32;

    // Take a snapshot of all processes in the system.
    hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hProcessSnap == INVALID_HANDLE_VALUE)
    {
        return(FALSE);
    }

    pe32.dwSize = sizeof(PROCESSENTRY32);

    if (!Process32First(hProcessSnap, &pe32))
    {
        CloseHandle(hProcessSnap);          // clean the snapshot object
        return(FALSE);
    }

    BOOL    bRet = FALSE;
    do
    {
        if (!strcmp(ProcessName, pe32.szExeFile))
        {
            dwPid = pe32.th32ProcessID;
            bRet = TRUE;
            break;
        }

    } while (Process32Next(hProcessSnap, &pe32));

    CloseHandle(hProcessSnap);
    return bRet;
}

运行效果:

技术分享

C++ 根据进程名找到对应Pid

标签:bool   filename   top   not   images   spi   span   for   ssi   

原文地址:http://www.cnblogs.com/albertofwb/p/6231102.html

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