Drag and Drop

From IronPython Cookbook

(Difference between revisions)
Line 6: Line 6:
[[Image:Dnd.jpg|Drag and drop onto a ListBox]]
[[Image:Dnd.jpg|Drag and drop onto a ListBox]]
You need to handle ''both'' the [http://msdn2.microsoft.com/en-us/library/system.windows.forms.control.dragenter(vs.80).aspx DragEnter] and the [http://msdn2.microsoft.com/en-us/library/system.windows.forms.control.dragdrop(vs.80).aspx DragDrop] events.

Current revision as of 14:05, 14 June 2007

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

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.Text = 'Drag and Drop Form'

    def _drag_enter(self, sender, e):
        if e.Data.GetDataPresent(DataFormats.FileDrop):
            e.Effect = DragDropEffects.All
            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()

Back to Contents.