Windows forms drag and drop

{lang: ‘ru’}

.NET Framework позволяет легко обнаруживать перетаскиваемые объекты в/из приложения Windows Forms. Для этого можно использовать одно или несколько из доступных событий drag and drop. В обработчиках этих событий можно проверить, является ли объект файлом.

Для включения отслеживания событий drag and drops, нужно установить свойство AllowDrop в true и использовать одно или несколько следующих событий:

  • DragEnter: Возникает при завершении операции перетаскивания

  • DragOver: Происходит, когда элемент перетаскивается с помощью мыши в клиентскую область этого элемента.

  • DragDrop: Возникает, когда объект перетаскивается за пределы элемента управления.

  • DragLeave: Возникает, когда объект перетаскивается на элемент управления.

  • GiveFeedback: Происходит, когда элемент перетаскивается с помощью мыши. Система запрашивает у элемента управления обеспечения обратной совместимости с этим эффектом.

  • QueryContinueDrag: Происходит при перетаскивании элемента. Система опрашивает, можно ли продолжать операцию перетаскивания мышью.

Чтобы обработать перетаскивание одного или нескольких файлов внутрь элемента управления, необходимо обработать два события: DragEnter и DragDrop. В DragEnter мы проверяем, что перетаскиваемый элемент имеет тип DataFormats.FileDrop. Если это так, операция перетаскивания правда операция перетаскивания разрешается. Событие DragDrop получает список файлов для помещения в элемент с помощью метода GetData и добавляет их в массив строк. Каждый элемент массива будет содержать полный путь к каждому файлу, помещенному в элемент управления.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

private void filesListBox_DragEnter(object sender, DragEventArgs e)

{

    if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)

    {

        e.Effect = DragDropEffects.All;

    }

}

private void filesListBox_DragDrop(object sender, DragEventArgs e)

{

    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

    foreach (string file in files)

    {

        filesListBox.Items.Add(file);

    }

}

Статья написана по мотивам оригинальной англоязычной версии. Исходный код с работающим примером так же доступен по ссылке из неё.

Полезная статья? Их будет больше, если вы поддержите меня!

Для выполнения операций перетаскивания и вставки в приложениях Windows необходимо обрабатывать последовательность событий, особенно DragEnter, DragLeave, и DragDrop события. Работая со сведениями, доступными через аргументы этих событий, можно значительно упростить операции перетаскивания.

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

Все операции перетаскивания начинаются с переноса данных. Функции для включения данных, собираемых при начале перетаскивания реализуются в DoDragDrop метод.

В следующем примере MouseDown событие используется для начала операции перетаскивания, так как он является самым удобным (большинство операций перетаскивания и вставки начинаются с кнопкой мыши). Однако не забывайте, что любое событие может использоваться для инициализации процедуры перетаскивания.

Note

Некоторые элементы управления имеют собственные события перетаскивания. ListView И TreeView элементов управления, например, быть ItemDrag событий.

Начало операции перетаскивания

  1. В MouseDown событий для элемента управления, в котором начнется перетаскивание, используйте DoDragDrop будут иметь метод, чтобы задать данные для переноса и разрешенный результат перетаскивания. Дополнительные сведения см. в разделах Data и AllowedEffect.

    В следующем примере показан запуск операции перетаскивания. Элемент управления, где начинается перетаскивание Button элемента управления, перетаскиваемых данных является строка, представляющая Text свойство Button управления и разрешенные эффекты копирование или перемещение.

    Private Sub Button1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseDown  
       Button1.DoDragDrop(Button1.Text, DragDropEffects.Copy Or DragDropEffects.Move)  
    End Sub  
    
    private void button1_MouseDown(object sender,   
    System.Windows.Forms.MouseEventArgs e)  
    {  
       button1.DoDragDrop(button1.Text, DragDropEffects.Copy |   
          DragDropEffects.Move);  
    }  
    
    Note

    Любые данные, которые могут использоваться в качестве параметра DoDragDrop метод; в примере выше, Text свойство Button управления был использован (а не жестко запрограммированного значения или получение данных из набора данных), так как свойство было связано с расположение которого выполнялось перетаскивание ( Button управления). Учитывайте это при реализации операций перетаскивания в приложениях Windows.

