Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
DoDragDrop Method
Collapse the table of content
Expand the table of content

Control.DoDragDrop Method

Begins a drag-and-drop operation.

Namespace: System.Windows.Forms
Assembly: System.Windows.Forms (in system.windows.forms.dll)

'Declaration
Public Function DoDragDrop ( _
	data As Object, _
	allowedEffects As DragDropEffects _
) As DragDropEffects
'Usage
Dim instance As Control
Dim data As Object
Dim allowedEffects As DragDropEffects
Dim returnValue As DragDropEffects

returnValue = instance.DoDragDrop(data, allowedEffects)
public DragDropEffects DoDragDrop (
	Object data, 
	DragDropEffects allowedEffects
)
public function DoDragDrop (
	data : Object, 
	allowedEffects : DragDropEffects
) : DragDropEffects

Parameters

data

The data to drag.

allowedEffects

One of the DragDropEffects values.

Return Value

A value from the DragDropEffects enumeration that represents the final effect that was performed during the drag-and-drop operation.

The allowedEffects parameter determines which drag operations can occur. If the drag operation needs to interoperate with applications in another process, data should either be a base managed class (String, Bitmap, or Metafile), or an object that implements ISerializable or IDataObject.

The following describes how and when events related to drag-and-drop operations are raised.

The DoDragDrop method determines the control under the current cursor location. It then checks to see if the control is a valid drop target.

If the control is a valid drop target, the GiveFeedback event is raised with the drag-and-drop effect specified. For a list of drag-and-drop effects, see the DragDropEffects enumeration.

Changes in the mouse cursor position, keyboard state, and mouse button state are tracked.

  • If the user moves out of a window, the DragLeave event is raised.

  • If the mouse enters another control, the DragEnter for that control is raised.

  • If the mouse moves but stays within the same control, the DragOver event is raised.

If there is a change in the keyboard or mouse button state, the QueryContinueDrag event is raised and determines whether to continue the drag, to drop the data, or to cancel the operation based on the value of the Action property of the event's QueryContinueDragEventArgs.

  • If the value of DragAction is Continue, the DragOver event is raised to continue the operation and the GiveFeedback event is raised with the new effect so appropriate visual feedback can be set. For a list of valid drop effects, see the DragDropEffects enumeration.

    NoteNote

    The DragOver and GiveFeedback events are paired so that as the mouse moves across the drop target, the user is given the most up-to-date feedback on the mouse's position.

  • If the value of DragAction is Drop, the drop effect value is returned to the source, so the source application can perform the appropriate operation on the source data; for example, cut the data if the operation was a move.

  • If the value of DragAction is Cancel, the DragLeave event is raised.

The following code example demonstrates a drag-and-drop operation between two ListBox controls. The example calls the DoDragDrop method when the drag action starts. The drag action starts if the mouse has moved more than SystemInformation.DragSize from the mouse location during the MouseDown event. The IndexFromPoint method is used to determine the index of the item to drag during the MouseDown event.

The example also demonstrates using custom cursors for the drag-and-drop operation. The example requires that two cursor files, 3dwarro.cur and 3dwno.cur, exist in the application directory, for the custom drag and no-drop cursors, respectively. The custom cursors will be used if the UseCustomCursorsCheckCheckBox is checked. The custom cursors are set in the GiveFeedback event handler.

The keyboard state is evaluated in the DragOver event handler for the right ListBox, to determine what the drag operation will be based on state of the SHIFT, CTRL, ALT, or CTRL+ALT keys. The location in the ListBox where the drop would occur is also determined during the DragOver event. If the data to drop is not a String, then the DragEventArgs.Effect is set to None in DragDropEffects. Finally, the status of the drop is displayed in the DropLocationLabelLabel.

The data to drop for the right ListBox is determined in the DragDrop event handler and the String value is added at the appropriate place in the ListBox. If the drag operation moves outside the bounds of the form, then the drag-and-drop operation is canceled in the QueryContinueDrag event handler.

Imports System
Imports System.Drawing
Imports System.Windows.Forms

