0

Is it possible to drag files directly onto a windows form or does it have to be onto a control on the windows form? I have been using the below code for quite some time, but this requires you drag onto a ListView

public Form1()
{
  InitializeComponent();
  this.Load += new EventHandler(Form1_Load);
}
void Form1_Load(object sender, EventArgs e)
{
  this.listView1.AllowDrop = true;
  this.listView1.Columns.Add("File name");
  this.listView1.Dock = DockStyle.Fill;
  this.listView1.SmallImageList = this.imageList1;
  this.listView1.View = View.Details;
  this.listView1.DragEnter += new DragEventHandler(listView1_DragEnter);
  this.listView1.DragDrop += new DragEventHandler(listView1_DragDrop);
}
void listView1_DragEnter(object sender, DragEventArgs e)
{
  if (e.Data.GetDataPresent("FileDrop") &&
      (e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy)
{
    e.Effect = DragDropEffects.Copy;
}
}

void listView1_DragDrop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent("FileDrop") &&
    (e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy)
    {
        string[] filePaths = (string[])e.Data.GetData("FileDrop");
        ListViewItem[] items = new ListViewItem[filePaths.Length];
        string filePath;
        for (int index = 0; index < filePaths.Length; index++)
        {
          filePath = filePaths[index];
          if (!this.imageList1.Images.Keys.Contains(filePath))
          {
            this.imageList1.Images.Add(filePath,
            Icon.ExtractAssociatedIcon(filePath));
          }
        items[index] = new ListViewItem(filePath, filePath);
    }
      this.listView1.Items.AddRange(items);
  }
}
  • 1
    Sure: `Form` inherits from `Control`, which is where all the `DragDrop` etc events are declared. Just add the handlers to the form instead of the listbox. – Blorgbeard Apr 10 '15 at 02:57
  • possible duplicate of [How do I drag and drop files into a C# application?](http://stackoverflow.com/questions/68598/how-do-i-drag-and-drop-files-into-a-c-sharp-application) – Prime Apr 10 '15 at 02:59

1 Answers1

2
this.DragDrop += new DragEventHandler(form_DragDrop);
Jon Tirjan
  • 3,556
  • 2
  • 16
  • 24