Click here to Skip to main content
15,897,090 members
Articles / Programming Languages / Visual Basic

Sticky Snap-to-Center Controls

Rate me:
Please Sign up or sign in to vote.
4.76/5 (20 votes)
17 Sep 2008CPOL2 min read 47.5K   1.1K   59  
Make your controls snap the cursor to their center and hold it for a short time.
Public Class Form1

    ' Starting time of the Snap Hold
    Private dSnapStart As Date
    ' When the Snap Hold should break
    Private dSnapEnd As Date
    ' Duration of the Snap Hold - set this value to 
    ' determine how long we hold the cursor
    Private dReleaseTime As Double = 250

    Private Sub SnapToCenter(ByVal control As Control)
        Dim objPoint As Point
        ' get the center of the control
        objPoint.X = control.Width / 2
        objPoint.Y = control.Height / 2

        Cursor.Position = control.PointToScreen(objPoint)
    End Sub

    Private Sub StartSnap(ByVal sender As System.Object, ByVal e As System.EventArgs)
        SnapToCenter(CType(sender, Control))
        dSnapStart = Date.Now
        dSnapEnd = dSnapStart.AddMilliseconds(dReleaseTime)
    End Sub

    Private Sub CheckSnap(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        If Date.Now < dSnapEnd Then
            SnapToCenter(CType(sender, Control))
        End If
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        AddHandler Button1.MouseEnter, AddressOf StartSnap
        AddHandler Button1.MouseMove, AddressOf CheckSnap
    End Sub

End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Systems Engineer ThomsonReuters Tax & Accounting
United States United States
I am a Senior System Administrator for a 400+ server ASP farm. With such a large farm and limited staff, our goal is to add as much automation as possible to the system. Most of my programming consists of intelligent slack: spending 2 hours to write a program that handles a reoccurring 10 minute manual job.

Comments and Discussions