Во время операции перетаскивания по сути, можно обрабатывать QueryContinueDrag событие, которое «запрашивает разрешение» системы на продолжение операции перетаскивания. При обработке этого метода, он также является подходящей точкой для вызова методов, которые будет влиять на операцию перетаскивания, например расширение TreeNode в TreeView управления, когда курсор находится над ней.

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

После начала перетаскивания данных из расположения в форме Windows Forms или элементе управления их требуется куда-то поместить. При попадании курсора в область формы или элемента управления, которые правильно настроены для размещения данных, вид курсора изменится. Любую область формы Windows или элемента управления можно сделать для принятия перетаскиваемых данных, задав AllowDrop свойство и обработка DragEnter и DragDrop события.

Завершение операции перетаскивания

  1. Задайте AllowDrop присваивается значение true.

  2. В DragEnter событие элемента управления, в котором будет выполнено освобождение убедитесь, что перетаскиваемые данные к допустимому типу (в данном случае Text). Затем код задает эффект, который будет происходить при завершении перетаскивания в значение DragDropEffects перечисления. Дополнительные сведения см. в разделе Effect.

    Private Sub TextBox1_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles TextBox1.DragEnter  
       If (e.Data.GetDataPresent(DataFormats.Text)) Then  
         e.Effect = DragDropEffects.Copy  
       Else  
         e.Effect = DragDropEffects.None  
       End If  
    End Sub  
    
    private void textBox1_DragEnter(object sender,   
    System.Windows.Forms.DragEventArgs e)  
    {  
       if (e.Data.GetDataPresent(DataFormats.Text))   
          e.Effect = DragDropEffects.Copy;  
       else  
          e.Effect = DragDropEffects.None;  
    }  
    
    Note

    Можно определить собственные DataFormats , указав собственный объект как Object параметр SetData метод. При этом необходимо убедиться, что указанный объект является сериализуемым. Дополнительные сведения см. в разделе ISerializable.

  3. В DragDrop событий для элемента управления, в которых будет выполняться перетаскивания, используйте GetData метод для получения перетаскиваемых данных. Дополнительные сведения см. в разделе Data.

    В следующем примере TextBox управления является элементом управления, на который переносятся данные (в котором будет выполнено освобождение данных). В коде устанавливается Text свойство TextBox управления равным перетаскиваемым данным.

    Private Sub TextBox1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles TextBox1.DragDrop  
       TextBox1.Text = e.Data.GetData(DataFormats.Text).ToString  
    End Sub  
    
    private void textBox1_DragDrop(object sender,   
    System.Windows.Forms.DragEventArgs e)  
    {  
       textBox1.Text = e.Data.GetData(DataFormats.Text).ToString();  
    }  
    
    Note

    Кроме того, вы можете работать с KeyState свойство, поэтому, в зависимости от клавиш, нажатых во время операции перетаскивания и вставки, происходили определенные действия (например, происходит копирование переносимых данных при нажатии клавиши CTRL).

См. также

  • Практическое руководство. Добавление данных в буфер обмена
  • Практическое руководство. Извлечение данных из буфера обмена
  • Операции перетаскивания и поддержка буфера обмена

How to support drag-and-drop in Windows Forms.

Last week I was writing a Windows Forms application that needed to process data
that had been dragged onto it.

This sent me down a (small) rabbit hole. Supporting drag and drop was not quite
as straightforward as I initially thought!

Here’s how to do it, broken down into a few manageable steps.

1. Allow drag-and-drop on the control

Set the AllowDrop property to true on the control which data can be dragged
onto. If you don’t do this, then the events detailed below won’t fire.

