问题描述
我使用了EnumChildWindows
,并且可以获得所有子窗口中的Handle
,ClassName
和WindowText
。但我也想获取所有子窗口的Rectangle
。有可能吗?
这是我的代码:
#include <iostream>
#include <windows.h>
using namespace std;
BOOL CALLBACK EnumWindowsProc(HWND hwnd,LParaM lParam)
{
char class_name[100];
char title[100];
GetClassNameA(hwnd,class_name,sizeof(class_name));
GetwindowTextA(hwnd,title,sizeof(title));
cout <<"Window name : "<<title<<endl;
cout <<"Class name : "<<class_name<<endl;
cout <<"hwnd : "<<hwnd<<endl<<endl;
return TRUE;
}
int main()
{
POINT pt;
Sleep(3000);
GetCursorPos(&pt);
HWND hwnd = WindowFromPoint(pt);
HWND hwndParent = GetParent(hwnd);
EnumChildWindows(hwndParent,EnumWindowsProc,0);
system("PAUSE");
return 0;
}
此外,如何存储每个子窗口的所有数据(句柄,类名,窗口文本,矩形)?也许在矢量列表中?
解决方法
对于第一个问题,您可以看看here。
对于第二个问题,您可以定义一个包含所需字段的结构,例如
#include <iostream>
#include <windows.h>
#include <vector>
struct MyWindow {
HWND handle_;
std::string name_;
std::string text_;
RECT rect_;
MyWindow(HWND handle,const std::string& name,const std::string& text,RECT rect): handle_{handle},name_{name},text_{text},rect_{rect}{}
};
BOOL CALLBACK EnumWindowsProc(HWND hwnd,LPARAM lParam)
{
char name[100];
char text[100];
RECT rect{0};
GetClassNameA(hwnd,name,sizeof(name));
GetWindowTextA(hwnd,text,sizeof(text));
GetWindowRect(hwnd,&rect);
std::vector<MyWindow>* myVec = reinterpret_cast<std::vector<MyWindow>*>(lParam);
if (myVec) {
myVec->emplace_back(MyWindow(hwnd,std::string(name),std::string(text),rect));
} else {
// Pointer to vector is NULL,handle accordingly
return FALSE;
}
return TRUE;
}
int main()
{
POINT pt;
Sleep(3000);
std::vector<MyWindow> myChildWindows;
GetCursorPos(&pt);
HWND hwnd = WindowFromPoint(pt);
HWND hwndParent = GetParent(hwnd);
EnumChildWindows(hwndParent,EnumWindowsProc,reinterpret_cast<LPARAM>(&myChildWindows));
for (const auto & childWindow: myChildWindows) {
std::cout <<"Window name : "<< childWindow.name_ << std::endl;
std::cout <<"Class name : "<< childWindow.text_<< std::endl;
std::cout <<"hwnd : "<< childWindow.handle_<< std::endl;
std::cout << "Rect: " << childWindow.rect_.left << "/" << childWindow.rect_.right << std::endl;
std::cout << "---" << std::endl;
}
system("PAUSE");
return 0;
}
编辑
我添加了更多代码和说明。这个示例应该可以编译并正常运行。
std::vector
是一个序列容器,封装了动态大小数组1。
在主函数中声明myChildWindows
时,它会初始化为一个空向量,其中可以包含MyWindow
类型的对象。您可以动态地向该向量添加和删除对象,即,您不必在编译时指定向量的大小,例如使用数组。然后,我们将指向此向量的指针传递给您的回调EnumWindowsProc
。在此回调中,我们使用此指针将MyWindow
类型的Object添加到向量中。当EnumChildWindows
返回时,我们可以通过打印矢量中包含的每个对象来查看矢量。