zoukankan      html  css  js  c++  java
  • C++ Windows 下 根据进程名获取进程ID 以及该进程下所有窗口的句柄

    #include <windows.h>
    #include <stdint.h>
    #include <tlhelp32.h>
    #include <stdio.h>
    #include <iostream>
    #include <vector>
    
    typedef struct EnumHWndsArg
    {
        std::vector<HWND> *vecHWnds;
        DWORD dwProcessId;
    }EnumHWndsArg, *LPEnumHWndsArg;
    
    HANDLE GetProcessHandleByID(int nID)//通过进程ID获取进程句柄
    {
        return OpenProcess(PROCESS_ALL_ACCESS, FALSE, nID);
    }
    
    DWORD GetProcessIDByName(const char* pName)
    {
        HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
        if (INVALID_HANDLE_VALUE == hSnapshot) {
            return NULL;
        }
        PROCESSENTRY32 pe = { sizeof(pe) };
        for (BOOL ret = Process32First(hSnapshot, &pe); ret; ret = Process32Next(hSnapshot, &pe)) {
            if (strcmp(pe.szExeFile, pName) == 0) {
                CloseHandle(hSnapshot);
                return pe.th32ProcessID;
            }
            //printf("%-6d %s
    ", pe.th32ProcessID, pe.szExeFile);
        }
        CloseHandle(hSnapshot);
        return 0;
    }
    
    BOOL CALLBACK lpEnumFunc(HWND hwnd, LPARAM lParam)
    {
        EnumHWndsArg *pArg = (LPEnumHWndsArg)lParam;
        DWORD  processId;
        GetWindowThreadProcessId(hwnd, &processId);
        if (processId == pArg->dwProcessId)
        {
            pArg->vecHWnds->push_back(hwnd);
            //printf("%p
    ", hwnd);
        }
        return TRUE;
    }
    
    void GetHWndsByProcessID(DWORD processID, std::vector<HWND> &vecHWnds)
    {
        EnumHWndsArg wi;
        wi.dwProcessId = processID;
        wi.vecHWnds = &vecHWnds;
        EnumWindows(lpEnumFunc, (LPARAM)&wi);
    }
    
    int32_t main()
    {
        DWORD pid = GetProcessIDByName("notepad++.exe");
        printf("pid = %u
    ", pid);
        if (pid != 0)
        {
            std::vector<HWND> vecHWnds;
            GetHWndsByProcessID(pid, vecHWnds);
            printf("vecHWnds.size() = %u
    ", vecHWnds.size());
            for (const HWND &h : vecHWnds)
            {
                HWND parent = GetParent(h);
                if (parent == NULL)
                {
                    printf("%p --->Main Wnd
    ", h);
                }
                else
                {
                    printf("%p %p
    ", h, parent);
                }
            }
        }
        getchar();
        return S_OK;
    }

  • 相关阅读:
    Java代理(静态/动态 JDK,cglib)
    Java数据库基础(JDBC)
    Servlet基础(工作原理、生命周期)
    Java XML DOM解析(xPath)
    java 文件操作
    从源码看集合ArrayList
    全面理解java异常机制
    python3 利用pip安装ipython notebook
    Centos的一个find命令配合rm删除某天前的文件
    在Pandas中直接加载MongoDB的数据
  • 原文地址:https://www.cnblogs.com/tangxin-blog/p/6077746.html
Copyright © 2011-2022 走看看