我是C ++的新手,几周前我开始学习。 目前我正试图在动态字符串数组中存储具有特定类名的所有窗口的标题。 到目前为止,我将LIST定义为全局变量,但我想使用本地变量并将其传递给EnumWindows函数。
string* LIST=new string[10];
int N;
int main(){
N=0;
EnumWindows((WNDENUMPROC)CreateList,0);
for(int i=0;i<N;i++){
cout << LIST[i]<< endl;
}
return 0
}
BOOL CreateList(HWND hWnd, long lParam){
char TitleArray[255], ClassArray[255];
GetWindowText(hWnd,TitleArray,254);
GetClassName(hWnd,ClassArray,254);
string ClassString=ClassArray;
string TitleString=TitleArray;
if (ClassString=="CLASS_NAME"){
LIST[N]=TitleString;
N++;
}
return TRUE;
}
答案 0 :(得分:2)
EnumWindows的第二个参数记录为:
要传递给回调函数的应用程序定义值。
由于您需要将应用程序定义的值传递给回调函数,只需这样做,例如:
int main() {
std::vector<std::string> windowTitles;
::EnumWindows(&CreateList, reinterpret_cast<LPARAM>(&windowTitles));
// ...
}
要在回调中检索指向窗口标题容器的指针, lParam 参数需要恢复其类型:
BOOL CALLBACK CreateList(HWND hWnd, LPARAM lParam) {
std::vector<std::string>& windowTitles =
*reinterpret_cast<std::vector<std::string>*>(lParam);
// Use windowTitles, e.g. windowTitles.push_back(TitleString);
// ...
}
请特别注意,您的CreateList
签名是错误的。它缺少一个调用约定(CALLBACK
)以及第二个参数使用错误的类型(long
即使在64位Windows中也是32位宽)。您无法使用long
类型的参数安全地传递指针,即使在32位Windows中也是如此(long
已签名)。让编译器通过删除EnumWindows
电话中的C风格演员来帮助您。