Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleLet the user drag a control to a new position
Keywordsdrag control, move control
CategoriesControls
 
If Shift is pressed, the MouseDown event handler starts dragging the control.

The MouseMove event handler determines the control's new position, making sure it stays on the form, and repositions the control accordingly.

The MouseUp event handler ends the drag.

 
' Start dragging.
Private Sub Picture1_MouseDown(Button As Integer, Shift As _
    Integer, X As Single, Y As Single)
    If Shift And vbShiftMask Then
        m_Dragging = True
        m_StartX = X
        m_StartY = Y
    End If
End Sub

' Continue dragging.
Private Sub Picture1_MouseMove(Button As Integer, Shift As _
    Integer, X As Single, Y As Single)
Dim new_x As Single
Dim new_y As Single

    If Not m_Dragging Then Exit Sub

    new_x = Picture1.Left + (X - m_StartX)
    If new_x < 0 Then
        new_x = 0
    ElseIf new_x > ScaleWidth - Picture1.Width Then
        new_x = ScaleWidth - Picture1.Width
    End If

    new_y = Picture1.Top + (Y - m_StartY)
    If new_y < 0 Then
        new_y = 0
    ElseIf new_y > ScaleHeight - Picture1.Height Then
        new_y = ScaleHeight - Picture1.Height
    End If

    Picture1.Move new_x, new_y
End Sub

' End dragging.
Private Sub Picture1_MouseUp(Button As Integer, Shift As _
    Integer, X As Single, Y As Single)
    If m_Dragging Then m_Dragging = False
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated