GetWindowRect API from within a control
Posted on 1998-11-19
Here's something which is seemingly correct (I think), but it doesn't work.
I've placed the following inside the control. The purpose is to provide a property get to obtain the screen coordinates of the control itself. Ie, coordinates relative to the screen, and not just the container.
Private Declare Function GetWindowRect Lib "user32" (ByVal hwnd As Long, lpRect As RECT) As Long
Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
Dim ControlRect As RECT
Public Property Get X_Left() As Long
GetWindowRect UserControl.hwnd, ControlRect
X_Left = ControlRect.Left
(there are actually 3 other property get for the other 3 values, but it doesn't matter since they are basically the same)
The GetWindowRect API is supposed to give the rect in screen coordinates, but it doesn't seem to work if this is inside the code of a control.
At runtime, reading the property actually returns a 0. Effectively, the 4 values of the rect returns, but the top left hand corner is 0,0. I.e. the rect returned is actually (0,0,something,something). The size of the control is returned correctly, but the position is wrong.
I've tried the same code on a form, but changed 'UserControl' to 'Picture1', and placed a dummy picture control, just to try obtaining the coordinates of the pic control. It works correctly in this case.
I know that by calculating the position of the control relative to the form would pretty much do what I want, but it is a requirement that the algorithm be within the control. I must be able to obtain the screen coord by just reading a control property.
That's my problem and it's giving me hard time. Any help will be greatly appreciated.
Thanks a lot in advance.