Practical Web Programming

Wednesday, February 06, 2008

Drag PictureBox at Runtime in Visual Basic

The source codes below shows how you can drag a picturebox at runtime. To test this, copy and paste code to the declaration section of a form with a picturebox on it.

Private dblX As Double, dblY As Double
Private bolMove As Boolean

Private Sub cmdClose_Click()
Unload Me
End Sub

Private Sub Picture1_MouseDown(Button As Integer, _
Shift As Integer, _
X As Single, Y As Single)
If Button = 1 And Not bolMove Then
bolMove = True
dblX = X
dblY = Y
End If
End Sub

Private Sub Picture1_MouseMove(Button As Integer, _
Shift As Integer, _
X As Single, Y As Single)
Dim tmpy As Integer
Dim tmpx As Integer

If bolMove Then
If dblY > Y Then 'scroll up
tmpy = (dblY - Y) '* 100
Me.Picture1.Top = Me.Picture1.Top - tmpy
Else 'scroll down
tmpy = (Y - dblY) '* 100
Me.Picture1.Top = Me.Picture1.Top + tmpy
End If
If dblX > X Then 'scroll right
tmpx = (dblX - X) '* 100
Me.Picture1.Left = Me.Picture1.Left - tmpx
Else 'scroll left
tmpx = (X - dblX) '* 100
Me.Picture1.Left = Me.Picture1.Left + tmpx
End If
End If
End Sub

Private Sub Picture1_MouseUp(Button As Integer, _
Shift As Integer, _
X As Single, Y As Single)
bolMove = False
End Sub


Radi said...

thanks for the code. But unfortunately, its not working on mine. I'm using VB 2008, by the way.

But it gives me the idea of how to drag n drop picturebox runtime :)

the X and Y variable is the location of mouse pointer, correct?
How do you get the position of mouse pointer without using that sub?
That's my only problem. Looking forward for your reply :)

kabalweg said...


I wrote this code in VB6 and wasn't able to wrote something in VB 2008 ( But I'm sure you can pick idea from this as VB 2008 as much similar to VB6 than the early version of

In your first question, the answer is correct, but I can't help you with the second as I focus in PHP now.

Recent Post