Public NotInheritable Class Form1
    Inherits System.Windows.Forms.Form

    Friend WithEvents ListDragSource As System.Windows.Forms.ListBox
    Friend WithEvents ListDragTarget As System.Windows.Forms.ListBox
    Friend WithEvents UseCustomCursorsCheck As System.Windows.Forms.CheckBox
    Friend WithEvents DropLocationLabel As System.Windows.Forms.Label

    Private indexOfItemUnderMouseToDrag As Integer
    Private indexOfItemUnderMouseToDrop As Integer

    Private dragBoxFromMouseDown As Rectangle
    Private screenOffset as Point

    Private MyNoDropCursor As Cursor
    Private MyNormalCursor As Cursor

    <System.STAThread()> _
    Public Shared Sub Main()
        System.Windows.Forms.Application.Run(New Form1())
    End Sub 'Main

    Public Sub New()
        MyBase.New()

        Me.ListDragSource = New System.Windows.Forms.ListBox()
        Me.ListDragTarget = New System.Windows.Forms.ListBox()
        Me.UseCustomCursorsCheck = New System.Windows.Forms.CheckBox()
        Me.DropLocationLabel = New System.Windows.Forms.Label()

        Me.SuspendLayout()

        ' ListDragSource
        Me.ListDragSource.Items.AddRange(New Object() {"one", "two", "three", "four", _
                                                            "five", "six", "seven", "eight", _
                                                            "nine", "ten"})
        Me.ListDragSource.Location = New System.Drawing.Point(10, 17)
        Me.ListDragSource.Size = New System.Drawing.Size(120, 225)

        ' ListDragTarget
        Me.ListDragTarget.AllowDrop = True
        Me.ListDragTarget.Location = New System.Drawing.Point(154, 17)
        Me.ListDragTarget.Size = New System.Drawing.Size(120, 225)

        ' UseCustomCursorsCheck
        Me.UseCustomCursorsCheck.Location = New System.Drawing.Point(10, 243)
        Me.UseCustomCursorsCheck.Size = New System.Drawing.Size(137, 24)
        Me.UseCustomCursorsCheck.Text = "Use Custom Cursors"

        ' DropLocationLabel
        Me.DropLocationLabel.Location = New System.Drawing.Point(154, 245)
        Me.DropLocationLabel.Size = New System.Drawing.Size(137, 24)
        Me.DropLocationLabel.Text = "None"

        ' Form1
        Me.ClientSize = New System.Drawing.Size(292, 270)
        Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.ListDragSource, _
                                            Me.ListDragTarget, Me.UseCustomCursorsCheck, _
                                            Me.DropLocationLabel})

        Me.Text = "drag-and-drop Example"
        Me.ResumeLayout(False)
    End Sub

    Private Sub ListDragSource_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles ListDragSource.MouseDown

        ' Get the index of the item the mouse is below.
        indexOfItemUnderMouseToDrag = ListDragSource.IndexFromPoint(e.X, e.Y)

        If (indexOfItemUnderMouseToDrag <> ListBox.NoMatches) Then

            ' Remember the point where the mouse down occurred. The DragSize indicates
            ' the size that the mouse can move before a drag event should be started.                
            Dim dragSize As Size = SystemInformation.DragSize

            ' Create a rectangle using the DragSize, with the mouse position being
            ' at the center of the rectangle.
            dragBoxFromMouseDown = New Rectangle(New Point(e.X - (dragSize.Width / 2), _
                                                            e.Y - (dragSize.Height / 2)), dragSize)
        Else
            ' Reset the rectangle if the mouse is not over an item in the ListBox.
            dragBoxFromMouseDown = Rectangle.Empty
        End If

    End Sub

    Private Sub ListDragSource_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) Handles ListDragSource.MouseUp

        ' Reset the drag rectangle when the mouse button is raised.
        dragBoxFromMouseDown = Rectangle.Empty
    End Sub

    Private Sub ListDragSource_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) Handles ListDragSource.MouseMove

        If ((e.Button And MouseButtons.Left) = MouseButtons.Left) Then

            ' If the mouse moves outside the rectangle, start the drag.
            If (Rectangle.op_Inequality(dragBoxFromMouseDown, Rectangle.Empty) And _
                Not dragBoxFromMouseDown.Contains(e.X, e.Y)) Then

                ' Creates custom cursors for the drag-and-drop operation.
                Try
                    MyNormalCursor = New Cursor("3dwarro.cur")
                    MyNoDropCursor = New Cursor("3dwno.cur")

                Catch
                    ' An error occurred while attempting to load the cursors so use
                    ' standard cursors.
                    UseCustomCursorsCheck.Checked = False
                Finally
                    ' The screenOffset is used to account for any desktop bands 
                    ' that may be at the top or left side of the screen when 
                    ' determining when to cancel the drag drop operation.
                    screenOffset = SystemInformation.WorkingArea.Location

                    ' Proceed with the drag-and-drop, passing in the list item.                    
                    Dim dropEffect As DragDropEffects = ListDragSource.DoDragDrop(ListDragSource.Items(indexOfItemUnderMouseToDrag), _
                                                                                  DragDropEffects.All Or DragDropEffects.Link)

                    ' If the drag operation was a move then remove the item.
                    If (dropEffect = DragDropEffects.Move) Then
                        ListDragSource.Items.RemoveAt(indexOfItemUnderMouseToDrag)

                        ' Select the previous item in the list as long as the list has an item.
                        If (indexOfItemUnderMouseToDrag > 0) Then
                            ListDragSource.SelectedIndex = indexOfItemUnderMouseToDrag - 1

                        ElseIf (ListDragSource.Items.Count > 0) Then
                            ' Selects the first item.
                            ListDragSource.SelectedIndex = 0
                        End If
                    End If

                    ' Dispose the cursors since they are no longer needed.
                    If (Not MyNormalCursor Is Nothing) Then _
                        MyNormalCursor.Dispose()

                    If (Not MyNoDropCursor Is Nothing) Then _
                        MyNoDropCursor.Dispose()
                End Try

            End If
        End If
    End Sub
    Private Sub ListDragSource_GiveFeedback(ByVal sender As Object, ByVal e As GiveFeedbackEventArgs) Handles ListDragSource.GiveFeedback

        ' Use custom cursors if the check box is checked.
        If (UseCustomCursorsCheck.Checked) Then

            ' Set the custom cursor based upon the effect.
            e.UseDefaultCursors = False
            If ((e.Effect And DragDropEffects.Move) = DragDropEffects.Move) Then
                Cursor.Current = MyNormalCursor
            Else
                Cursor.Current = MyNoDropCursor
            End If
        End If

    End Sub

    Private Sub ListDragTarget_DragOver(ByVal sender As Object, ByVal e As DragEventArgs) Handles ListDragTarget.DragOver
        ' Determine whether string data exists in the drop data. If not, then
        ' the drop effect reflects that the drop cannot occur.
        If Not (e.Data.GetDataPresent(GetType(System.String))) Then

            e.Effect = DragDropEffects.None
            DropLocationLabel.Text = "None - no string data."
            Return
        End If

        ' Set the effect based upon the KeyState.
        If ((e.KeyState And (8 + 32)) = (8 + 32) And _
            (e.AllowedEffect And DragDropEffects.Link) = DragDropEffects.Link) Then
            ' KeyState 8 + 32 = CTL + ALT

            ' Link drag-and-drop effect.
            e.Effect = DragDropEffects.Link

        ElseIf ((e.KeyState And 32) = 32 And _
            (e.AllowedEffect And DragDropEffects.Link) = DragDropEffects.Link) Then

            ' ALT KeyState for link.
            e.Effect = DragDropEffects.Link

        ElseIf ((e.KeyState And 4) = 4 And _
            (e.AllowedEffect And DragDropEffects.Move) = DragDropEffects.Move) Then

            ' SHIFT KeyState for move.
            e.Effect = DragDropEffects.Move

        ElseIf ((e.KeyState And 8) = 8 And _
            (e.AllowedEffect And DragDropEffects.Copy) = DragDropEffects.Copy) Then

            ' CTL KeyState for copy.
            e.Effect = DragDropEffects.Copy

        ElseIf ((e.AllowedEffect And DragDropEffects.Move) = DragDropEffects.Move) Then

            ' By default, the drop action should be move, if allowed.
            e.Effect = DragDropEffects.Move

        Else
            e.Effect = DragDropEffects.None
        End If

        ' Gets the index of the item the mouse is below. 

        ' The mouse locations are relative to the screen, so they must be 
        ' converted to client coordinates.

        indexOfItemUnderMouseToDrop = _
            ListDragTarget.IndexFromPoint(ListDragTarget.PointToClient(New Point(e.X, e.Y)))

        ' Updates the label text.
        If (indexOfItemUnderMouseToDrop <> ListBox.NoMatches) Then

            DropLocationLabel.Text = "Drops before item #" & (indexOfItemUnderMouseToDrop + 1)
        Else
            DropLocationLabel.Text = "Drops at the end."
        End If

    End Sub

    Private Sub ListDragTarget_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs) Handles ListDragTarget.DragDrop
        ' Ensures that the list item index is contained in the data.

        If (e.Data.GetDataPresent(GetType(System.String))) Then

            Dim item As Object = CType(e.Data.GetData(GetType(System.String)), System.Object)

            ' Perform drag-and-drop, depending upon the effect.
            If (e.Effect = DragDropEffects.Copy Or _
                e.Effect = DragDropEffects.Move) Then

                ' Insert the item.
                If (indexOfItemUnderMouseToDrop <> ListBox.NoMatches) Then
                    ListDragTarget.Items.Insert(indexOfItemUnderMouseToDrop, item)
                Else
                    ListDragTarget.Items.Add(item)

                End If
            End If
            ' Reset the label text.
            DropLocationLabel.Text = "None"
        End If
    End Sub
    Private Sub ListDragSource_QueryContinueDrag(ByVal sender As Object, ByVal e As QueryContinueDragEventArgs) Handles ListDragSource.QueryContinueDrag
        ' Cancel the drag if the mouse moves off the form.
        Dim lb as ListBox = CType(sender, System.Windows.Forms.ListBox)

        If Not (lb is nothing) Then

            Dim f as Form = lb.FindForm()

            ' Cancel the drag if the mouse moves off the form. The screenOffset
            ' takes into account any desktop bands that may be at the top or left
            ' side of the screen.
            If (((Control.MousePosition.X - screenOffset.X) < f.DesktopBounds.Left) Or _
                ((Control.MousePosition.X - screenOffset.X) > f.DesktopBounds.Right) Or _
                ((Control.MousePosition.Y - screenOffset.Y) < f.DesktopBounds.Top) Or _
                ((Control.MousePosition.Y - screenOffset.Y) > f.DesktopBounds.Bottom)) Then

                e.Action = DragAction.Cancel
            End If
        End if
    End Sub
    Private Sub ListDragTarget_DragEnter(ByVal sender As Object, ByVal e As DragEventArgs) Handles ListDragTarget.DragEnter

        ' Reset the label text.
        DropLocationLabel.Text = "None"
    End Sub
    Private Sub ListDragTarget_DragLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListDragTarget.DragLeave

        ' Reset the label text.
        DropLocationLabel.Text = "None"
    End Sub
