Control (Métodos)


Control.DoDragDrop (Método)
Inicia una operación de arrastrar y colocar.

Espacio de nombres: System.Windows.Forms
Ensamblado: System.Windows.Forms (en system.windows.forms.dll)

Sintaxis

Visual Basic (Declaración)
Public Function DoDragDrop ( _
    data As Object, _
    allowedEffects As DragDropEffects _
) As DragDropEffects
Visual Basic (Uso)
Dim instance As Control
Dim data As Object
Dim allowedEffects As DragDropEffects
Dim returnValue As DragDropEffects

returnValue = instance.DoDragDrop(data, allowedEffects)
C#
public DragDropEffects DoDragDrop (
    Object data,
    DragDropEffects allowedEffects
)
C++
public:
DragDropEffects DoDragDrop (
    Object^ data, 
    DragDropEffects allowedEffects
)
J#
public DragDropEffects DoDragDrop (
    Object data, 
    DragDropEffects allowedEffects
)
JScript
public function DoDragDrop (
    data : Object, 
    allowedEffects : DragDropEffects
) : DragDropEffects
XAML
No aplicable.

Parámetros

data

Datos que se van a arrastrar.

allowedEffects

Uno de los valores de DragDropEffects.

Valor devuelto

Valor de la enumeración DragDropEffects que representa el efecto final obtenido durante la operación de arrastrar y colocar.
Comentarios

El parámetro allowedEffects determina las operaciones de arrastre que pueden llevarse a cabo. Si la operación de arrastre necesita interoperar con aplicaciones en otro proceso, los datos deben ser una clase base administrada (String, Bitmap o Metafile), o un objeto que implemente ISerializable o IDataObject.

A continuación, se describe cómo y cuándo se provocan eventos relacionados con operaciones de arrastrar y colocar.

El método DoDragDrop determina el control en la posición actual del cursor. A continuación, comprueba si el control es un destino (colocar) válido.

Si el control es un destino válido, se provoca el evento GiveFeedback con el efecto de arrastrar y colocar especificado. Para obtener una lista de efectos de arrastrar y colocar, vea la enumeración DragDropEffects.

Se realiza el seguimiento de la posición del cursor del mouse, del estado del teclado y del estado de los botones del mouse.

  • Si el usuario desplaza el mouse fuera de una ventana, se provoca el evento DragLeave.

  • Si el mouse entra en otro control, se provoca el evento DragEnter para ese control.

  • Si se mueve el mouse dentro del mismo control, se provoca el evento DragOver.

Si hay un cambio en el estado del teclado o de los botones del mouse, se produce el evento QueryContinueDrag y se determina si continúa la operación de arrastrar o colocar datos, o si se cancela la operación en función del valor de la propiedad Action de QueryContinueDragEventArgs del evento.

  • Si el valor de DragAction es Continue, se produce el evento DragOver para continuar con la operación y, con el nuevo efecto, se produce el evento GiveFeedback de forma que se pueda establecer la información visual apropiada. Para obtener una lista de efectos de colocar válidos, vea la enumeración DragDropEffects.

    NotaNota:

    Los eventos DragOver y GiveFeedback están emparejados de forma que cuando el mouse se desplace por el destino (colocar), el usuario reciba la información más actualizada sobre la posición del mouse.

  • Si el valor de DragAction es Drop, el valor del efecto de colocar se devuelve al origen para que la aplicación de origen pueda realizar la operación apropiada en los datos de origen; por ejemplo, cortar los datos si la operación es un movimiento.

  • Si el valor de DragAction es Cancel, se produce el evento DragLeave.

Ejemplo

En el ejemplo de código siguiente se muestra una operación de arrastrar y colocar entre dos controles ListBox. En el ejemplo se llama al método DoDragDrop cuando se inicia la acción de arrastrar. La acción de arrastrar se inicia si se ha movido el mouse más de SystemInformation.DragSize desde su ubicación durante el evento MouseDown. El método IndexFromPoint se utiliza para determinar el índice del elemento que se va a arrastrar durante el evento MouseDown.

