Drag and Drop

From IronPython Cookbook

Revision as of 14:03, 14 June 2007 by MichaelFoord (Talk | contribs)

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

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.