End Class

package SnipDragNDrop;

import System.*;
import System.Drawing.*;
import System.Windows.Forms.*;

public class Form1 extends System.Windows.Forms.Form
{
    private System.Windows.Forms.ListBox listDragSource;
    private System.Windows.Forms.ListBox listDragTarget;
    private System.Windows.Forms.CheckBox useCustomCursorsCheck;
    private System.Windows.Forms.Label dropLocationLabel;
    private int indexOfItemUnderMouseToDrag;
    private int indexOfItemUnderMouseToDrop;
    private Rectangle dragBoxFromMouseDown;
    private Point screenOffset;
    private Cursor myNoDropCursor;
    private Cursor myNormalCursor;

    /// The main entry point for the application.
    /** @attribute STAThread()
     */
    public static void main(String[] args)
    {
        Application.Run(new Form1());
    } //main

    public Form1()
    {
        this.listDragSource = new System.Windows.Forms.ListBox();
        this.listDragTarget = new System.Windows.Forms.ListBox();
        this.useCustomCursorsCheck = new System.Windows.Forms.CheckBox();
        this.dropLocationLabel = new System.Windows.Forms.Label();

        this.SuspendLayout();
        // listDragSource
        this.listDragSource.get_Items().AddRange(new Object[] { "one", "two", 
            "three", "four", "five", "six", "seven", "eight", "nine", "ten" });
        this.listDragSource.set_Location(new System.Drawing.Point(10, 17));
        this.listDragSource.set_Size(new System.Drawing.Size(120, 225));
        this.listDragSource.add_MouseDown(
            new System.Windows.Forms.MouseEventHandler(
            this.listDragSource_MouseDown));
        this.listDragSource.add_QueryContinueDrag(
            new System.Windows.Forms.QueryContinueDragEventHandler(
            this.listDragSource_QueryContinueDrag));
        this.listDragSource.add_MouseUp(
            new System.Windows.Forms.MouseEventHandler(
            this.listDragSource_MouseUp));
        this.listDragSource.add_MouseMove(
            new System.Windows.Forms.MouseEventHandler(
            this.listDragSource_MouseMove));
        this.listDragSource.add_GiveFeedback(
            new System.Windows.Forms.GiveFeedbackEventHandler(
            this.listDragSource_GiveFeedback));
        // listDragTarget
        this.listDragTarget.set_AllowDrop(true);
        this.listDragTarget.set_Location(new System.Drawing.Point(154, 17));
        this.listDragTarget.set_Size(new System.Drawing.Size(120, 225));
        this.listDragTarget.add_DragOver(
            new System.Windows.Forms.DragEventHandler(
            this.listDragTarget_DragOver));
        this.listDragTarget.add_DragDrop(
            new System.Windows.Forms.DragEventHandler(
            this.listDragTarget_DragDrop));
        this.listDragTarget.add_DragEnter(
            new System.Windows.Forms.DragEventHandler(
            this.listDragTarget_DragEnter));
        this.listDragTarget.add_DragLeave(
            new System.EventHandler(this.listDragTarget_DragLeave));
        // useCustomCursorsCheck
        this.useCustomCursorsCheck.set_Location(
            new System.Drawing.Point(10, 243));
        this.useCustomCursorsCheck.set_Size(new System.Drawing.Size(137, 24));
        this.useCustomCursorsCheck.set_Text("Use Custom Cursors");
        // dropLocationLabel
        this.dropLocationLabel.set_Location(
            new System.Drawing.Point(154, 245));
        this.dropLocationLabel.set_Size(new System.Drawing.Size(137, 24));
        this.dropLocationLabel.set_Text("None");
        // Form1
        this.set_ClientSize(new System.Drawing.Size(292, 270));
        this.get_Controls().AddRange(new System.Windows.Forms.Control[] { 
            this.listDragSource, this.listDragTarget, 
            this.useCustomCursorsCheck, this.dropLocationLabel });
        this.set_Text("drag-and-drop Example");
        this.ResumeLayout(false);
    } //Form1