En el ejemplo también se muestra la utilización de cursores personalizados para la operación de arrastrar y colocar. Este ejemplo requiere que haya dos archivos de cursor (3dwarro.cur y 3dwno.cur) en el directorio de la aplicación para los cursores personalizados de arrastrar y prohibición de colocar, respectivamente. Los cursores personalizados se utilizan si se ha activado UseCustomCursorsCheckCheckBox. Los cursores personalizados se establecen en el controlador de eventos GiveFeedback.

El estado del teclado se evalúa en el controlador de evento DragOver del control ListBox derecho, con el fin de determinar qué operación de arrastrar se realizará en función del estado de las teclas MAYÚS, CTRL, ALT o CTRL+ALT. La ubicación en ListBox donde se va a producir la operación de colocar también se determina durante el evento DragOver. Si los datos que se van a colocar no son de tipo String, el valor de la propiedad DragEventArgs.Effect se establece en None en DragDropEffects. Por último, el estado de la operación de colocar se muestra en DropLocationLabelLabel.

Los datos que se colocan para el ListBox correcto se determinan en el controlador de eventos DragDrop y el valor String se agrega a la ubicación apropiada de ListBox. Si la operación de arrastrar se realiza fuera de los límites del formulario, la operación de arrastrar y colocar se cancelará en el controlador de eventos QueryContinueDrag.

