Drag and Drop

From IronPython Cookbook

Adapted from this example.

This code shows how to register a component for 'drag and drop', so that you can drag and drop files onto it.

In this code, if you drag files onto a listbox, the filepaths will be added to the listbox.

Drag and drop onto a ListBox

You need to handle both the DragEnter and the DragDrop events.

import clr
clr.AddReference('System.Windows.Forms')
clr.AddReference('System.Drawing')

from System.Drawing import Point, Size
from System.Windows.Forms import Application, DragDropEffects, DataFormats, Form, ListBox


class DragAndDropForm(Form):
    def __init__(self):
    
        self._listBox1 = ListBox()
        self._listBox1.AllowDrop = True
        self._listBox1.FormattingEnabled = True
        self._listBox1.ItemHeight = 12
        self._listBox1.Location = Point(12, 19)
        self._listBox1.Size = Size(413, 208)
        self._listBox1.TabIndex = 0
        self._listBox1.DragEnter += self._drag_enter
        self._listBox1.DragDrop += self._drag_drop
        
        
        self.AllowDrop = True
        self.ClientSize = Size(440, 250)
        self.Controls.Add(self._listBox1)
        
        self.Text = 'Drag and Drop Form'


    def _drag_enter(self, sender, e):
        if e.Data.GetDataPresent(DataFormats.FileDrop):
            e.Effect = DragDropEffects.All
        else:
            e.Effect = DragDropEffects.None


    def _drag_drop(self, sender, e):            
        data = e.Data.GetData(DataFormats.FileDrop, False)            
        for s in data:
            print self._listBox1.Items.Add(s)            

dNd = DragAndDropForm()
Application.Run(dNd)


Back to Contents.

TOOLBOX
LANGUAGES