Error : Cannot convert char to wchat_t*

Error : Cannot convert char to wchat_t*

我正在尝试使用 GetForegroundWindow 和 GetWindowText 函数获取活动 window 标题,这是我的代码

HWND hwnd = GetForegroundWindow();
char wname[255];
GetWindowText(hwnd,wname,255);

而且每次我尝试构建项目时,我都会收到此错误消息 "Error : Error : Cannot convert char to wchat_t*"

我正在使用 c++builder xe7

那么,怎么了?

您正在以 Unicode 识别模式构建您的应用程序; a char 不够大,无法容纳 UTF-16 字符。类型系统通过为您捕获此问题,使您免于很多 潜在的头痛。要么更改为 ASCII 模式(简单但不好的解决方案),切换到在任何地方都使用宽字符串(烦人的解决方案),要么使用提供的宏在编译时根据构建参数进行选择(更烦人但最正确的解决方案)。

这就是实施上述任一解决方案后此代码片段的样子:

HWND hwnd = GetForegroundWindow();
wchar_t wname[255];
GetWindowText(hwnd, wname, 255);

HWND hwnd = GetForegroundWindow();
TCHAR wname[255];
GetWindowTextW(hwnd, wname, 255);

如果您选择构建一个支持 Unicode 的应用程序(您应该这样做),您还必须记住根据需要使用 wmain_tmain,而不是普通的无聊 main.因为Windows.

您正在调用 GetWindowText()TCHAR 版本。在您的项目选项中,您将 "TCHAR maps to" 选项设置为 wchar_t,因此 GetWindowText() 映射到 GetWindowTextW(),这需要一个 wchar_t*参数。这就是为什么你不能传入 char[] 缓冲区。

因此,您需要:

  1. "TCHAR maps to" 更改为 char 以便 GetWindowText() 映射到 GetWindowTextA() (同样类似影响代码中所有其他基于 TCHAR 的 API 函数调用。只有在将遗留的 pre-Unicode 代码迁移到 C++Builder 2009+ 时才使用此方法。

  2. 更改代码以使用 TCHAR

    TCHAR wname[255];
    GetWindowText(hwnd,wname,255);
    
  3. 更改您的代码以直接使用 GetWindowText() 的 Ansi 或 Unicode 版本:

    char wname[255];
    GetWindowTextA(hwnd,wname,255);
    

    wchar_t wname[255];
    GetWindowTextW(hwnd,wname,255);