Using SetWindowLong I set the offset, and put the address of the object of my class there. But, the function stubbornly returns 0. Tell me, what is the error?

class Test { int *a; std::string test; public: Test(){} void Tests(HWND hwnd) { LONG res = SetWindowLong(hwnd, GWL_USERDATA, (LONG)this); // в res возвращается 0 return; } }; 

PS: I do it so that I can refer to the class from the window procedure.

    2 answers 2

    Well, actually, SetWindowLong returns the old value or 0 in case of an error. However, if the old value itself was 0 (which is always the case when you first call with GWL_USERDATA ), then it will be returned, of course, exactly 0 and this will not mean at all that an error has occurred.

    In other words, in the case of GWL_USERDATA on the returned value of 0 , it is still not possible to say that something is wrong. If you suspect an error has occurred, check GetLastError . (However, I nowhere see any guarantee that SetWindowLong sets last error to 0 if successful, so for reliability in this case, it makes sense to first do SetLastError(0) yourself.)

    You can also do GetWindowLong for reliability to make sure that the value was successfully recorded.

      The SetWindowLong function returns the previous value of the parameter. For GWL_USERDATA initial value is zero, so this is quite normal. If you suspect an error, you need to reset the error code via SetLastError before starting and, after starting, take it through GetLastError .

      By the way, the SetWindowLong function SetWindowLong not make sense in 64-bit applications (therefore it is better to use SetWindowLongPtr ).