DragEventArgs Clase
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
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
- Herencia
- Derivado
- Atributos
Ejemplos
En el ejemplo siguiente se muestra una operación de arrastrar y colocar entre dos ListBox controles. En el ejemplo se llama al DoDragDrop método cuando se inicia la acción de arrastre. La acción de arrastrar se inicia si el mouse se ha movido más que SystemInformation.DragSize desde la ubicación del mouse durante el MouseDown evento. El IndexFromPoint método se usa para determinar el índice del elemento que se va a arrastrar durante el MouseDown
evento.
En el ejemplo también se muestra el uso de cursores personalizados para la operación de arrastrar y colocar. En el ejemplo se supone que existen dos archivos de cursor y 3dwarro.cur
3dwno.cur
, en el directorio de la aplicación, para los cursores personalizados de arrastrar y sin colocar, respectivamente. Los cursores personalizados se usarán si UseCustomCursorsCheck
CheckBox está activado. Los cursores personalizados se establecen en el controlador de GiveFeedback eventos.
El estado del teclado se evalúa en el DragOver controlador de eventos de la derecha ListBox
para determinar cuál será la operación de arrastre según el estado de las teclas MAYÚS, CTRL, ALT o CTRL+ALT. La ubicación en la ListBox
que se produciría la colocación también se determina durante el DragOver
evento. Si los datos que se van a quitar no son , String
se establece DragDropEffects.Noneen DragEventArgs.Effect . Por último, el estado de la colocación se muestra en .DropLocationLabel
Label
Los datos que se van a quitar de la derecha ListBox
se determinan en el DragDrop controlador de eventos y el String
valor se agrega en el lugar adecuado de .ListBox
Si la operación de arrastre se mueve fuera de los límites del formulario, la operación de arrastrar y colocar se cancela en el QueryContinueDrag controlador de eventos.
Este extracto de código muestra cómo usar la DragEventArgs clase . Consulte el método para obtener el DoDragDrop ejemplo 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
En el ejemplo siguiente se muestra cómo DragEventArgs se pasan entre el origen y el destino de una operación de arrastrar y colocar. En este ejemplo, un ListBox control es el origen de los datos y el RichTextBox control es el destino. En el ejemplo se supone que el ListBox control se ha rellenado con una lista de nombres de archivo válidos. Cuando el usuario arrastra uno de los nombres de archivo mostrados del ListBox control al RichTextBox control, se abre el archivo al que se hace referencia en el nombre de archivo.
La operación se inicia en el ListBox evento MouseDown del control. En el controlador de eventos, en el DragEnter ejemplo se usa el GetDataPresent método para comprobar que los datos están en un formato que el RichTextBox control puede mostrar y, a continuación, establece la DragDropEffects propiedad para especificar que los datos se deben copiar del control de código fuente al control de destino. Por último, el RichTextBox controlador de eventos DragDrop del control usa el GetData método para recuperar el nombre de archivo que se va a abrir.
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
Comentarios
El DragDrop evento se produce cuando el usuario completa una operación de arrastrar y colocar arrastrando un objeto sobre el control y, a continuación, colóquelo en el control liberando el botón del mouse. El DragEnter evento se produce cuando el usuario mueve el puntero del mouse al control mientras arrastra un objeto con el mouse. El DragOver evento se produce cuando el usuario mueve el puntero del mouse sobre el control mientras arrastra un objeto con el mouse.
Un DragEventArgs objeto especifica los datos asociados a este evento; el estado actual de las teclas MAYÚS, CTRL y ALT; la ubicación del puntero del mouse y los efectos de arrastrar y colocar permitidos por el origen y el destino del evento de arrastre.
Para obtener información sobre el modelo de eventos, consulte Control y generación de eventos.
Constructores
DragEventArgs(IDataObject, Int32, Int32, Int32, DragDropEffects, DragDropEffects) |
Inicializa una nueva instancia de la clase DragEventArgs. |
DragEventArgs(IDataObject, Int32, Int32, Int32, DragDropEffects, DragDropEffects, DropImageType, String, String) |
Inicializa una nueva instancia de la clase DragEventArgs. |
Propiedades
AllowedEffect |
Obtiene las operaciones de arrastrar y colocar permitidas por el autor (u origen) del evento arrastrar. |
Data |
Obtiene la interfaz IDataObject que contiene los datos asociados a este evento. |
DropImageType |
Obtiene o establece el tipo de imagen de descripción de colocación. |
Effect |
Obtiene o establece el efecto de colocación en el destino de una operación de arrastrar y colocar. |
KeyState |
Obtiene el estado actual de las teclas MAYÚS, CTRL y ALT, así como el estado de los botones del mouse. |
Message |
Obtiene o establece el texto de la descripción desplegable, como "Mover a %1". |
MessageReplacementToken |
Obtiene o establece el texto de la descripción desplegable, como "Documentos", cuando se especifica %1 en Message. |
X |
Obtiene la coordenada X del puntero del mouse, en coordenadas de pantalla. |
Y |
Obtiene la coordenada Y del puntero del mouse, en coordenadas de pantalla. |
Métodos
Equals(Object) |
Determina si el objeto especificado es igual que el objeto actual. (Heredado de Object) |
GetHashCode() |
Sirve como la función hash predeterminada. (Heredado de Object) |
GetType() |
Obtiene el Type de la instancia actual. (Heredado de Object) |
MemberwiseClone() |
Crea una copia superficial del Object actual. (Heredado de Object) |
ToString() |
Devuelve una cadena que representa el objeto actual. (Heredado de Object) |
Se aplica a
Consulte también
Comentarios
https://aka.ms/ContentUserFeedback.
Próximamente: A lo largo de 2024 iremos eliminando gradualmente GitHub Issues como mecanismo de comentarios sobre el contenido y lo sustituiremos por un nuevo sistema de comentarios. Para más información, vea:Enviar y ver comentarios de