DragEventArgs Classe

Definição

Fornece dados para o evento DragDrop, DragEnter ou DragOver.Provides data for the DragDrop, DragEnter, or DragOver event.

public ref class DragEventArgs : EventArgs
[System.Runtime.InteropServices.ComVisible(true)]
public class DragEventArgs : EventArgs
type DragEventArgs = class
    inherit EventArgs
Public Class DragEventArgs
Inherits EventArgs
Herança
DragEventArgs
Derivado
Atributos

Exemplos

O exemplo a seguir demonstra uma operação de arrastar e soltar entre dois ListBox controles.The following example demonstrates a drag-and-drop operation between two ListBox controls. O exemplo chama o DoDragDrop método quando a ação de arrastar é iniciada.The example calls the DoDragDrop method when the drag action starts. A ação de arrastar será iniciada se o mouse tiver SystemInformation.DragSize mudado mais do que o local MouseDown do mouse durante o evento.The drag action starts if the mouse has moved more than SystemInformation.DragSize from the mouse location during the MouseDown event. O IndexFromPoint método é usado para determinar o índice do item a ser arrastado durante MouseDown o evento.The IndexFromPoint method is used to determine the index of the item to drag during the MouseDown event.

O exemplo também demonstra o uso de cursores personalizados para a operação de arrastar e soltar.The example also demonstrates using custom cursors for the drag-and-drop operation. O exemplo supõe que dois arquivos de 3dwarro.cur cursor e 3dwno.curexistam no diretório do aplicativo, para os cursores arrastar e não soltar personalizados, respectivamente.The example assumes that two cursor files, 3dwarro.cur and 3dwno.cur, exist in the application directory, for the custom drag and no-drop cursors, respectively. Os cursores personalizados serão usados se o UseCustomCursorsCheck CheckBox estiver marcado.The custom cursors will be used if the UseCustomCursorsCheckCheckBox is checked. Os cursores personalizados são definidos no manipulador GiveFeedback de eventos.The custom cursors are set in the GiveFeedback event handler.

O estado do teclado é avaliado no DragOver manipulador de eventos à direita ListBox, para determinar qual será a operação de arrastar com base no estado das teclas Shift, CTRL, ALT ou CTRL + ALT.The keyboard state is evaluated in the DragOver event handler for the right ListBox, to determine what the drag operation will be based upon state of the SHIFT, CTRL, ALT, or CTRL+ALT keys. O local no ListBox qual a queda ocorre também é determinado durante o DragOver evento.The location in the ListBox where the drop would occur is also determined during the DragOver event. Se os dados a serem descartados Stringnão forem um DragEventArgs.Effect , o será DragDropEffects.Nonedefinido como.If the data to drop is not a String, then the DragEventArgs.Effect is set to DragDropEffects.None. Por fim, o status da remoção é exibido no DropLocationLabel. LabelFinally, the status of the drop is displayed in the DropLocationLabelLabel.

Os dados a serem descartados ListBox para a direita são DragDrop determinados no manipulador de String eventos e o valor ListBoxé adicionado no local apropriado no.The data to drop for the right ListBox is determined in the DragDrop event handler and the String value is added at the appropriate place in the ListBox. Se a operação de arrastar se mover para fora dos limites do formulário, a operação de arrastar e soltar será cancelada no QueryContinueDrag manipulador de eventos.If the drag operation moves outside the bounds of the form, then the drag-and-drop operation is canceled in the QueryContinueDrag event handler.

Este trecho de código demonstra o DragEventArgs uso da classe.This code excerpt demonstrates using the DragEventArgs class. Consulte o DoDragDrop método para obter o exemplo de código completo.See the DoDragDrop method for the complete code example.

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

