RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB7
Expertise: beginner
Dec 2, 2002

Get Mouse Position Anywhere, Anytime

Some control events provide the mouse pointer's current position within the control's client area; others provide only the screen coordinates of the mouse pointer (the same as returned by Cursor.Position). Is there a function that tells you where the mouse is positioned within a specific control? Well, no...

Cursor.Position is handy for getting the mouse pointer's location whenever you want, but how do you translate it into the relative position of the mouse within a particular control? The brute force way would be to calculate the X and Y offset of the control, based on its position in its parent, and its parent's position in the next parent, on up to the form. And you would also have to calculate the height of the titlebars of any forms, and the widths of any borders, of all the containers between the control and the desktop. Although this is possible (and might make a great classroom puzzle for a .NET object model workshop), it's obvious that a mouse-oriented GUI must have a better way of doing this.

In fact, the only reason this tip is needed is that the solution is very hard to find in the .NET documentation. Because searching for it involves some extremely common keywords (mouse, pointer, position, etc.), one could search unsuccessfully for a long time. Interestingly, the solution doesn't have anything (directly) to do with these keywords. In fact, the function isn't even mentioned in the VB.NET docs -- only in the .NET Framework Class Library. And precious little info there, either.

If you started with a close study of all the base Control methods, you'd probably run across this.

The solution is to convert the screen coordinates (which are returned as a Point object by the Cursor.Position method) into "client" coordinates (relative to the top left corner of the client area of the control in question). This is done with the PointToClient() method found in virtually every .NET Windows control that has a GUI:

Dim LocalMousePosition as Point
LocalMousePosition = myControl.PointToClient(Cursor.Position)
Debug.WriteLine("X = " & LocalMousePosition.X & ", " & LocalMousePosition.Y)
Not surprisingly, there is a corresponding complementary method which converts a client position to global screen coordinates:
If Cursor.Position = myControl.PointToScreen(LocalMousePosition) Then 
End If
(The Cursor object is located in the System.Windows.Forms namespace.)
Allen Cobb
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date