枚举窗口不工作

EnumWindows not working

本文关键字:工作 窗口 枚举      更新时间:2023-10-16

我正在创建一个dll文件

我代码:

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam);
void test() {
    EnumWindows(EnumWindowsProc, NULL);
}
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
    char class_name[80];
    char title[80];
    GetClassName(hwnd, (LPWSTR) class_name, sizeof(class_name));
    GetWindowText(hwnd, (LPWSTR) title,sizeof(title));
    std::string titlas(title);
    std::string classas(class_name);
    Loggerc(titlas);
    Loggerc("Gooing");
    return TRUE;
}

那么我就调用test()

日志中titlas为空,code停止。

当我用CodeBlock在Win32应用程序中尝试这段代码时,一切正常,所有的标题都显示出来了。但是在dll中,它不起作用。

问题在哪里?

char class_name[80];
char title[80];
GetClassName(hwnd, (LPWSTR) class_name, sizeof(class_name));
GetWindowText(hwnd, (LPWSTR) title,sizeof(title));
std::string titlas(title);
std::string classas(class_name);

考虑到自VS2005以来默认已在Unicode模式(而不是ANSI/MBCS)中构建,并且您拥有那些(丑陋的c风格)(LPWSTR)类型转换,我假设您在将基于字符的字符串缓冲区传递给GetClassName()和GetWindowText()等api时遇到编译时错误,并且您试图用类型转换修复这些错误。
这是错误的。编译器实际上是在帮助你处理这些错误,所以请遵循它的建议,而不是将编译器错误抛掉。

假设Unicode构建,您可能希望使用 wchar_t std::wstring 代替charstd::string,并使用 _countof() 代替sizeof()来获取wchar_t s中的缓冲区大小,而不是以字节(char s)。

例如:

// Note: wchar_t used instead of char
wchar_t class_name[80];
wchar_t title[80];
// Note: no need to cast to LPWSTR (i.e. wchar_t*)
GetClassName(hwnd, class_name, _countof(class_name));
GetWindowText(hwnd, title, _countof(title));
// Note: std::wstring used instead of std::string
std::wstring titlas(title);
std::wstring classas(class_name);

如果你的代码的其他部分使用std::string,你可能想从存储在std::wstring(由Windows api返回)的utf -16编码的文本转换为utf -8编码的文本,并将其存储在std::string实例。