    private void listDragSource_MouseDown(Object sender, 
        System.Windows.Forms.MouseEventArgs e)
    {
        // Get the index of the item the mouse is below.
        indexOfItemUnderMouseToDrag = listDragSource.IndexFromPoint(e.get_X(), 
            e.get_Y());

        if (indexOfItemUnderMouseToDrag != ListBox.NoMatches) {
            // Remember the point where the mouse down occurred. The DragSize 
            // indicates the size that the mouse can move before a drag event 
            // should be started.                
            Size dragSize = SystemInformation.get_DragSize();
            // Create a rectangle using the DragSize, with the mouse position 
            // being at the center of the rectangle.
            dragBoxFromMouseDown = new Rectangle(new Point(e.get_X() 
                - dragSize.get_Width() / 2, e.get_Y() 
                - dragSize.get_Height() / 2), dragSize);
        }
        // Reset the rectangle if the mouse is not over an item in the ListBox.
        else {
            dragBoxFromMouseDown = Rectangle.Empty;
        }
    } //listDragSource_MouseDown

    private void listDragSource_MouseUp(Object sender, 
        System.Windows.Forms.MouseEventArgs e)
    {
        // Reset the drag rectangle when the mouse button is raised.
        dragBoxFromMouseDown = Rectangle.Empty;
    } //listDragSource_MouseUp

