zoukankan      html  css  js  c++  java
  • C++ 根据进程名找到对应Pid

    // 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]
    ", ListApps[i], dwPid);
            }
            else
            {
                printf("[%s] [Not Found]
    ", 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;
    }

    运行效果:

  • 相关阅读:
    机器学习之朴素贝叶斯
    机器学习之KNN
    格式化数字
    web.xml中load-on-startup的作用
    ExecutorService线程池
    201404转成 2014.04
    DBCP连接池配置示例
    java 写文本换行
    打印IP 来源
    MySQL分库分表的一些技巧
  • 原文地址:https://www.cnblogs.com/albertofwb/p/6231102.html
Copyright © 2011-2022 走看看