How to “Snap” the Cursor

If you’re attempting to create that foolproof Windows application, one great technique to use is snapping the cursor to a particular control, thus anticipating the user’s next click.

The following neat little function does exactly that. Simply pass in a control to get it started: it’ll calculate the exact bottom middle location of the control and then snap the cursor to that position. Here’s the code:

Public Sub SnapToControl(ByVal Control As Control)
    ' Snaps the cursor to the bottom middle of the passed control
    Dim objPoint As Point = Control.PointToScreen(New Point(0, 0))
    objPoint.X += (Control.Width / 2)
    objPoint.Y += ((Control.Height / 4) * 3)
    Cursor.Position = objPoint
End Sub

And here’s how you might use this to snap to, say, a Button control:


You might also like...


Karl Moore


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Theory is when you know something, but it doesn't work. Practice is when something works, but you don't know why. Programmers combine theory and practice: Nothing works and they don't know why.”