    private void listDragSource_MouseMove(Object sender, 
        System.Windows.Forms.MouseEventArgs e)
    {
        if ((e.get_Button() & get_MouseButtons().Left) 
            == get_MouseButtons().Left) {
            // If the mouse moves outside the rectangle, start the drag.
            if (!(dragBoxFromMouseDown.Equals(Rectangle.Empty)) 
                && !(dragBoxFromMouseDown.Contains(e.get_X(), e.get_Y()))) {
                // Create custom cursors for the drag-and-drop operation.
                try {
                    myNormalCursor = new Cursor("3dwarro.cur");
                    myNoDropCursor = new Cursor("3dwno.cur");
                }
                catch (System.Exception exp) {
                    // An error occurred while attempting to load the cursors, 
                    // so use standard cursors.
                    useCustomCursorsCheck.set_Checked(false);
                }
                finally {
                    // The screenOffset is used to account for any desktop bands 
                    // that may be at the top or left side of the screen when 
                    // determining when to cancel the drag drop operation.
                    screenOffset = 
                        SystemInformation.get_WorkingArea().get_Location();
                    // Proceed with the drag-and-drop, passing in the list item.                    
                    DragDropEffects dropEffect = listDragSource.DoDragDrop(
                        listDragSource.get_Items().get_Item(
                        indexOfItemUnderMouseToDrag), 
                        DragDropEffects.All | DragDropEffects.Link);
                    // If the drag operation was a move then remove the item.
                    if (dropEffect.Equals(DragDropEffects.Move)) {
                        listDragSource.get_Items().RemoveAt(
                            indexOfItemUnderMouseToDrag);
                        // Selects the previous item in the list as long as the 
                        // list has an item.
                        if (indexOfItemUnderMouseToDrag > 0) {
                            listDragSource.set_SelectedIndex(
                                indexOfItemUnderMouseToDrag - 1);
                        }
                        else {
                            if (listDragSource.get_Items().get_Count() > 0) {
                                // Selects the first item.
                                listDragSource.set_SelectedIndex(0);
                            }
                        }
                    }
                    // Dispose of the cursors since they are no longer needed.
                    if (myNormalCursor != null) {
                        myNormalCursor.Dispose();
                    }

                    if (myNoDropCursor != null) {
                        myNoDropCursor.Dispose();
                    }
                }
            }
        }
    } //listDragSource_MouseMove

