gpt4 book ai didi

c++ - EnumWindows 不工作

转载 作者:行者123 更新时间:2023-11-28 02:01:44 26 4
gpt4 key购买 nike

我正在创建一个 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 为空,代码停止。

当我在带有 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_tstd::wstring 而不是 charstd::string_countof() 而不是 sizeof () 获取 wchar_t 中的缓冲区大小,不是 以字节 (chars) 为单位。

例如:

// 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 中的 UTF-16 编码文本进行转换(返回通过 Windows API)转换为 UTF-8 编码的文本并将其存储在 std::string 实例中。

关于c++ - EnumWindows 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39274583/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com