Visual Basic
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 (lb isNot 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
C#
using System;
using System.Drawing;
using System.Windows.Forms;

namespace Snip_DragNDrop
{
    public class Form1 : 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.
        [STAThread]
        static void Main() 
        {
            Application.Run(new Form1());
        }

        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.Items.AddRange(new object[] {"one", "two", "three", "four", 
                                                                "five", "six", "seven", "eight",
                                                                "nine", "ten"});
            this.ListDragSource.Location = new System.Drawing.Point(10, 17);
            this.ListDragSource.Size = new System.Drawing.Size(120, 225);
            this.ListDragSource.MouseDown += new System.Windows.Forms.MouseEventHandler(this.ListDragSource_MouseDown);
            this.ListDragSource.QueryContinueDrag += new System.Windows.Forms.QueryContinueDragEventHandler(this.ListDragSource_QueryContinueDrag);
            this.ListDragSource.MouseUp += new System.Windows.Forms.MouseEventHandler(this.ListDragSource_MouseUp);
            this.ListDragSource.MouseMove += new System.Windows.Forms.MouseEventHandler(this.ListDragSource_MouseMove);
            this.ListDragSource.GiveFeedback += new System.Windows.Forms.GiveFeedbackEventHandler(this.ListDragSource_GiveFeedback);

            // ListDragTarget
            this.ListDragTarget.AllowDrop = true;
            this.ListDragTarget.Location = new System.Drawing.Point(154, 17);
            this.ListDragTarget.Size = new System.Drawing.Size(120, 225);
            this.ListDragTarget.DragOver += new System.Windows.Forms.DragEventHandler(this.ListDragTarget_DragOver);
            this.ListDragTarget.DragDrop += new System.Windows.Forms.DragEventHandler(this.ListDragTarget_DragDrop);
            this.ListDragTarget.DragEnter += new System.Windows.Forms.DragEventHandler(this.ListDragTarget_DragEnter);
            this.ListDragTarget.DragLeave += new System.EventHandler(this.ListDragTarget_DragLeave);

            // UseCustomCursorsCheck
            this.UseCustomCursorsCheck.Location = new System.Drawing.Point(10, 243);
            this.UseCustomCursorsCheck.Size = new System.Drawing.Size(137, 24);
            this.UseCustomCursorsCheck.Text = "Use Custom Cursors";

            // DropLocationLabel
            this.DropLocationLabel.Location = new System.Drawing.Point(154, 245);
            this.DropLocationLabel.Size = new System.Drawing.Size(137, 24);
            this.DropLocationLabel.Text = "None";
           
            // Form1
            this.ClientSize = new System.Drawing.Size(292, 270);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {this.ListDragSource,
                                                        this.ListDragTarget, this.UseCustomCursorsCheck,
                                                        this.DropLocationLabel});
            this.Text = "drag-and-drop Example";

            this.ResumeLayout(false);

        }

        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.X, e.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.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;

        }

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

        private void ListDragSource_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) 
        {
            
            if ((e.Button & MouseButtons.Left) == MouseButtons.Left) {

                // If the mouse moves outside the rectangle, start the drag.
                if (dragBoxFromMouseDown != Rectangle.Empty && 
                    !dragBoxFromMouseDown.Contains(e.X, e.Y)) {

                    // Create 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.                    
                        DragDropEffects dropEffect = ListDragSource.DoDragDrop(ListDragSource.Items[indexOfItemUnderMouseToDrag], DragDropEffects.All | DragDropEffects.Link);

                        // If the drag operation was a move then remove the item.
                        if (dropEffect == DragDropEffects.Move) {                        
                            ListDragSource.Items.RemoveAt(indexOfItemUnderMouseToDrag);

                            // Selects the previous item in the list as long as the list has an item.
                            if (indexOfItemUnderMouseToDrag > 0)
                                ListDragSource.SelectedIndex = indexOfItemUnderMouseToDrag -1;

                            else if (ListDragSource.Items.Count > 0)
                                // Selects the first item.
                                ListDragSource.SelectedIndex =0;
                        }

                        // Dispose of the cursors since they are no longer needed.
                        if (MyNormalCursor != null)
                            MyNormalCursor.Dispose();

                        if (MyNoDropCursor != null)
                            MyNoDropCursor.Dispose();
                    }
                }
            }
        }
        private void ListDragSource_GiveFeedback(object sender, System.Windows.Forms.GiveFeedbackEventArgs e) 
        {
            // Use custom cursors if the check box is checked.
            if (UseCustomCursorsCheck.Checked) {

                // Sets the custom cursor based upon the effect.
                e.UseDefaultCursors = false;
                if ((e.Effect & DragDropEffects.Move) == DragDropEffects.Move)
                    Cursor.Current = MyNormalCursor;
                else 
                    Cursor.Current = MyNoDropCursor;
            }
        
        }
        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.Data.GetDataPresent(typeof(System.String))) {

                e.Effect = DragDropEffects.None;
                DropLocationLabel.Text = "None - no string data.";
                return;
            }

            // Set the effect based upon the KeyState.
            if ((e.KeyState & (8+32)) == (8+32) && 
                (e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link) {
                // KeyState 8 + 32 = CTL + ALT

                // Link drag-and-drop effect.
                e.Effect = DragDropEffects.Link;

            } else if ((e.KeyState & 32) == 32 && 
                (e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link) {

                // ALT KeyState for link.
                e.Effect = DragDropEffects.Link;

            } else if ((e.KeyState & 4) == 4 && 
                (e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move) {

                // SHIFT KeyState for move.
                e.Effect = DragDropEffects.Move;

            } else if ((e.KeyState & 8) == 8 && 
                (e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy) {

                // CTL KeyState for copy.
                e.Effect = DragDropEffects.Copy;

            } else if ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move)  {

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

            } else
                e.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.X, e.Y)));

            // Updates the label text.
            if (indexOfItemUnderMouseToDrop != ListBox.NoMatches){

                DropLocationLabel.Text = "Drops before item #" + (indexOfItemUnderMouseToDrop + 1);
            } else
                DropLocationLabel.Text = "Drops at the end.";

        }
        private void ListDragTarget_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) 
        {
            // Ensure that the list item index is contained in the data.
            if (e.Data.GetDataPresent(typeof(System.String))) {

                Object item = (object)e.Data.GetData(typeof(System.String));

                // Perform drag-and-drop, depending upon the effect.
                if (e.Effect == DragDropEffects.Copy ||
                    e.Effect == DragDropEffects.Move) {
                
                    // Insert the item.
                    if (indexOfItemUnderMouseToDrop != ListBox.NoMatches)
                        ListDragTarget.Items.Insert(indexOfItemUnderMouseToDrop, item);
                    else
                        ListDragTarget.Items.Add(item);
                    
                }
            }
            // Reset the label text.
            DropLocationLabel.Text = "None";
        }
        private void ListDragSource_QueryContinueDrag(object sender, System.Windows.Forms.QueryContinueDragEventArgs e) {
            // Cancel the drag if the mouse moves off the form.
            ListBox lb = sender as ListBox;

            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.MousePosition.X - screenOffset.X) < f.DesktopBounds.Left) ||
                    ((Control.MousePosition.X - screenOffset.X) > f.DesktopBounds.Right) ||
                    ((Control.MousePosition.Y - screenOffset.Y) < f.DesktopBounds.Top) ||
                    ((Control.MousePosition.Y - screenOffset.Y) > f.DesktopBounds.Bottom)) {

                    e.Action = DragAction.Cancel;
                }
            }
        }
        private void ListDragTarget_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) {
            // Reset the label text.
            DropLocationLabel.Text = "None";
        }
        private void ListDragTarget_DragLeave(object sender, System.EventArgs e) {
            // Reset the label text.
            DropLocationLabel.Text = "None";
        }
    }
}
C++
using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;

