c++ - EnumWindows 不工作

标签 c++ string winapi unicode vc10

我正在创建一个 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/

相关文章:

c++ - 如何从内存中删除指针并稍后在 C++ 中恢复它们

JavaScript、UWP : Backgroundtask tracking keypress events

c - 为什么我能够像这样将新字符串重新分配给 C 中的 char 指针(ch *string = "hello"; string = "assign";)

SQL Server 转换选择一列并将其转换为字符串

c# - 为什么 Control.Invoke() 调用 PostMessage() 而不是 SendMessage()?

c++ - 为什么在 IUserNotificationCallback COM 对象上查询 IMarshall 接口(interface)?

c++ - 如何按除数对数组元素进行排序?

c++ - 按顺序查找boost::multi_index,按顺序获取下一个元素

c++ - QGridLayout 3x3 网格调整大小小部件

c++ - vector push_back 不起作用 c++