O exemplo a seguir ilustra DragEventArgs como os são passados entre a origem e o destino de uma operação de arrastar e soltar.The following example illustrates how DragEventArgs are passed between the source and target of a drag-and-drop operation. Neste exemplo, um ListBox controle é a origem dos dados e o RichTextBox controle é o destino.In this example, a ListBox control is the source of the data, and the RichTextBox control is the target. O exemplo supõe que o ListBox controle tenha sido preenchido com uma lista de nomes de fileválidos.The example assumes that the ListBox control has been populated with a list of valid filenames. Quando o usuário arrasta um dos nomes de arquivos exibidos do ListBox controle para o RichTextBox controle, o arquivo referenciado no filename é aberto.When the user drags one of the displayed filenames from the ListBox control onto the RichTextBox control, the file referenced in the filename is opened.

A operação é iniciada no ListBox evento MouseDown do controle.The operation is initiated in the ListBox control's MouseDown event. No manipulador de GetDataPresent RichTextBox DragDropEffects eventos, o exemplo usa o método para verificar se os dados estão em um formato que o controle pode exibir e, em seguida, define a propriedade para especificar que os dados devem ser copiados do controle do código-fonte DragEnter para o controle de destino.In the DragEnter event handler, the example uses the GetDataPresent method to verify that the data is in a format that the RichTextBox control can display and then sets the DragDropEffects property to specify that data should be copied from the source control to the target control. Por fim, RichTextBox o manipulador de eventos DragDrop do controle GetData usa o método para recuperar o nome de arquivo a ser aberto.Finally, the RichTextBox control's DragDrop event handler uses the GetData method to retrieve the filename to open.

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

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

Comentários

O DragDrop evento ocorre quando o usuário conclui uma operação de arrastar e soltar arrastando um objeto sobre o controle e, em seguida, soltando-o no controle, liberando o botão do mouse.The DragDrop event occurs when the user completes a drag-and-drop operation by dragging an object over the control and then dropping it onto the control by releasing the mouse button. O DragEnter evento ocorre quando o usuário move o ponteiro do mouse para o controle enquanto arrasta um objeto com o mouse.The DragEnter event occurs when the user moves the mouse pointer onto the control while dragging an object with the mouse. O DragOver evento ocorre quando o usuário move o ponteiro do mouse sobre o controle ao arrastar um objeto com o mouse.The DragOver event occurs when the user moves the mouse pointer over the control while dragging an object with the mouse.

Um DragEventArgs objeto especifica todos os dados associados a esse evento; o estado atual das teclas Shift, CTRL e Alt; o local do ponteiro do mouse e os efeitos de arrastar e soltar permitidos pela origem e pelo destino do evento arrastar.A DragEventArgs object specifies any data associated with this event; the current state of the SHIFT, CTRL, and ALT keys; the location of the mouse pointer; and the drag-and-drop effects allowed by the source and target of the drag event.

Para obter informações sobre o modelo de evento, consulte manipulando e gerando eventos.For information about the event model, see Handling and Raising Events.

Construtores

DragEventArgs(IDataObject, Int32, Int32, Int32, DragDropEffects, DragDropEffects)

Inicializa uma nova instância da classe DragEventArgs.Initializes a new instance of the DragEventArgs class.

Propriedades

AllowedEffect

Obtém as operações do tipo "arrastar e soltar" permitidas pelo remetente (ou pela fonte) do evento arrastar.Gets which drag-and-drop operations are allowed by the originator (or source) of the drag event.

Data

Obtém o IDataObject que contém os dados associados a este evento.Gets the IDataObject that contains the data associated with this event.

Effect

Obtém ou define o efeito de soltar de destino em uma operação do tipo "arrastar e soltar".Gets or sets the target drop effect in a drag-and-drop operation.

KeyState

Obtém o estado atual das teclas SHIFT, CTRL e ALT, bem como o estado dos botões do mouse.Gets the current state of the SHIFT, CTRL, and ALT keys, as well as the state of the mouse buttons.

X

Obtém a coordenada X do ponteiro do mouse, em coordenadas na tela.Gets the x-coordinate of the mouse pointer, in screen coordinates.

Y

Obtém a coordenada y do ponteiro do mouse, em coordenadas de tela.Gets the y-coordinate of the mouse pointer, in screen coordinates.

Métodos

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Herdado de Object)

Aplica-se a

Veja também