namespace Snip_DragNDrop
{
   public ref class Form1: public System::Windows::Forms::Form
   {
   private:
      System::Windows::Forms::ListBox^ ListDragSource;
      System::Windows::Forms::ListBox^ ListDragTarget;
      System::Windows::Forms::CheckBox^ UseCustomCursorsCheck;
      System::Windows::Forms::Label ^ DropLocationLabel;
      Int32 indexOfItemUnderMouseToDrag;
      Int32 indexOfItemUnderMouseToDrop;
      Rectangle dragBoxFromMouseDown;
      Point screenOffset;
      System::Windows::Forms::Cursor^ MyNoDropCursor;
      System::Windows::Forms::Cursor^ MyNormalCursor;

   public:
      Form1()
      {
         this->ListDragSource = gcnew System::Windows::Forms::ListBox;
         this->ListDragTarget = gcnew System::Windows::Forms::ListBox;
         this->UseCustomCursorsCheck = gcnew System::Windows::Forms::CheckBox;
         this->DropLocationLabel = gcnew System::Windows::Forms::Label;
         this->SuspendLayout();
         
         // ListDragSource
         array<Object^>^temp0 = {"five","six","seven","eight","nine","ten"};
         this->ListDragSource->Items->AddRange( temp0 );
         this->ListDragSource->Location = System::Drawing::Point( 10, 17 );
         this->ListDragSource->Size = System::Drawing::Size( 120, 225 );
         this->ListDragSource->MouseDown += gcnew System::Windows::Forms::MouseEventHandler( this, &Form1::ListDragSource_MouseDown );
         this->ListDragSource->QueryContinueDrag += gcnew System::Windows::Forms::QueryContinueDragEventHandler( this, &Form1::ListDragSource_QueryContinueDrag );
         this->ListDragSource->MouseUp += gcnew System::Windows::Forms::MouseEventHandler( this, &Form1::ListDragSource_MouseUp );
         this->ListDragSource->MouseMove += gcnew System::Windows::Forms::MouseEventHandler( this, &Form1::ListDragSource_MouseMove );
         this->ListDragSource->GiveFeedback += gcnew System::Windows::Forms::GiveFeedbackEventHandler( this, &Form1::ListDragSource_GiveFeedback );
         
         // ListDragTarget
         this->ListDragTarget->AllowDrop = true;
         this->ListDragTarget->Location = System::Drawing::Point( 154, 17 );
         this->ListDragTarget->Size = System::Drawing::Size( 120, 225 );
         this->ListDragTarget->DragOver += gcnew System::Windows::Forms::DragEventHandler( this, &Form1::ListDragTarget_DragOver );
         this->ListDragTarget->DragDrop += gcnew System::Windows::Forms::DragEventHandler( this, &Form1::ListDragTarget_DragDrop );
         this->ListDragTarget->DragEnter += gcnew System::Windows::Forms::DragEventHandler( this, &Form1::ListDragTarget_DragEnter );
         this->ListDragTarget->DragLeave += gcnew System::EventHandler( this, &Form1::ListDragTarget_DragLeave );
         
         // UseCustomCursorsCheck
         this->UseCustomCursorsCheck->Location = System::Drawing::Point( 10, 243 );
         this->UseCustomCursorsCheck->Size = System::Drawing::Size( 137, 24 );
         this->UseCustomCursorsCheck->Text = "Use Custom Cursors";
         
         // DropLocationLabel
         this->DropLocationLabel->Location = System::Drawing::Point( 154, 245 );
         this->DropLocationLabel->Size = System::Drawing::Size( 137, 24 );
         this->DropLocationLabel->Text = "None";
         
         // Form1
         this->ClientSize = System::Drawing::Size( 292, 270 );
         array<System::Windows::Forms::Control^>^formControls = {this->ListDragSource,this->ListDragTarget,this->UseCustomCursorsCheck,this->DropLocationLabel};
         this->Controls->AddRange( formControls );
         this->Text = "drag-and-drop Example";
         this->ResumeLayout( false );
      }


   private:
      void ListDragSource_MouseDown( Object^ /*sender*/, System::Windows::Forms::MouseEventArgs^ e )
      {
         
         // Get the index of the item the mouse is below.
         indexOfItemUnderMouseToDrag = this->ListDragSource->IndexFromPoint( e->X, e->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.
            System::Drawing::Size dragSize = SystemInformation::DragSize;
            
            // Create a rectangle using the DragSize, with the mouse position being
            // at the center of the rectangle.
            dragBoxFromMouseDown = Rectangle(Point(e->X - (dragSize.Width / 2),e->Y - (dragSize.Height / 2)),dragSize);
         }
         else
                  dragBoxFromMouseDown = Rectangle::Empty;

         
         // Reset the rectangle if the mouse is not over an item in the ListBox.
      }

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


      void ListDragSource_MouseMove( Object^ /*sender*/, System::Windows::Forms::MouseEventArgs^ e )
      {
         if ( (e->Button & ::MouseButtons::Left) == ::MouseButtons::Left )
         {
            
            // If the mouse moves outside the rectangle, start the drag.
            if ( dragBoxFromMouseDown != Rectangle::Empty &&  !dragBoxFromMouseDown.Contains( e->X, e->Y ) )
            {
               
               // Create custom cursors for the drag-and-drop operation.
               try
               {
                  MyNormalCursor = gcnew System::Windows::Forms::Cursor( "3dwarro.cur" );
                  MyNoDropCursor = gcnew System::Windows::Forms::Cursor( "3dwno.cur" );
               }
               catch ( Exception^ ) 
               {
                  // An error occurred while attempting to load the cursors, so use
                  // the standard cursors.
                  this->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.
                  DragDropEffects dropEffect = this->ListDragSource->DoDragDrop( ListDragSource->Items[ indexOfItemUnderMouseToDrag ], static_cast<DragDropEffects>(DragDropEffects::All | DragDropEffects::Link) );
                  
                  // If the drag operation was a move then remove the item.
                  if ( dropEffect == DragDropEffects::Move )
                  {
                     ListDragSource->Items->RemoveAt( indexOfItemUnderMouseToDrag );
                     
                     // Selects the previous item in the list as long as the list has an item.
                     if ( indexOfItemUnderMouseToDrag > 0 )
                                          ListDragSource->SelectedIndex = indexOfItemUnderMouseToDrag - 1;
                     else
                     if ( ListDragSource->Items->Count > 0 )
                                          
                     // Selects the first item.
                     ListDragSource->SelectedIndex = 0;
                  }
                  
                  // Dispose of the cursors since they are no longer needed.
                  if ( MyNormalCursor != nullptr )
                                    delete MyNormalCursor;
                  if ( MyNoDropCursor != nullptr )
                                    delete MyNoDropCursor;
               }
            }
         }
      }

      void ListDragSource_GiveFeedback( Object^ /*sender*/, System::Windows::Forms::GiveFeedbackEventArgs^ e )
      {
         // Use custom cursors if the check box is checked.
         if ( UseCustomCursorsCheck->Checked )
         {
            // Sets the custom cursor based upon the effect.
            e->UseDefaultCursors = false;
            if ( (e->Effect & DragDropEffects::Move) == DragDropEffects::Move )
                        ::Cursor::Current = MyNormalCursor;
            else
                        ::Cursor::Current = MyNoDropCursor;
         }
      }

      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->Data->GetDataPresent( System::String::typeid ) )
         {
            e->Effect = DragDropEffects::None;
            DropLocationLabel->Text = "None - no string data.";
            return;
         }

