Exportar (0) Imprimir
Expandir Tudo
Expandir Minimizar
Este artigo foi traduzido por máquina. Coloque o ponteiro do mouse sobre as frases do artigo para ver o texto original. Mais informações.
Tradução
Original

Método Control.DoDragDrop

Inicia uma operação de do tipo arrastar e soltar.

Namespace:  System.Windows.Forms
Assembly:  System.Windows.Forms (em System.Windows.Forms.dll)

[UIPermissionAttribute(SecurityAction.Demand, Clipboard = UIPermissionClipboard.OwnClipboard)]
public DragDropEffects DoDragDrop(
	Object data,
	DragDropEffects allowedEffects
)

Parâmetros

data
Tipo: System.Object
Os dados para arrastar.
allowedEffects
Tipo: System.Windows.Forms.DragDropEffects
Um do DragDropEffects valores.

Valor de retorno

Tipo: System.Windows.Forms.DragDropEffects
Um valor a partir de DragDropEffects Enumeração que representa o efeito final foi executado durante a operação de do tipo arrastar e soltar.

The allowedEffects parâmetro determina qual arrastar as operações podem ocorrer. Se a operação arrastar e precisar interoperar com aplicativos em outro processo, dados devem ser uma classe base gerenciada (String, Bitmap, ou Metafile), ou um objeto que implementa ISerializable ou IDataObject.

A seguir descrevem como e quando são gerados eventos relacionados a operações de do tipo arrastar e soltar.

The DoDragDrop método determina o controle de local do cursor corrente. Em seguida, ele verifica se o controle é um válido destino de soltura.

Se o controle for um válido solto, o GiveFeedback evento é gerado com o efeito de do tipo arrastar e soltar especificado. Para obter uma lista de efeitos de do tipo arrastar e soltar, consulte o DragDropEffects enumeração.

As alterações na posição do cursor do mouse, estado do teclado e o estado de botão do mouse são controladas.

  • Se o usuário é movido para fora de uma janela, a DragLeave evento é gerado.

  • Se o mouse entra em outro controle, a DragEnter para que o controle é disparado.

  • Se o mouse se move, mas permanece dentro do mesmo controle, a DragOver evento é gerado.

Se houver uma alterar no teclado ou mouse botão do mouse estado, a QueryContinueDrag evento é gerado e determina se deve continuar a arrastar, soltar dados, ou cancelar a operação com base no valor da Action propriedade de evento QueryContinueDragEventArgs.

  • Se o valor de DragAction é Continue, o DragOver evento é gerado para continuar a operação e o GiveFeedback evento é gerado com o novo efeito para que possa ser definido retorno visual apropriado. Para obter uma lista de efeitos de soltar válidas, consulte o DragDropEffects enumeração.

    ObservaçãoObservação:

    O DragOver e GiveFeedback eventos são combinados para que, conforme o mouse se move entre o local de destino, o usuário terá o comentário mais atualizado na posição do mouse.

  • Se o valor de DragAction é Drop, será retornado o valor de efeito de soltar para a fonte, para que o aplicativo de origem possa executar a operação apropriada nos dados de origem; por exemplo, recortar os dados se a operação foi uma movimentação.

  • Se o valor de DragAction é Cancel, o DragLeave evento é gerado.

ObservaçãoObservação:

O DoDragDrop método captura todas as exceções e relança apenas a segurança seguinte ou exceções importantes:

  • SecurityException

  • NullReferenceException

  • StackOverflowException

  • OutOfMemoryException

  • ThreadAbortException

  • ExecutionEngineException

  • IndexOutOfRangeException

  • AccessViolationException

O exemplo de código a seguir demonstra uma operação de do tipo arrastar e soltar entre dois ListBox controles. O exemplo chama o DoDragDrop método quando a ação de arrastar é iniciado. A ação de arrastar inicia se o mouse foi movido mais de SystemInformation.DragSize do local de mouse durante o MouseDown evento. The IndexFromPoint método é usado para determinar o índice do item a arrastar durante o MouseDown evento.

