I find myself writing a fair amount of custom controls. Frequently, I find myself wanting to find the position of the mouse relative to my control. The MouseDown, MouseDrag, etc. events have this info, but if you need this in the Paint event, you must either save it to a property or get it from the system. We're exploring the latter, as it's not as simple as you might think.
System.MouseX and System.MouseY will tell you where the mouse is. You might think that simply using System.MouseX - Self.Left is sufficient - but it's not. Self.Left and Self.Top only return values relative to the parent window. In today's REALbasic, ContainerControls come into play. In fact, multiple layers of ContainerControls can occur. Then, finding your control's true position on screen can become difficult.
The solution is a method I use call TrueWindow, that extends any Window (and thus ContainerControl) or RectControl. It traverses up the Window.Parent chain until it hits a Window that is not a ContainerControl.
Function TrueWindow(Extends R As RectControl) As Window
Return r.window.truewindow
End Function
Function TrueWindow(Extends W As Window) As Window
If w IsA containercontrol Then
Return containercontrol(w).window.truewindow
Else
Return w
End
End Function
Now technically, this will be enough. But I like to use a couple other tricks too. I usually create a structure, we'll call it ZAZRect, which has four integer properties: Left, Top, Width, and Height. I also create two extender methods for it: Right() and Bottom() which just calculate that for me.
I then use this nice TrueBoundary() method to instantly get the bounding rect of any control relative to the user's screen:
Function TrueBoundary(Extends C As RectControl) As ZAZRect
Dim r As zazrect
r.height = c.height
r.width = c.width
r.top = c.top
r.left = c.left
Dim w As window = c.window
While w IsA containercontrol
r.top = r.top + w.top
r.left = r.left + w.left
w = containercontrol(w).window
Wend
r.top = r.top + w.top
r.left = r.left + w.left
Return r
End Function
So there's some ground work for some upcoming tutorials I plan to write.