         // Set the effect based upon the KeyState.
         if ( (e->KeyState & (8 + 32)) == (8 + 32) && ((e->AllowedEffect & DragDropEffects::Link) == DragDropEffects::Link) )
         {
            // KeyState 8 + 32 = CTL + ALT
            // Link drag-and-drop effect.
            e->Effect = DragDropEffects::Link;
         }
         else
         if ( (e->KeyState & 32) == 32 && ((e->AllowedEffect & DragDropEffects::Link) == DragDropEffects::Link) )
         {
            // ALT KeyState for link.
            e->Effect = DragDropEffects::Link;
         }
         else
         if ( (e->KeyState & 4) == 4 && ((e->AllowedEffect & DragDropEffects::Move) == DragDropEffects::Move) )
         {
            // SHIFT KeyState for move.
            e->Effect = DragDropEffects::Move;
         }
         else
         if ( (e->KeyState & 8) == 8 && ((e->AllowedEffect & DragDropEffects::Copy) == DragDropEffects::Copy) )
         {
            // CTL KeyState for copy.
            e->Effect = DragDropEffects::Copy;
         }
         else
         if ( (e->AllowedEffect & DragDropEffects::Move) == DragDropEffects::Move )
         {
            // By default, the drop action should be move, if allowed.
            e->Effect = DragDropEffects::Move;
         }
         else
                  e->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( Point(e->X,e->Y) ) );
         
         // Updates the label text.
         if ( indexOfItemUnderMouseToDrop != ListBox::NoMatches )
         {
            DropLocationLabel->Text = String::Concat( "Drops before item # ", (indexOfItemUnderMouseToDrop + 1) );
         }
         else
                  DropLocationLabel->Text = "Drops at the end.";
      }

      void ListDragTarget_DragDrop( Object^ /*sender*/, System::Windows::Forms::DragEventArgs^ e )
      {
         // Ensure that the list item index is contained in the data.
         if ( e->Data->GetDataPresent( System::String::typeid ) )
         {
            Object^ item = dynamic_cast<Object^>(e->Data->GetData( System::String::typeid ));
            
            // Perform drag-and-drop, depending upon the effect.
            if ( e->Effect == DragDropEffects::Copy || e->Effect == DragDropEffects::Move )
            {
               // Insert the item.
               if ( indexOfItemUnderMouseToDrop != ListBox::NoMatches )
                              ListDragTarget->Items->Insert( indexOfItemUnderMouseToDrop, item );
               else
                              ListDragTarget->Items->Add( item );
            }
         }

         // Reset the label text.
         DropLocationLabel->Text = "None";
      }

      void ListDragSource_QueryContinueDrag( Object^ sender, System::Windows::Forms::QueryContinueDragEventArgs^ e )
      {
         // Cancel the drag if the mouse moves off the form.
         ListBox^ lb = dynamic_cast<ListBox^>(sender);
         if ( lb != nullptr )
         {
            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::MousePosition.X - screenOffset.X) < f->DesktopBounds.Left) || ((Control::MousePosition.X - screenOffset.X) > f->DesktopBounds.Right) || ((Control::MousePosition.Y - screenOffset.Y) < f->DesktopBounds.Top) || ((Control::MousePosition.Y - screenOffset.Y) > f->DesktopBounds.Bottom) )
            {
               e->Action = DragAction::Cancel;
            }
         }
      }

      void ListDragTarget_DragEnter( Object^ /*sender*/, System::Windows::Forms::DragEventArgs^ /*e*/ )
      {
         // Reset the label text.
         DropLocationLabel->Text = "None";
      }

      void ListDragTarget_DragLeave( Object^ /*sender*/, System::EventArgs^ /*e*/ )
      {
        // Reset the label text.
         DropLocationLabel->Text = "None";
      }
   };
}

