long to HWND (VS8 C++)

17,801

Solution 1

As long as you're sure that the LONG you have is really an HWND, then it's as simple as:

HWND hWnd = (HWND)(LONG_PTR)lParam;

Solution 2

Doing that is only safe if you are not running on a 64 bit version of windows. The LONG type is 32 bits, but the HANDLE type is probably 64 bits. You'll need to make your code 64 bit clean. In short, you will want to change the LONG to a LONG_PTR.

Rules for using pointer types:

Do not cast pointers to int, long, ULONG, or DWORD. If you must cast a pointer to test some bits, set or clear bits, or otherwise manipulate its contents, use the UINT_PTR or INT_PTR type. These types are integral types that scale to the size of a pointer for both 32- and 64-bit Windows (for example, ULONG for 32-bit Windows and _int64 for 64-bit Windows). For example, assume you are porting the following code:

ImageBase = (PVOID)((ULONG)ImageBase | 1);

As a part of the porting process, you would change the code as follows:

ImageBase = (PVOID)((ULONG_PTR)ImageBase | 1);

Use UINT_PTR and INT_PTR where appropriate (and if you are uncertain whether they are required, there is no harm in using them just in case). Do not cast your pointers to the types ULONG, LONG, INT, UINT, or DWORD.

Note that HANDLE is defined as a void*, so typecasting a HANDLE value to a ULONG value to test, set, or clear the low-order 2 bits is an error on 64-bit Windows.

Share:
17,801
Admin
Author by

Admin

Updated on August 04, 2022

Comments

  • Admin
    Admin over 1 year

    How can I cast long to HWND (C++ visual studio 8)?

    Long lWindowHandler;
    HWND oHwnd = (HWND)lWindowHandler;
    

    But I got the following warning:

    warning C4312: 'type cast' : conversion from 'LONG' to 'HWND' of greater size

    Thanks.

  • Admin
    Admin over 15 years
    Thanks for your reply. I tried that and got a warning: warning C4312: 'type cast' : conversion from 'LONG' to 'HWND' of greater size any suggestions? Thanks.
  • ehsun7b
    ehsun7b about 12 years
    I think this is the best answer, (HWND) long_ver does not work for me!
  • dst
    dst almost 7 years
    While your advice is correct for pointers, see this answer on handle lengths (or the corresponding MSDN article)– HWND only uses the lowest 32 bits and thus is safe across process bounds.