    private void listDragSource_GiveFeedback(Object sender, 
        System.Windows.Forms.GiveFeedbackEventArgs e)
    {
        // Use custom cursors if the check box is checked.
        if (useCustomCursorsCheck.get_Checked()) {
            // Sets the custom cursor based upon the effect.
            e.set_UseDefaultCursors(false);
            if ((e.get_Effect() & DragDropEffects.Move) 
                == DragDropEffects.Move) {
                get_Cursor().set_Current(myNormalCursor);
            }
            else {
                get_Cursor().set_Current(myNoDropCursor);
            }
        }
    } //listDragSource_GiveFeedback

    private void listDragTarget_DragOver(Object sender, 
        System.Windows.Forms.DragEventArgs e)
    {
        // Determine whether string data exists in the drop data. If not, then
        // the drop effect reflects that the drop cannot occur.
        if (!(e.get_Data().GetDataPresent(String.class.ToType()))) {
            e.set_Effect(DragDropEffects.None);
            dropLocationLabel.set_Text("None - no string data.");
            return;
        }
        // Set the effect based upon the KeyState.
        if ((e.get_KeyState() & 8 + 32) == 8 + 32 && (e.get_AllowedEffect() 
            & DragDropEffects.Link) == DragDropEffects.Link) {
            // KeyState 8 + 32 = CTL + ALT
            // Link drag-and-drop effect.
            e.set_Effect(DragDropEffects.Link);
        }
        else {
            if ((e.get_KeyState() & 32) == 32 && (e.get_AllowedEffect() 
                & DragDropEffects.Link) == DragDropEffects.Link) {
                // ALT KeyState for link.
                e.set_Effect(DragDropEffects.Link);
            }
            else {
                if ((e.get_KeyState() & 4) == 4 && (e.get_AllowedEffect() 
                    & DragDropEffects.Move) == DragDropEffects.Move) {
                    // SHIFT KeyState for move.
                    e.set_Effect(DragDropEffects.Move);
                }
                else {
                    if ((e.get_KeyState() & 8) == 8 && (e.get_AllowedEffect() 
                        & DragDropEffects.Copy) == DragDropEffects.Copy) {
                        // CTL KeyState for copy.
                        e.set_Effect(DragDropEffects.Copy);
                    }
                    else {
                        if ((e.get_AllowedEffect() & DragDropEffects.Move) 
                            == DragDropEffects.Move) {
                            // By default, the drop action should be move, 
                            //if allowed.
                            e.set_Effect(DragDropEffects.Move);
                        }
                        else {
                            e.set_Effect(DragDropEffects.None);
                        }
                    } // Get the index of the item the mouse is below. 
                }
            } // The mouse locations are relative to the screen, so they 
              // must be converted to client coordinates.
        } 
        indexOfItemUnderMouseToDrop = listDragTarget.IndexFromPoint(
            listDragTarget.PointToClient(new Point(e.get_X(), e.get_Y())));
        // Updates the label text.
        if (indexOfItemUnderMouseToDrop != ListBox.NoMatches) {
            dropLocationLabel.set_Text("Drops before item #" 
                + (indexOfItemUnderMouseToDrop + 1));
        }
        else {
            dropLocationLabel.set_Text("Drops at the end.");
        }
    } //listDragTarget_DragOver

