Free since 2005 · No login required
AT

Academic Tutorials

Learn at your own pace

site-mobile-top-banner · 320x50

Implement Drag and Drop in Your Windows Forms Applications

Added 31 Jul 2008

I n general, when a user drags and drops data from an external application onto your Windows application, you need to determine the structure of the data being passed in and devise the appropriate mechanism to use the data.
However, not many developers take the effort to implement drag and drop functionality in their applications. While it does take considerable effort to implement, adding support for drag and drop to your application will greatly increase its usefulness. This article shows you how to implement drag and drop functionality in your Windows Forms application.
Drag and Drop Event Handlers
To understand how you can drag objects from one control onto another control, you need to become acquainted with a couple of event handlers. Consider the example in , which shows the process of dragging an image displayed in one PictureBox control to another PictureBox. To implement the drag and drop feature, you write code for both controls.

Code for Dragged Control
The MouseDown or MouseMove event is probably a good starting point to load the data that is going to be dragged. In this case, you will copy the image stored in the left PictureBox control.

The QueryContinueDrag event allows you to know the outcome of the drag operation, i.e., whether the user eventually drops the item. If the dragging is a move operation and the user successfully executes it, you may need to remove the image on the left PictureBox control.

The control constantly fires the GiveFeedBack event during the drag operation. You can handle this event if you wish to modify the appearance of the mouse pointer.

Code for Control Accepting Drop
When the mouse enters the control that will accept the drop, the control fires the DragEnter event. This is usually the event that you need to service to change the mouse pointer to reflect the action it is performing (such as copy, move, etc). You can also modify the appearance of the control so that it is obvious to the user that the control is a drop target.

While the mouse hovers over the control that will accept at drop, the control fires the DragOver event. The control fires this event continuously as long as the mouse is over the target control. You can use either this event or the DragEnter event to change the appearance of the mouse pointer.

When the mouse leaves the control that accepts a drop, the control fires the DragLeave event. You usually service this event if you modified the control's appearance during the DragEnter event.

When a user drops an object over the control that accepts a drop, the control fires the DragDrop event, which you can handle appropriately. Using the example from Figure 1, you would load the right PictureBox control with the image that the user drags from the left PictureBox control.