/// The main entry point for the application.

[STAThread]
int main()
{
   Application::Run( gcnew Snip_DragNDrop::Form1 );
}
J#
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 

En el siguiente ejemplo de código se muestra cómo utilizar la enumeración DragDropEffects para especificar cómo se deben transferir los datos entre los controles implicados en una operación de arrastrar y colocar. En este ejemplo se requiere que el formulario incluya un control RichTextBox y un control Label, y que el control Label se llene con una lista de nombre de archivo válidos. Cuando el usuario arrastra un nombre de archivo al control RichTextBox, se provoca el evento DragEnter del control. En el controlador de eventos, la propiedad Effect de DragEventArgs se inicializa en DragDropEffects para indicar que los datos a los que hace referencia la ruta de acceso del archivo deben copiarse al control RichTextBox.

Visual Basic
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
C#
private void Form1_Load(object sender, EventArgs e) 
{
   // 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.

}

private void listBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
   // Determines which item was selected.
   ListBox lb =( (ListBox)sender);
   Point pt = new Point(e.X,e.Y);
   int index = lb.IndexFromPoint(pt);

   // Starts a drag-and-drop operation with that item.
   if(index>=0) 
   {
      lb.DoDragDrop(lb.Items[index].ToString(), DragDropEffects.Link);
   }
}