This may be the whole form, or perhaps a label saying «drop here».

2. Handle the «enter» event

The DragEnter event fires when data is dragged over the control in question.
That is, the mouse enters the control’s bounds while the left button is pressed
and the user is dragging something.

This event uses DragEventArgs, which has the property AllowedEffect. This is
a flags enum containing all the different «effects» (Link, Copy,
Move)
allowed by the source of the drag. For example, if you drag a file from Windows
File Explorer, you’re allowed to link or copy but not move.

In the event handler, you need to set the value of DragEventArgs.Effect to one
of the allowed values. This does two things:

  • Changes the cursor to provide a visual cue to the user that drag-and-drop is
    possible (the default is a «no entry» cursor to indicate that drag-and-drop is
    not supported). The exact cursor used depends on which value you choose.
  • Sets up the DragDrop event to fire if/when the user releases the left mouse
    button (see below).

If you want to make a bigger visual change than just the cursor (e.g. change the
appearance of the control), then you should also do that in the DragEnter
event handler.

3. Handle the «drop» event

The DragDrop event fires when the user releases the mouse to drop data onto
the control.

The data that has been dragged can be found in DragEventArgs.Data. This is an
IDataObject, which contains the data in a number of «formats». The exact
formats used will depend on where the data was dragged from, so when developing
there’s a bit of trial and error to see which formats are appropriate for you to
use.

Some helpful methods on IDataObject:

  • GetFormats(): this returns a string[], each item of which is the name of a
    format the data can be provided in.
  • GetData(string format): this returns the data in the specified format.
    Because this method returns object, you’ll have to cast it before using it.
    If format is not recognised, it returns null.
  • GetDataPresent(string format): this returns a bool indicating whether the
    data is present in the specified format. This method could be used in the
    DragEnter event handler to determine whether to enable drag-and-drop at all.

As an example, one of the formats when dragging data from Windows File Explorer
was "FileName". If you call GetData("FileName") then you get a string[]
containing the full paths of the files being dragged.

Once you have the data you want you can then do whatever you like. For example,
my application reads in the file, transforms it, and puts the result in a text
box.

This event also uses DragEventArgs, and it uses the same instance as the one
provided in DragEnter, meaning you can inspect the value you chose for
Effect if you need to.

4. Handle the «leave» event (maybe)

The DragLeave event fires when the mouse leave the bounds of the control and
the user is still dragging the item.

Handling this event is only necessary if you need to tidy up from the
DragEnter event; perhaps you need to reset some visuals to indicate that
releasing the mouse won’t complete the drag-and-drop operation.

Example

The following example shows you how to accept files dragged from File Explorer.
It captures a file dragged onto dragDropLabel and displays the file contents
in outputTextBox.

using System.Linq;
using System.Windows.Forms;

private void dragDropLabel_DragEnter(object sender, DragEventArgs e)
{
    if (e.AllowedEffect.HasFlag(DragDropEffects.Copy) &&
        e.Data.GetData("FileName") is string[] fileNames &&
        fileNames.Any())
    {
        e.Effect = DragDropEffects.Copy;
    }
}

private void dragDropLabel_DragDrop(object sender, DragEventArgs e)
{
    var fileNames = (string[])e.Data.GetData("FileName");
    var fileName = fileNames[0];

    this.outputTextBox.Text = File.ReadAllText(fileName);
}

Appendix: exploring the data

While developing, the following snippet was useful for discovering what formats
were supported by DragEventArgs.Data and exactly how the data looked.

foreach (var format in e.Data.GetFormats())
{
    var data = e.Data.GetData(format);

    string text;
    if (data is MemoryStream ms)
    {
        using (var sr = new StreamReader(ms))
        {
            text = sr.ReadToEnd();
        }
    }
    else
    {
        text = data?.ToString();
    }

    System.Diagnostics.Debug.WriteLine($"{format}:{text}");
}

