枚举进程子窗口(Win32, C++)

本文介绍了一种改进的窗口枚举方法,结合`EnumProcessWindows`和`FindWindowEx`,确保在查找过程中不会遗漏子窗口,特别关注指定进程ID的窗口,可用于内容社区中的技术分享。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 遇到需要枚举窗口的操作, 发现使用EnumWindows和EnumChildWindows枚举的窗口不完整, 于是参考 SystemInformer 的写法整理了一下这个功能比较全面的枚举方法.

#include <windows.h>
#include <tchar.h>
#include <string>
#include <map>
#include <locale.h>

#ifdef _UNICODE
using _tstring = std::wstring;
#else
using _tstring = std::string;
#endif

typedef struct _WND_INFO
{
    HWND hWnd;
    DWORD dwPid;
    DWORD dwTid;
    _tstring strClass;
    _tstring strText;

}WND_INFO;

void _EnumProcessWindows(std::map<HWND, WND_INFO>& infos, HWND hWnd, DWORD dwPid)
{
    HWND childWindow = NULL;
    ULONG nMaxTimes = 0x4000;

    //使用 FindWindowEx 函数搜索子窗口
    while (nMaxTimes > 0 && (childWindow = ::FindWindowEx(hWnd, childWindow, NULL, NULL)))
    {
        ULONG processId = 0;
        ULONG threadId = 0;

        threadId = ::GetWindowThreadProcessId(childWindow, &processId);

        if (dwPid == processId)
        {
            TCHAR szClassBuf[MAX_PATH] = { 0 };
            TCHAR szTextBuf[MAX_PATH] = { 0 };
            ::GetClassName(childWindow, szClassBuf, _countof(szClassBuf));
            ::GetWindowText(childWindow, szTextBuf, _countof(szTextBuf));

            WND_INFO info;
            info.hWnd = childWindow;
            info.dwPid = processId;
            info.dwTid = threadId;
            info.strClass = szClassBuf;
            info.strText = szTextBuf;

            infos.insert(std::make_pair(childWindow, info));
        }

        nMaxTimes--;
    }
}

std::map<HWND, WND_INFO> EnumProcessWindows(DWORD dwPid)
{
    std::map<HWND, WND_INFO> infos;

    //枚举 桌面窗口 的子窗口
    _EnumProcessWindows(infos, ::GetDesktopWindow(), dwPid);

    //枚举 仅消息窗口 的子窗口
    _EnumProcessWindows(infos, HWND_MESSAGE, dwPid);
    return infos;
}

int main()
{
    ::setlocale(LC_ALL, "");

    std::map<HWND, WND_INFO> infos = EnumProcessWindows(23408);

    for (const auto& item : infos)
    {
        const WND_INFO& info = item.second;
        _tprintf(_T("0x%p Class:[%s] Text: [%s]\r\n"), item.first, info.strClass.c_str(), info.strText.c_str());
    }

    return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值