WINAPI C++ GetDlgItem 不是 return 有效句柄

WINAPI C++ GetDlgItem does not return a valid handle

我正在尝试通过其 ID 获取子 Window 的句柄,但为此我必须对 ID 进行双重转换,否则它将无法工作。还有别的办法吗?我错过了什么?

WINAPI x64 C++

代码:

#define BASE_ID 100
UINT8 i = 1;
CreateWindow(... (HMENU)BASE_ID + i, ...)

//later in code

HWND hWnd = GetDlgItem(hParent, BASE_ID + i); // This won't work (Returns null handle)
HWND hWnd = GetDlgItem(hParent, (int)((HMENU)BASE_ID + i)); //Works but I get compiler warning

第一种方法在正常情况下工作得很好,你应该使用:

GetDlgItem(hParent, BASE_ID + i)

它在您的代码中失败的原因是因为 BASE_ID + i(又名 101)与您传递给 CreateWindow() 的 ID 不同。

当调用 CreateWindow() 时,您首先通过自身转换 BASE_ID 常量,然后将 i 添加到该指针,从而调用指针算法,最终产生不同的 ID (32 位上为 104,64 位上为 108)比您预期的 (101)。

因此,GetDlgItem(hParent, BASE_ID + i) 找不到匹配的 ID,而 GetDlgItem(hParent, (int)((HMENU)BASE_ID + i)) 成功了,因为它使用了与调用 CreateWindow() 时相同的转换逻辑,从而找到了匹配的 ID .

Casting has a higher precedence than addition,所以(HMENU)BASE_ID + i被编译器解释为((HMENU)BASE_ID) + i。您需要修复括号,以便先执行加法,然后再转换结果:

CreateWindow(... (HMENU)(BASE_ID + i), ...)

然后 GetDlgItem(hParent, BASE_ID + i) 将按预期工作。