Dialog to open a file

Create a project of type “Windows Forms Application”:

On form add a textbox and a button like this:

Click twice on button “Open” to generate the click event:

Add the follow code:

  1. using (OpenFileDialog dialog = new OpenFileDialog())  
  2. {  
  3.    if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)  
  4.    {  
  5.       textBox1.Text = dialog.FileName;  
  6.    }  
  7. }  

Run your application.

Drag file from explorer to your Application

We need to set the property “allowdrop” to true on our textbox:

Now we need to implement the event DragOver on the textbox component:

At event created we need to add the follow code:

  1. private void textBox1_DragOver(object sender, DragEventArgs e)  
  2. {  
  3.    if (e.Data.GetDataPresent(DataFormats.FileDrop))  
  4.       e.Effect = DragDropEffects.Link;  
  5.    else  
  6.       e.Effect = DragDropEffects.None;  
  7. }  

The method “.Data.GetDataPresent(DataFormats.FileDrop)” check if is a File droping. In case true, we set the effect to “Link”.

Now we need to create event DragDrop on textbox:

At event created put this:

  1. private void textBox1_DragDrop(object sender, DragEventArgs e)  
  2. {  
  3.    string[] files = e.Data.GetData(DataFormats.FileDrop) as string[];   
  4.    if (files != null && files.Any())  
  5.       textBox1.Text = files.First();   
  6. }  

Run your application from generated “.exe”, from debug doesn’t work.

Many modern applications operate on files that a user can upload to their system. Image editors, code IDEs, and word processors are all examples. If you’re building a Windows Form application, you can easily add this functionality as part of your user interface.

Windows Form applications allow you to drag and drop UI elements such as panels or list boxes. You can use these UI elements to create your drag and drop functionality. When the user drags a file onto a panel, you can display feedback based on that file.

How to Create the UI for the Drag and Drop Container

You can use a panel element to create the UI for the drag and drop functionality. You can then use a ListBox UI element to display the names of any files a user drags onto the panel.

  1. Create a new Windows Forms application.
  2. In the toolbox, search for a panel UI element, and drag it onto the canvas.

    Dragging panel from toolbox to canvas

  3. Highlight the new panel. In the properties window, change the values of the following properties:

    Property

    New Value

    Name

    dragDropPanel

    BackColor

    WhiteSmoke

    BorderStyle

    FixedSingle

    Size

    600, 400

    Visible

    True

    Winforms panel with properties window

  4. In the toolbox, search for a ListBox UI element, and drag it onto the canvas. Position it so that it is inside the panel, and ensure that there is some spacing between the ListBox and the panel.

    Dragging ListBox element from toolbox to canvas

  5. Highlight the new ListBox, and change the values of the following properties:

    Property

    New Value

    Name

    uploadedFilesList

    BackColor

    WhiteSmoke

    BorderStyle

    None

    Size

    500, 300

    Visible

    False

    Winforms canvas with ListBox properties

How to Add the Drag and Drop Event

You can use events in a Windows Form application to execute certain functions only when certain events occur.

To add functionality to the drag and drop panel, you will need to add two events. The «DragEnter» event will occur when you drag files over the panel. The «DragDrop» event will occur when you let go of the mouse to drop the files into the panel.

  1. Highlight the outer panel UI element.

    Panel UI element highlighted on the canvas

  2. In the properties window, click on the Lightening icon to open the events list.

    List of events in properties window

  3. Double-click on the DragEnter event to generate a new function. This function will execute when you drag files over the panel.

    New DragEnter event for panel

  4. Inside the new function, change the icon of the mouse to indicate the drag/drop action:

            private void dragDropPanel_DragEnter(object sender, DragEventArgs e)
    {
        // Changes the icon of the mouse
        e.Effect = DragDropEffects.All;
    }
  5. Click on the Form 1.cs [Design] tab at the top of the Visual Studio window, to go back to the canvas view. Highlight the panel UI element.

    Changing tabs back to view canvas

  6. In the properties window, click on the Lightening icon to go back to the events list. This time, double-click on the DragDrop event. This will generate another function that will execute when you let go of the mouse to drop the files into the panel.

    New DragDrop event generated for panel in events list

  7. Inside the new DragDrop function, get the list of files that the user is dragging into the panel. You can find this in the event details that are automatically passed into the function.

            private void dragDropPanel_DragDrop(object sender, DragEventArgs e)
    {
        string[] files = (string[])e.Data.GetData(DataFormats.FileDrop, false);
    }

