Get Mouse Position Anywhere, Anytime

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.

See also  Why ChatGPT Is So Important Today

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     Debug.WriteLine("Yes!")End If

(The Cursor object is located in the System.Windows.Forms namespace.)


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist