DragEventArgs Classe

Definição

Fornece dados para o evento DragDrop, DragEnter ou DragOver.

public ref class DragEventArgs : EventArgs
[System.Runtime.InteropServices.ComVisible(true)]
public class DragEventArgs : EventArgs
public class DragEventArgs : EventArgs
[<System.Runtime.InteropServices.ComVisible(true)>]
type DragEventArgs = class
    inherit 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. O exemplo chama o DoDragDrop método quando a ação de arrastar é iniciada. A ação de arrastar será iniciada se o mouse tiver se movido mais do que SystemInformation.DragSize do local do mouse durante o MouseDown evento. O IndexFromPoint método é usado para determinar o índice do item a ser arrastado durante o MouseDown evento.

O exemplo também demonstra o uso de cursores personalizados para a operação de arrastar e soltar. O exemplo pressupõe que dois arquivos de cursor, 3dwarro.cur e 3dwno.cur, existam no diretório do aplicativo, para os cursores personalizados de arrastar e sem soltar, respectivamente. Os cursores personalizados serão usados se o UseCustomCursorsCheckCheckBox for verificado. Os cursores personalizados são definidos no GiveFeedback manipulador de eventos.

O estado do teclado é avaliado no DragOver manipulador de eventos para o direito ListBox, para determinar qual operação de arrastar será baseada no estado das teclas SHIFT, CTRL, ALT ou CTRL+ALT. O local no qual ListBox a queda ocorreria também é determinado durante o DragOver evento. Se os dados a serem soltas não forem um String, o DragEventArgs.Effect será definido DragDropEffects.Nonecomo . Por fim, o status da queda é exibido no DropLocationLabelLabel.

Os dados a serem soltas para a direita ListBox são determinados no DragDrop manipulador de eventos e o String valor é adicionado no local apropriado no 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.

Este trecho de código demonstra o uso da DragEventArgs classe . Consulte o DoDragDrop método para obter o exemplo de código completo.

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 = CTRL + 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) )
   {
      // CTRL 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, 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 = CTRL + 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)
    {
        // CTRL 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 = CTRL + 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

        ' CTRL 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 como DragEventArgs são passados entre a origem e o destino de uma operação de arrastar e soltar. Neste exemplo, um ListBox controle é a origem dos dados e o RichTextBox controle é o destino. O exemplo pressupõe que o ListBox controle foi preenchido com uma lista de nomes de arquivo válidos. Quando o usuário arrasta um dos nomes de arquivo exibidos do ListBox controle para o RichTextBox controle, o arquivo referenciado no nome do arquivo é aberto.

A operação é iniciada no ListBox evento MouseDown do controle. DragEnter No manipulador de eventos, o exemplo usa o GetDataPresent método para verificar se os dados estão em um formato que o RichTextBox controle pode exibir e, em seguida, define a DragDropEffects propriedade para especificar que os dados devem ser copiados do controle do código-fonte para o controle de destino. Por fim, o RichTextBox manipulador de eventos DragDrop do controle usa o GetData método para recuperar o nome do arquivo a ser aberto.

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 soltando-o no controle liberando o botão do mouse. O DragEnter evento ocorre quando o usuário move o ponteiro do mouse para o controle enquanto arrasta um objeto com o mouse. O DragOver evento ocorre quando o usuário move o ponteiro do mouse sobre o controle enquanto arrasta um objeto com o 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 de arrastar.

Para obter informações sobre o modelo de evento, consulte Manipulando e gerando eventos.

Construtores

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

Inicializa uma nova instância da classe DragEventArgs.

DragEventArgs(IDataObject, Int32, Int32, Int32, DragDropEffects, DragDropEffects, DropImageType, String, String)

Inicializa uma nova instância da classe DragEventArgs.

Propriedades

AllowedEffect

Obtém as operações do tipo "arrastar e soltar" permitidas pelo remetente (ou pela fonte) do evento arrastar.

Data

Obtém o IDataObject que contém os dados associados a este evento.

DropImageType

Obtém ou define o tipo de imagem drop description.

Effect

Obtém ou define o efeito de soltar de destino em uma operação do tipo "arrastar e soltar".

KeyState

Obtém o estado atual das teclas SHIFT, CTRL e ALT, bem como o estado dos botões do mouse.

Message

Obtém ou define o texto de descrição da remoção, como "Mover para %1".

MessageReplacementToken

Obtém ou define o texto de descrição da remoção, como "Documentos", quando %1 é especificado em Message.

X

Obtém a coordenada X do ponteiro do mouse, em coordenadas na tela.

Y

Obtém a coordenada y do ponteiro do mouse, em coordenadas de tela.

Métodos

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Aplica-se a

Confira também