如何统计具有相同标题栏或类的窗口数量?
统计特定窗口类/标题的窗口数量
要统计符合特定类名/标题的窗口数量,你得用EnumWindows(或EnumDesktopWindows,针对当前桌面窗口)API——FindWindow确实只能返回第一个匹配的窗口,没法遍历所有,所以必须靠枚举窗口的方式实现。
核心实现思路
- 调用
EnumWindows,传入自定义的回调函数,它会遍历所有顶层窗口并逐个调用回调 - 在回调函数里,对每个窗口句柄:
- 用
GetWindowText获取窗口标题,或GetClassName获取窗口类名 - 对比目标字符串(比如"Visual Studio"),匹配就增加计数
- 用
- 用全局变量或结构体传递计数结果(回调函数没法直接给调用者返回值)
示例代码(C++)
#include <windows.h> #include <string> #include <algorithm> // 全局变量存计数,也可以用结构体传递更安全 int g_MatchCount = 0; std::wstring g_TargetWindowText = L"Visual Studio"; // EnumWindows会给每个顶层窗口调用这个回调函数 BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam) { wchar_t windowText[256]; GetWindowText(hwnd, windowText, sizeof(windowText)/sizeof(wchar_t)); // 不区分大小写检查标题是否包含目标字符串 std::wstring currentText(windowText); std::transform(currentText.begin(), currentText.end(), currentText.begin(), ::towlower); std::wstring targetLower = g_TargetWindowText; std::transform(targetLower.begin(), targetLower.end(), targetLower.begin(), ::towlower); if (currentText.find(targetLower) != std::wstring::npos) { g_MatchCount++; } return TRUE; // 返回TRUE继续枚举,返回FALSE停止 } int CountTargetWindows() { g_MatchCount = 0; EnumWindows(EnumWindowsProc, 0); return g_MatchCount; } // 使用示例 int main() { int vsWindowCount = CountTargetWindows(); // 输出统计结果 return 0; }
注意事项
- 要是想匹配窗口类名,把
GetWindowText换成GetClassName就行 - 如果需要统计子窗口(非顶层),可以用
EnumChildWindows,但统计应用窗口一般用顶层窗口足够 - 建议用宽字符版本的API(比如
GetWindowTextW),避免编码问题
内容的提问来源于stack exchange,提问作者bugger
相关产品推荐
相关产品推荐

