Drag And Drop

Tips >> Visual Basic

MAKE WEB APPLICATION WITHOUT KNOWLEDGE OF CODING? CLICK HERE

 

Setting the DragMode Property of a control to "Automatic", allows a control to be dragged. For an action to be performed, a corresponding DragDrop Event will need to exist.
For example
, to reposition the control on a different part of the Form, the Form would require a DragDrop event.

 

 

Private Sub Form_DragDrop(Source As Control, X As Single, Y As Single)
     Source.Move X, Y
End Sub

 

 

If you try the above example, you'll notice that when you release the mouse, the top left of the control being dragged is positioned to the current mouse position, so jumps when dropped. You can alter this by taking note of the relative position on the control when it was clicked. When a control's DragDrop Property is set to Automatic, you lose the MouseDown, MouseUp, and Click Events for that control. The MouseMove Event is still available, but you get more control by setting the DragDrop Property to "Manual" (the default value for the Property), and calling the Drag method explicitly.
The following example uses a PictureBox's MouseDown Event to start the Drag operation, and get the relative position the mouse was clicked on the control, so it's dropped exactly where the mouse is released on the Form.

 

 

Option Explicit
' Variables to store the relative position of a control on MouseDown
Dim dragX As Integer, dragY As Integer
Private Sub Form_DragDrop(Source As Control, X As Single, Y As Single)
     ' Position the control with adjustments
     Source.Move X - dragX, Y - dragY
End Sub
Private Sub picFace_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
     ' Store the relative coordinates
     dragX = X
     dragY = Y
     picFace.Drag vbBeginDrag
End Sub

 

 

 

THE DRAGOVER EVENT

The DragOver Event can be used to detect whether an object is being dragged over another object. The Event fires when the mouse cursor enters the target. The Event has a State parameter which can be used to determine whether it has entered the target, is over the target or is leaving the target.

 

 

Private Sub picTarget_DragOver(Source As Control, X As Single, Y As Single, State As Integer)
     ' Only change the background colour of the Target if the
     ' Source object is a PictureBox
     If TypeOf Source Is PictureBox Then
          Select Case State
               Case vbEnter
                    picTarget.BackColor = RGB(0, 0, 0)
               Case vbOver
                    picTarget.BackColor = RGB(128, 0, 0)
               Case vbLeave
                    picTarget.BackColor = RGB(255, 255, 255)
          End Select
     End If
End Sub

 

 

If you don't find what you are looking for. Please click here to submit your query, our experts will reply soon.

 

E-mail : sales@virtualsplat.com
Phone : +91-9892413501

Whatsapp Icon +91-9967648641

Whatsapp Icon +91-9967648641