The .NET Framework makes it easy to detect objects dragged and/or dropped into a Windows Forms application using one or more of the drag-and-drop events available. In these events you could check if the object is a file.

dragndrop

To enable a control to be a target of a drag-and-drop operation set its AllowDrop property to true and use one or more of the following events:

  • DragEnter: Occurs when the user drags an object into the control's area, and has not released the mouse button yet.
  • DragOver: Occurs when the object is being dragged in the control's area.
  • DragDrop: Occurs when the user lets go of the dragged object in the control's area.
  • DragLeave: Occurs if the object dragged into the control is dragged out again without the user releasing the mouse button, or the user canceled the operation by pressing the Escape key.
  • GiveFeedback: Occurs when the drag-and-drop operation starts and is used to modify the visual feedback of the operation.
  • QueryContinueDrag: Occurs when the keyboard or mouse state is changed during the drag-and-drop operation.

To process one or more files dragged and dropped into a control two events are needed, DragEnter and DragDrop. The if statement in DragEnter checks what is dragged in is of type DataFormats.FileDrop, the Windows file drop format, or not. If true the drag operation is allowed. The DragDrop event retrieves the list of files dropped using the GetData method and casts them to an array of strings. Each element of the array will contain a full path of one of the files dropped.

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);
    }
}