làm cho bạn với commandbutton1, với 2, 3 tương tự.
(bạn nên đặt tên cho các buttons, để nguyên vậy khó quản về sau)
Dim XBegin As Single, YBegin As Single, LeftBegin As Single, TopBegin As Single
Private Sub CommandButton1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
XBegin = X
YBgin = Y
LeftBegin = CommandButton1.Left
TopBegin = CommandButton1.Top
End Sub
Private Sub CommandButton1_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
If Button = 1 Then
CommandButton1.Left = CommandButton1.Left + X - XBegin
CommandButton1.Top = CommandButton1.Top + Y - YBegin
End If
End Sub
Private Sub CommandButton1_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
Dim CtrDrop As Control
Set CtrDrop = dropToControl(CommandButton1, X, Y)
If Not CtrDrop Is Nothing Then
CommandButton1.Left = CtrDrop.Left
CommandButton1.Top = CtrDrop.Top
CtrDrop.Left = LeftBegin
CtrDrop.Top = TopBegin
Else
CommandButton1.Left = LeftBegin
CommandButton1.Top = TopBegin
End If
End Sub
Private Function dropToControl(MyControl As Control, X As Single, Y As Single) As Control
Dim Ctr As Control, XDrop As Single, YDrop As Single
XDrop = MyControl.Left + X
YDrop = MyControl.Top + Y
For Each Ctr In Me.Controls
If Ctr.Name <> MyControl.Name Then
If XDrop >= Ctr.Left And XDrop <= Ctr.Left + Ctr.Width _
And YDrop >= Ctr.Top And YDrop <= Ctr.Top + Ctr.Height Then
Set dropToControl = Ctr
Exit For
End If
End If
Next
End Function