When a source control is dragged and dropped, here's what happens:
- When the mouse pointer leaves the source control, the parent form receives a single DragOver event with the State argument equal to 0.
- As the pointer moves over the form the form receives multiple DragOver events with the State argument equal to 2.
- When the source is dragged over another control on the form, the form receives a DragOver event with the State argument equal to 1 (signaling that the pointer has left the form), and the control over which the source was just dragged receives a DragOver event with the State argument equal to 0 (signaling that the pointer has entered the Form).
- When the control is dropped, the object it is currently over receives a DragDrop event.
Let's look at some examples, starting with something really simple. Create a Visual Basic project and place a Text Box and a Label on the form. Set the Text Box's DragMode property to vbAutomatic. Put the following code in the Label's DragDrop event procedure:
Private Sub Label1_DragDrop(Source As Control, _
X As Single, Y As Single)
Label1.Caption = Source.Text
When you run the project, enter some text in the Text Box then drag from the Text Box to the Label. Doing this, you'll see that the text is copied from the Text Box to the Label.
Now add some enhancements. Suppose you do not want the drag operation to be possible if the Text Box is empty. Change the Text Box's DragMode property back to the default setting of vbManual. Then, add this code to the Text Box's MouseDown event procedure:
Private Sub Text1_MouseDown(Button As Integer, _
Shift As Integer, X As Single, Y As Single)
If Len(Text1.Text) > 0 And Button = 1 Then
The If statement checks to see if the Text Box contains text and also makes sure that the left mouse button is depressed, as is traditional for drag-and-drop operations. Only if both conditions are met is a drag-drop operation started.