private void richTextBox1_DragEnter(object sender, DragEventArgs e) 
{
   // If the data is text, copy the data to the RichTextBox control.
   if(e.Data.GetDataPresent("Text"))
      e.Effect = DragDropEffects.Copy;
}

private void richTextBox1_DragDrop(object sender, DragEventArgs e) 
{
   // Loads the file into the control. 
   richTextBox1.LoadFile((String)e.Data.GetData("Text"), System.Windows.Forms.RichTextBoxStreamType.RichText);
}
C++
private:
   void Form1_Load( Object^ /*sender*/, EventArgs^ /*e*/ )
   {
      // 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.
   }

   void listBox1_MouseDown( Object^ sender, System::Windows::Forms::MouseEventArgs^ e )
   {
      // Determines which item was selected.
      ListBox^ lb = (dynamic_cast<ListBox^>(sender));
      Point pt = Point(e->X,e->Y);
      int index = lb->IndexFromPoint( pt );

      // Starts a drag-and-drop operation with that item.
      if ( index >= 0 )
      {
         lb->DoDragDrop( lb->Items[ index ], DragDropEffects::Link );
      }
   }

   void richTextBox1_DragEnter( Object^ /*sender*/, DragEventArgs^ e )
   {
      // If the data is text, copy the data to the RichTextBox control.
      if ( e->Data->GetDataPresent( "Text" ) )
            e->Effect = DragDropEffects::Copy;
   }

   void richTextBox1_DragDrop( Object^ /*sender*/, DragEventArgs^ e )
   {
      // Loads the file into the control.
      richTextBox1->LoadFile( dynamic_cast<String^>(e->Data->GetData( "Text" )), System::Windows::Forms::RichTextBoxStreamType::RichText );
   }
Plataformas

Windows 98, Windows 2000 Service Pack 4, Windows CE, Windows Millennium, Windows Mobile para Pocket PC, Windows Mobile para Smartphone, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter

Microsoft .NET Framework 3.0 es compatible con Windows Vista, Microsoft Windows XP SP2 y Windows Server 2003 SP1.

Información de versión

.NET Framework

Compatible con: 3.0, 2.0, 1.1, 1.0
Vea también

Page view tracker