Drag and drop windows form

Пошаговое руководство. Выполнение операции перетаскивания в Windows Forms Walkthrough: Performing a Drag-and-Drop Operation in Windows Forms

Для выполнения операций перетаскивания в приложениях на основе Windows необходимо выполнить обработку ряда событий, особенно DragEnter DragLeave событий, и DragDrop . To perform drag-and-drop operations within Windows-based applications you must handle a series of events, most notably the DragEnter, DragLeave, and DragDrop events. Работая со сведениями, доступными через аргументы этих событий, можно значительно упростить операции перетаскивания. By working with the information available in the event arguments of these events, you can easily facilitate drag-and-drop operations.

Перетаскивание данных Dragging Data

Все операции перетаскивания начинаются с переноса данных. All drag-and-drop operations begin with dragging. Функция, позволяющая собирать данные при начале перетаскивания, реализуется в DoDragDrop методе. The functionality to enable data to be collected when dragging begins is implemented in the DoDragDrop method.

В следующем примере MouseDown событие используется для запуска операции перетаскивания, поскольку она является наиболее интуитивно понятной (большинство действий по перетаскиванию начинается с нажатия кнопки мыши). In the following example, the MouseDown event is used to start the drag operation because it is the most intuitive (most drag-and-drop actions begin with the mouse button being depressed). Однако не забывайте, что любое событие может использоваться для инициализации процедуры перетаскивания. However, remember that any event could be used to initiate a drag-and-drop procedure.

Некоторые элементы управления имеют собственные события перетаскивания. Certain controls have custom drag-specific events. ListView TreeView Для элементов управления и, например, имеется ItemDrag событие. The ListView and TreeView controls, for example, have an ItemDrag event.

Начало операции перетаскивания To start a drag operation

В MouseDown событии для элемента управления, в котором начнется перетаскивание, используйте DoDragDrop метод, чтобы задать перетаскиваемые данные и разрешить перетаскивание разрешенных эффектов. In the MouseDown event for the control where the drag will begin, use the DoDragDrop method to set the data to be dragged and the allowed effect dragging will have. Дополнительные сведения см. в разделах Data и AllowedEffect. For more information, see Data and AllowedEffect.

В следующем примере показан запуск операции перетаскивания. The following example shows how to initiate a drag operation. Элемент управления, в котором начинается перетаскивание Button , является элементом управления, перетаскиваемые данные — это строка, представляющая Text свойство Button элемента управления, и разрешенные эффекты можно копировать или перемещать. The control where the drag begins is a Button control, the data being dragged is the string representing the Text property of the Button control, and the allowed effects are either copying or moving.

В качестве параметра в методе можно использовать любые данные DoDragDrop . в приведенном выше примере Text Button используется свойство элемента управления (вместо жесткого кодирования значения или извлечения данных из набора данных), поскольку свойство было связано с расположением, которое перетаскивается из ( Button элемент управления). Any data can be used as a parameter in the DoDragDrop method; in the example above, the Text property of the Button control was used (rather than hard-coding a value or retrieving data from a dataset) because the property was related to the location being dragged from (the Button control). Учитывайте это при реализации операций перетаскивания в приложениях Windows. Keep this in mind as you incorporate drag-and-drop operations into your Windows-based applications.

Пока действует операция перетаскивания, можно выполнить обработку QueryContinueDrag события, которое «запрашивает разрешение» системы, чтобы продолжить операцию перетаскивания. While a drag operation is in effect, you can handle the QueryContinueDrag event, which «asks permission» of the system to continue the drag operation. При обработке этого метода также является подходящая точка для вызова методов, которые влияют на операцию перетаскивания, например, расширение объекта TreeNode в TreeView элементе управления при наведении курсора мыши на него. When handling this method, it is also the appropriate point for you to call methods that will have an effect on the drag operation, such as expanding a TreeNode in a TreeView control when the cursor hovers over it.

Читайте также:  Система macos отличие от windows

Завершение перетаскивания данных Dropping Data

После начала перетаскивания данных из расположения в форме Windows Forms или элементе управления их требуется куда-то поместить. Once you have begun dragging data from a location on a Windows Form or control, you will naturally want to drop it somewhere. При попадании курсора в область формы или элемента управления, которые правильно настроены для размещения данных, вид курсора изменится. The cursor will change when it crosses an area of a form or control that is correctly configured for dropping data. Любая область внутри формы или элемента управления Windows может быть сделана для приема пропущенных данных путем установки AllowDrop Свойства и обработки DragEnter DragDrop событий и. Any area within a Windows Form or control can be made to accept dropped data by setting the AllowDrop property and handling the DragEnter and DragDrop events.

Завершение операции перетаскивания To perform a drop