How to Display the List of Dragged Files

Now that you have added the functionality for the user to drag and drop files, you can display the names of the files using the ListBox UI element.

  1. Inside the dragDropPanel_DragDrop() function, after getting the list of files, use a for-loop to loop through each file.

            foreach (var file in files)
    {

                    }

  2. Inside the for-loop, only get the name of the file. Separate the name of the file from the file path, and store it in a separate variable. If you are using a Mac, you may need to modify the code to take into account forward slashes instead of backslashes.

            string fileName = file.Substring(file.LastIndexOf("\\") + 1, file.Length - (file.LastIndexOf("\\") + 1));
        
  3. Add the name of the file to the ListBox UI element.

            try
    {
        uploadedFilesList.Items.Add(fileName);
    }
    catch (Exception exception)
    {
        Console.WriteLine(exception);
    }
  4. The ListBox is not visible by default. After the for-loop, change the visibility of the ListBox to true:

            uploadedFilesList.Visible = true;
        
  5. Modify the constructor at the top of the file. Set the AllowDrop and AutoScroll properties of the drag and drop panel to true.

            public Form1()
    {
        InitializeComponent();
        dragDropPanel.AllowDrop = true;
        dragDropPanel.AutoScroll = true;
    }

How to Clear the List

After the user has dragged items into the panel, they may want to clear the list and start again. You can add a button to clear the list when the user clicks on it.

  1. Using the toolbox, drag a button onto the canvas.

    Dragging button UI element from toolbox to canvas

  2. Highlight the button. Use the properties window the change the following properties to the new values:

    Property

    New Value

    Name

    clearButton

    Text

    Clear

    Button highlighted in canvas with properties window open

  3. Double-click on the button to generate a new function. This function will execute when you click on the button at runtime:

            private void clearButton_Click(object sender, EventArgs e)
    {

    }

  4. Inside the function, clear the contents of the ListBox UI element and hide it:

            private void clearButton_Click(object sender, EventArgs e)
    {
        uploadedFilesList.Items.Clear();
        uploadedFilesList.Visible = false;
    }

How to Test the Drag and Drop Panel

To test the drag and drop functionality, run the application and drag some files into the panel. If needed, you can also debug your Winforms application in Visual Studio at runtime. This will help you understand what is happening in each line of code.

  1. Press the green play button at the top of the Visual Studio window to run the application.

    Play button at the top of Visual Studio

  2. Drag some files from your file explorer, and drop them into the panel. Make sure you are not running Visual Studio in administrator mode. You will need to configure extra security permissions for drag and drop to work in administrator mode.

    Files dragged into panel at runtime

  3. The panel will update to show you the names of the files you dragged into the panel.

    Files displaying inside panel at runtime

  4. Drag enough files and you’ll see the drag and drop panel displays a scrollbar on its right side automatically.

    Many files inside panel with scrollbars

  5. Click on the Clear button to empty the list.

    Panels list cleared at runtime

Using Drag and Drop Functionality in Windows Form Apps

Now you hopefully understand how to add drag and drop functionality to your Windows Form application. There are many other features you can explore to do interesting things with Windows Forms.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows get free ports
  • Windows 10 home single language x86
  • Как проверить работу клавиши windows
  • App installer windows 10 mobile
  • Boot ini windows server 2008