O exemplo também demonstra o uso de cursores personalizados para a operação de do tipo arrastar e soltar.O exemplo requer que dois arquivos de cursor, 3dwarro.cur e 3dwno.cur, existe no diretório de aplicativo, para o personalizado arrastar e soltar não cursores, respectivamente. The custom cursors will be used if the UseCustomCursorsCheck CheckBox is checked.Cursores personalizados são conjunto no GiveFeedback manipulador de eventos.

O estado do teclado é avaliado no DragOver evento manipulador para a direita ListBox, para determinar o que a operação arrastar e será baseada no estado das teclas deslocar, CTRL, ALT ou as teclas CTRL+ALT. O local em que o ListBox onde ocorreria o descarte é também determinado durante o DragOver evento. Se os dados para soltar não um String, o DragEventArgs.Effect é conjunto para None em DragDropEffects. Finally, the status of the drop is displayed in the DropLocationLabel Label.

Os dados para soltar para a direita ListBox determinado na DragDrop evento manipulador e o String valor é adicionado no local apropriado do ListBox. Se a operação de arrastar é movido para fora dos limites do formulário, a operação de do tipo arrastar e soltar foi cancelada no QueryContinueDrag manipulador de eventos.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace Snip_DragNDrop
{
    publicclass 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;

        privateint indexOfItemUnderMouseToDrag;
        privateint indexOfItemUnderMouseToDrop;        

        private Rectangle dragBoxFromMouseDown;
        private Point screenOffset;

        private Cursor MyNoDropCursor;
        private Cursor MyNormalCursor;

        /// The main entry point for the application.
        [STAThread]
        staticvoid 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();

            // ListDragSourcethis.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);

            // ListDragTargetthis.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);

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

            // DropLocationLabelthis.DropLocationLabel.Location = new System.Drawing.Point(154, 245);
            this.DropLocationLabel.Size = new System.Drawing.Size(137, 24);
            this.DropLocationLabel.Text = "None";

            // Form1this.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);

        }

        privatevoid 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;

        }

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

        privatevoid 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;

                            elseif (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();
                    }
                }
            }
        }
        privatevoid 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;
            }

        }
        privatevoid 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;

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

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

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

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

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

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

            } elseif ((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.";

        }
        privatevoid 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";
        }
        privatevoid 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;
                }
            }
        }
        privatevoid ListDragTarget_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) {
            // Reset the label text.
            DropLocationLabel.Text = "None";
        }
        privatevoid ListDragTarget_DragLeave(object sender, System.EventArgs e) {
            // Reset the label text.
            DropLocationLabel.Text = "None";
        }
    }
}


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 


O exemplo de código a seguir mostra como usar o DragDropEffects enumeração para especificar como os dados devem ser transferidos entre os controles envolvidos em uma operação de do tipo arrastar e soltar. Este exemplo requer que seu formulário inclui um RichTextBox controle e um ListBox controle e que o ListBox controle é preenchido com uma lista de nomes de arquivo válido. Quando o usuário arrasta um nome de arquivo para o RichTextBox do controle, o controle DragEnter evento é gerado. No manipulador de eventos, a Effect propriedade das DragEventArgs é inicializado para DragDropEffects para indicar que os dados referenciados pelo caminho do arquivo devem ser copiados para o RichTextBox controle.

privatevoid 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.

}

privatevoid 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);
   }
}

privatevoid 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;
}

privatevoid richTextBox1_DragDrop(object sender, DragEventArgs e) 
{
   // Loads the file into the control. 
   richTextBox1.LoadFile((String)e.Data.GetData("Text"), System.Windows.Forms.RichTextBoxStreamType.RichText);
}



Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

o.NET Framework e.NET Compact Framework não oferecem suporte a todas as versões de cada plataforma. Para obter uma lista de versões suportadas, consulte Requisitos de sistema do .NET framework.

.NET Framework

Compatível com: 3.5, 3.0, 2.0, 1.1, 1.0


Data

História

Motivo

Julho de 2008

Observação adicionada sobre exceções swallowed.

Comentários do cliente.

Contribuições da comunidade

ADICIONAR
Mostrar:
© 2014 Microsoft