Присвойте AllowDrop свойству значение true. Set the AllowDrop property to true.

В DragEnter событии для элемента управления, в котором будет выполняться перетаскивание, убедитесь, что перетаскиваемые данные имеют допустимый тип (в данном случае Text ). In the DragEnter event for the control where the drop will occur, ensure that the data being dragged is of an acceptable type (in this case, Text). Затем код задает результат, который будет выполняться при выполнении перетаскивания в значение в DragDropEffects перечислении. The code then sets the effect that will happen when the drop occurs to a value in the DragDropEffects enumeration. Для получения дополнительной информации см. Effect. For more information, see Effect.

Вы можете определить собственное DataFormats , указав собственный объект в качестве Object параметра SetData метода. You can define your own DataFormats by specifying your own object as the Object parameter of the SetData method. При этом необходимо убедиться, что указанный объект является сериализуемым. Be sure, when doing this, that the object specified is serializable. Для получения дополнительной информации см. ISerializable. For more information, see ISerializable.

В DragDrop событии для элемента управления, в котором будет выполняться удаление, используйте GetData метод для получения перетаскиваемых данных. In the DragDrop event for the control where the drop will occur, use the GetData method to retrieve the data being dragged. Для получения дополнительной информации см. Data. For more information, see Data.

В приведенном ниже примере элемент TextBox управления — это элемент управления, к которому выполняется перетаскивание (где произойдет удаление). In the example below, a TextBox control is the control being dragged to (where the drop will occur). Код задает Text свойство TextBox элемента управления, равное перетаскиваемых данным. The code sets the Text property of the TextBox control equal to the data being dragged.

Кроме того, можно работать со KeyState свойством, чтобы, в зависимости от нажатых клавиш во время операции перетаскивания, были выполнены определенные эффекты (например, для копирования перетаскиваемых данных при нажатии клавиши CTRL). Additionally, you can work with the KeyState property, so that, depending on keys depressed during the drag-and-drop operation, certain effects occur (for example, it is standard to copy the dragged data when the CTRL key is pressed).

Walkthrough: Performing a Drag-and-Drop Operation in Windows Forms

To perform drag-and-drop operations within Windows-based applications you must handle a series of events, most notably the DragEnter, DragLeave, and DragDrop events. By working with the information available in the event arguments of these events, you can easily facilitate drag-and-drop operations.

Dragging Data

All drag-and-drop operations begin with dragging. The functionality to enable data to be collected when dragging begins is implemented in the DoDragDrop method.

In the following example, the MouseDown event is used to start the drag operation because it is the most intuitive (most drag-and-drop actions begin with the mouse button being depressed). However, remember that any event could be used to initiate a drag-and-drop procedure.

Читайте также:  Как убрать лишние копии windows при запуске

Certain controls have custom drag-specific events. The ListView and TreeView controls, for example, have an ItemDrag event.

To start a drag operation

In the MouseDown event for the control where the drag will begin, use the DoDragDrop method to set the data to be dragged and the allowed effect dragging will have. For more information, see Data and AllowedEffect.

The following example shows how to initiate a drag operation. The control where the drag begins is a Button control, the data being dragged is the string representing the Text property of the Button control, and the allowed effects are either copying or moving.

Any data can be used as a parameter in the DoDragDrop method; in the example above, the Text property of the Button control was used (rather than hard-coding a value or retrieving data from a dataset) because the property was related to the location being dragged from (the Button control). Keep this in mind as you incorporate drag-and-drop operations into your Windows-based applications.

While a drag operation is in effect, you can handle the QueryContinueDrag event, which «asks permission» of the system to continue the drag operation. When handling this method, it is also the appropriate point for you to call methods that will have an effect on the drag operation, such as expanding a TreeNode in a TreeView control when the cursor hovers over it.

Dropping Data

Once you have begun dragging data from a location on a Windows Form or control, you will naturally want to drop it somewhere. The cursor will change when it crosses an area of a form or control that is correctly configured for dropping data. Any area within a Windows Form or control can be made to accept dropped data by setting the AllowDrop property and handling the DragEnter and DragDrop events.

To perform a drop

Set the AllowDrop property to true.

In the DragEnter event for the control where the drop will occur, ensure that the data being dragged is of an acceptable type (in this case, Text). The code then sets the effect that will happen when the drop occurs to a value in the DragDropEffects enumeration. For more information, see Effect.

You can define your own DataFormats by specifying your own object as the Object parameter of the SetData method. Be sure, when doing this, that the object specified is serializable. For more information, see ISerializable.

In the DragDrop event for the control where the drop will occur, use the GetData method to retrieve the data being dragged. For more information, see Data.