    private void listDragTarget_DragDrop(Object sender, 
        System.Windows.Forms.DragEventArgs e)
    {
        // Ensure that the list item index is contained in the data.
        if (e.get_Data().GetDataPresent(String.class.ToType())) {
            Object item = (Object)(e.get_Data().GetData(
                   String.class.ToType()));
            // Perform drag-and-drop, depending upon the effect.
            if (e.get_Effect().Equals(DragDropEffects.Copy) || 
                e.get_Effect().Equals(DragDropEffects.Move)) {
                // Insert the item.
                if (indexOfItemUnderMouseToDrop != ListBox.NoMatches) {
                    listDragTarget.get_Items().Insert(
                        indexOfItemUnderMouseToDrop, item);
                }
                else {
                    listDragTarget.get_Items().Add(item);
                }
            }
        }
        // Reset the label text.
        dropLocationLabel.set_Text("None");
    } //listDragTarget_DragDrop

    private void listDragSource_QueryContinueDrag(Object sender, 
        System.Windows.Forms.QueryContinueDragEventArgs e)
    {
        // Cancel the drag if the mouse moves off the form.
        ListBox lb = (ListBox)sender;

        if (lb != null) {
            Form f = lb.FindForm();
            // Cancel the drag if the mouse moves off the form. The 
            // screenOffset takes into account any desktop bands 
            // that may be at the top or left side of the screen.
            if (Control.get_MousePosition().get_X() - screenOffset.get_X() 
                < f.get_DesktopBounds().get_Left() 
                || Control.get_MousePosition().get_X() 
                - screenOffset.get_X() > f.get_DesktopBounds().get_Right() 
                || Control.get_MousePosition().get_Y() - screenOffset.get_Y() 
                < f.get_DesktopBounds().get_Top() 
                || Control.get_MousePosition().get_Y() - screenOffset.get_Y() 
                > f.get_DesktopBounds().get_Bottom()) {
                e.set_Action(DragAction.Cancel);
            }
        }
    } //listDragSource_QueryContinueDrag

    private void listDragTarget_DragEnter(Object sender, 
        System.Windows.Forms.DragEventArgs e)
    {
        // Reset the label text.
        dropLocationLabel.set_Text("None");
    } //listDragTarget_DragEnter

    private void listDragTarget_DragLeave(Object sender, System.EventArgs e)
    {
        // Reset the label text.
        dropLocationLabel.set_Text("None");
    } //listDragTarget_DragLeave
} //Form1 

The following code example shows how to use the DragDropEffects enumeration to specify how data should be transferred between the controls involved in a drag-and-drop operation. This example requires that your form includes a RichTextBox control and a Label control and that the Label control is populated with a list of valid file names. When the user drags a file name onto the RichTextBox control, the control's DragEnter event is raised. Within the event handler, the Effect property of the DragEventArgs is initialized to DragDropEffects to indicate that the data referenced by the file path should be copied to the RichTextBox control.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
   ' Sets the AllowDrop property so that data can be dragged onto the control.
   RichTextBox1.AllowDrop = True

   ' Add code here to populate the ListBox1 with paths to text files.

End Sub

Private Sub RichTextBox1_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles RichTextBox1.DragEnter
   ' If the data is text, copy the data to the RichTextBox control.
   If (e.Data.GetDataPresent("Text")) Then
      e.Effect = DragDropEffects.Copy
   End If
End Sub


Private Overloads Sub RichTextBox1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles RichTextBox1.DragDrop
   ' Loads the file into the control. 
   RichTextBox1.LoadFile(e.Data.GetData("Text"), System.Windows.Forms.RichTextBoxStreamType.RichText)
End Sub

Private Sub ListBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseDown
   Dim Lb As ListBox
   Dim Pt As New Point(e.X, e.Y)
   Dim Index As Integer

   ' Determines which item was selected.
   Lb = sender
   Index = Lb.IndexFromPoint(Pt)

   ' Starts a drag-and-drop operation with that item.
   If Index >= 0 Then
      Lb.DoDragDrop(Lb.Items(Index), DragDropEffects.Link)
   End If
End Sub

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

Community Additions

ADD
Show:
© 2015 Microsoft