Visual Basic Concepts

Controlling When Dragging Starts or Stops

See Also

Visual Basic has a Manual setting for the DragMode property that gives you more control than the Automatic setting. The Manual setting allows you to specify when a control can and cannot be dragged. (When DragMode is set to Automatic, you can always drag the control as long as the setting isn't changed.)

For instance, you may want to enable dragging in response to MouseDown and MouseUp events, or in response to a keyboard or menu command. The Manual setting also allows you to recognize a MouseDown event before dragging starts, so that you can record the mouse position.

To enable dragging from code, leave DragMode in its default setting (0-Manual). Then use the Drag method whenever you want to begin or stop dragging an object. Use the following Visual Basic constants to specify the action of the Drag argument.

Constant Value Meaning
vbCancel 0 Cancel drag operation
vbBeginDrag 1 Begin drag operation
vbEndDrag 2 End drag operation

The syntax for the Drag method is as follows:

[object.]Drag action

If action is set to vbBeginDrag, the Drag method initiates dragging of the control. If action is set to vbEndDrag, the control is dropped, causing a DragDrop event. If action is set to vbCancel, the drag is canceled. The effect is similar to giving the value vbEndDrag, except that no DragDrop event occurs.

Building on the example given in "Responding When the User Drops the Object" earlier in this chapter, you can add a MouseDown event for Image1 that illustrates the Drag method. Set the Image1 DragMode property to 0-Manual, then add the following procedure:

Private Sub Image1_MouseDown(Button As Integer, _
      Shift As Integer, X As Single, Y As Single)
   Image1.Drag vbBeginDrag
   Set Image1.DragIcon = LoadPicture("c:\Program _
      files\ Microsoft Visual _
      Basic\Icons\Dragdrop\Dragfldr.ico")
End Sub

Adding a DragOver event procedure to Image2 allows you to terminate dragging when the source enters the target. This example closes the file cabinet when Image1 is passed over Image2.

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

Adding a third Image control to the form demonstrates canceling a drag operation. In this example the Image3 Picture property contains an icon of a trash can. Using the DragOver event and the source argument, dragging the files over Image3 cancels the drag operation.

Private Sub Image3_DragOver(Source As Control, _
      X As Single, Y As Single, State As Integer)
   Source.Drag vbCancel
End Sub

For More Information   See "Drag-and-Drop Constants" in the Language Reference.