Visual Basic Concepts

Responding When the User Drops the Object

See Also

When the user releases the mouse button after dragging a control, Visual Basic generates a DragDrop event. You can respond to this event in many ways. Remember that the control doesn't automatically move to the new location, but you can write code to relocate the control to the new location (indicated by the last position of the gray outline). See "Changing the Position of a Control" for more information.

Two terms are important when discussing drag-and-drop operations: source and target.

Term Meaning
Source The control being dragged. This control can be any object except a menu, timer, line, or shape.
Target The object onto which the user drops the control. This object, which can be a form or control, recognizes the DragDrop event.

A control becomes the target if the mouse position is within its borders when the button is released. A form is the target if the pointer is in a blank portion of the form.

The DragDrop event provides three arguments: source, x, and y. The source argument is a reference to the control that was dropped onto the target.

Because source is declared As Control, you use it just as you would a control — you can refer to its properties or call one of its methods.

The following example illustrates how the source and target interact. The source is an Image control with its Picture property set to load a sample icon file representing a few file folders. Its DragMode property has been set to 1-Automatic and its DragIcon property to a sample drag-and-drop icon file. The target, also an image control, contains a picture of an open file cabinet.

Add the following procedure to the second image control's DragDrop event:

Private Sub Image2_DragDrop(Source As Control, _
      X As Single, Y As Single)
   Source.Visible = False
   Image2.Picture = LoadPicture("c:\Program _
      Files\Microsoft Visual _
      Basic\Icons\Office\Files03a.ico")
End Sub

Dragging and dropping Image1 onto Image2 causes Image1 to vanish and Image2 to change its picture to that of a closed file cabinet. Using the source argument, the Visible property of Image1 was changed to False.

Note   You should use the source argument carefully. Although you know that it always refers to a control, you don't necessarily know which type of control. For example, if the control is a text box and you attempt to refer to Source.Value, the result is a run-time error because text boxes have no Value property.

You can use the If...Then...Else statement with the TypeOf keyword to determine what kind of control was dropped.

For More Information   See "If…Then…Else" in the Language Reference and see "Programming with Objects."