Library code snippets

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:

SnapToControl(Button1)

Comments

  1. 30 Apr 2007 at 02:26
    After spending an hour or so studying "How To Implement the Snap-To Feature in Visual Basic"---from Microsoft's Knowledge Base--which describes how to cycle through each of the controls in a form (and then I added the ability to cycle through each of the contained controls in any particular control) I then discovered that this paper was written for VB5, and that there is no button property called "default button". After another half-hour search, I could find nothing that in any way indicates that the Cancel or Accept properties are associated with the buttons; these properties are associated with the controlling form instead.

    This small routine of Karl's is so much simpler and more comprehensible.
    Thanks Karl.






  2. 01 Jan 1999 at 00:00

    This thread is for discussions of How to “Snap” the Cursor.

Leave a comment

Sign in or Join us (it's free).

Karl Moore

Related podcasts

  • xpert to Expert: Inside Concurrent Basic (CB)

    "Concurrent Basic extends Visual Basic with stylish asynchronous concurrency constructs derived from the join calculus. Our design advances earlier MSRC work on Polyphonic C#, Comega and the Joins Library. Unlike its C# based predecessors, CB adopts a simple event-like syntax familiar to VB progr...

We'd love to hear what you think! Submit ideas or give us feedback