Zebra0.com

Learn to Program Step-by-Step

Drag and Drop

A Simple Drag Drop

The Flash movie below shows what the drag and drop project does:

To create this project:
  1. add a PictureBoxpictureBox to the form.
  2. Set the cursor property of PictureBox1 to "hand" hand
  3. Add the code to allow drag drop:
Public Class Form1
    'Form level variables
    Dim startPoint As Point 'the point on the picture where we clicked to start dragging
     Dim dragging As Boolean

    Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
        dragging = True
        startPoint.X = e.X
        startPoint.Y = e.Y
    End Sub 'PictureBox1_MouseDown

    Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
        If dragging = True Then
            'without  the if, the picture will start moving even when the mouse is not down
            'instead of putting the picture the same place as the mouse,
            'we need to offset it by the point that was clicked to start dragging
            PictureBox1.Left = PictureBox1.Left + e.X - startPoint.X
            PictureBox1.Top = PictureBox1.Top + e.Y - startPoint.Y
        End If
    End Sub 'PictureBox1_MouseMove


    Private Sub PictureBox1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseUp
        dragging = False
    End Sub 'PictureBox1_MouseUp

End Class
Last modified: January 30 2025 14:19:09.