Is it normal for an hwnd to have its high bit set?

北城以北 提交于 2019-12-12 05:38:15

问题


I'm passing my HWND to a sub-process so it can send me messages back on its progress. Occasionally I never receive any messages from the sub-process. While investigating, I've found that GetSafeHwnd() of which I'm passing to the subprocess seems to be returning values I don't expect.

For example: 0xffffffffa5400382

Based on that, I can probably deduce that I'm not properly converting that value to/from an int64/string properly. I can fix that. But what I find odd is that this hwnd just doesn't look right?

Are there scenarios where an HWND can have it's high bit set? Is this a normal window, or is there something special about the hwnd to end up like that?

I'm in C++, this is an CDialog based application window.


回答1:


The result you are seeing comes from sign extension of the handle value to a 64-bit integer. The actual handle value is 0xa5400382, because handle values are always in the 32-bit range, even if the process is 64-bit!

So you should cast the HWND to std::uint32_t instead and convert that to string (or the other way around).

Convert HWND to wstring:

HWND hwnd = GetSafeHwnd();
std::uint32_t handleValue = reinterpret_cast<std::uint32_t>( hwnd );
std::wstring handleValueStr = std::to_wstring( handleValue );

Convert wstring to HWND:

try
{
    std::uint32_t handleValue = std::stoul( someString );
    HWND handle = reinterpret_cast<HWND>( handleValue );
}
catch( std::exception& e )
{
    // Handle string conversion error
}

The try/catch block is required because std::stoul() may throw exceptions if the conversion fails.



来源:https://stackoverflow.com/questions/43012454/is-it-normal-for-an-hwnd-to-have-its-high-bit-set

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!