In the example below, a TextBox control is the control being dragged to (where the drop will occur). The code sets the Text property of the TextBox control equal to the data being dragged.

Additionally, you can work with the KeyState property, so that, depending on keys depressed during the drag-and-drop operation, certain effects occur (for example, it is standard to copy the dragged data when the CTRL key is pressed).

Control. Drag Drop Событие

Определение

Вызывается при завершении операции перетаскивания. Occurs when a drag-and-drop operation is completed.

Тип события

Примеры

Этот фрагмент кода демонстрирует использование DragDrop события. This code excerpt demonstrates using the DragDrop event. DoDragDropПолный пример кода см. в описании метода. See the DoDragDrop method for the complete code example.

Комментарии

XСвойства и Y объекта DragEventArgs находятся в экранных координатах, а не на клиентских координатах. The X and Y properties of the DragEventArgs are in screen coordinates, not client coordinates. Следующая строка кода Visual C# преобразует свойства в клиент Point . The following line of Visual C# code converts the properties to a client Point.

В версиях более ранних, чем платформа .NET Framework 2,0, при UserControl помещении DragEnter с DragDrop событиями и в Windows Forms и перетаскивании чего-либо UserControl во время разработки создаются DropDrop DropEnter события и. In versions earlier than .NET Framework 2.0, if you put a UserControl with DragEnter and DragDrop events on a Windows Form and drag and drop something onto the UserControl at design time, the DropDrop and DropEnter events are raised. Однако при закрытии и повторном открытии решения DragEnter DragDrop события и не вызываются снова. However, when you close and reopen the solution, the DragEnter and DragDrop events are not raised again.

Читайте также:  Как разбить диски для установки linux

Дополнительные сведения об обработке событий см. в разделе обработка и вызов событий. For more information about handling events, see Handling and Raising Events.

Drag-and-drop mouse behavior overview (Windows Forms .NET)

Windows Forms includes a set of methods, events, and classes that implement drag-and-drop behavior. This topic provides an overview of the drag-and-drop support in Windows Forms.

The Desktop Guide documentation for .NET 5 (and .NET Core) is under construction.

Drag-and-drop events

There are two categories of events in a drag and drop operation: events that occur on the current target of the drag-and-drop operation, and events that occur on the source of the drag and drop operation. To perform drag-and-drop operations, you must handle these events. By working with the information available in the event arguments of these events, you can easily facilitate drag-and-drop operations.

Events on the current drop target

The following table shows the events that occur on the current target of a drag-and-drop operation.

Mouse Event Description
DragEnter This event occurs when an object is dragged into the control’s bounds. The handler for this event receives an argument of type DragEventArgs.
DragOver This event occurs when an object is dragged while the mouse pointer is within the control’s bounds. The handler for this event receives an argument of type DragEventArgs.
DragDrop This event occurs when a drag-and-drop operation is completed. The handler for this event receives an argument of type DragEventArgs.
DragLeave This event occurs when an object is dragged out of the control’s bounds. The handler for this event receives an argument of type EventArgs.

The DragEventArgs class provides the location of the mouse pointer, the current state of the mouse buttons and modifier keys of the keyboard, the data being dragged, and DragDropEffects values that specify the operations allowed by the source of the drag event and the target drop effect for the operation.

Events on the drop source

The following table shows the events that occur on the source of the drag-and-drop operation.

Mouse Event Description
GiveFeedback This event occurs during a drag operation. It provides an opportunity to give a visual cue to the user that the drag-and-drop operation is occurring, such as changing the mouse pointer. The handler for this event receives an argument of type GiveFeedbackEventArgs.
QueryContinueDrag This event is raised during a drag-and-drop operation and enables the drag source to determine whether the drag-and-drop operation should be canceled. The handler for this event receives an argument of type QueryContinueDragEventArgs.

The QueryContinueDragEventArgs class provides the current state of the mouse buttons and modifier keys of the keyboard, a value specifying whether the ESC key was pressed, and a DragAction value that can be set to specify whether the drag-and-drop operation should continue.

Performing drag-and-drop

Drag-and-drop operations always involve two components, the drag source and the drop target. To start a drag-and-drop operation, designate a control as the source and handle the MouseDown event. In the event handler, call the DoDragDrop method providing the data associated with the drop and the a DragDropEffects value.

Set the target control’s AllowDrop property set to true to allow that control to accept a drag-and-drop operation. The target handles two events, first an event in response to the drag being over the control, such as DragOver. And a second event which is the drop action itself, DragDrop.

The following example demonstrates a drag from a Label control to a TextBox. When the drag is completed, the TextBox responds by assigning the label’s text to itself.

For more information about the drag effects, see Data and AllowedEffect.

Оцените статью