Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement file dragging to the desktop from a .net winforms application?

I have a list of files with their names in a listbox and their contents stored in an SQL table and want the user of my app to be able to select one or more of the filenames in the listbox and drag them to the desktop, yielding the actual files on the desktop. I can't find any documentation on how to do this. Can anyone explain or point to an explanation?

Added later: I've been able to make this work by handling the DragLeave event. In it I create a file in a temporary directory with the selected name and the contents pulled from SQL Server. I then put the path to the file into the object:

var files = new string[1];
files[0] = "full path to temporary file";
var dob = new DataObject();    
dob.SetData(DataFormats.FileDrop, files);
DoDragDrop(dob, DragDropEffects.Copy);

But this seems very inefficient and clumsy, and I have not yet figured out a good way to get rid of accumulated temp files.

like image 643
mlo Avatar asked Jun 17 '09 19:06

mlo


People also ask

What is AllowDrop in VB net?

AllowDrop. Boolean property, indicating whether the control can accept data that the user drags onto it. False by default. DoDragDrop.

How to drag and drop in Windows application c#?

To perform a dropSet the AllowDrop property to true. In the DragEnter event for the control where the drop will occur, ensure that the data being dragged is of an acceptable type (in this case, Text). The code then sets the effect that will happen when the drop occurs to a value in the DragDropEffects enumeration.


2 Answers

I can help you somewhat. Here's some code that will allow you to drag something out of the listbox, and when dropped on the desktop, it will create a copy of a file that exists on your machine to the desktop.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.listBox1.Items.Add("foo.txt");
        this.listBox1.MouseDown += new MouseEventHandler(listBox1_MouseDown);
        this.listBox1.DragOver += new DragEventHandler(listBox1_DragOver);
    }

    void listBox1_DragOver(object sender, DragEventArgs e)
    {
        e.Effect = DragDropEffects.Copy;
    }

    void listBox1_MouseDown(object sender, MouseEventArgs e)
    {
        string[] filesToDrag = 
        {
            "c:/foo.txt"
        };
        this.listBox1.DoDragDrop(new DataObject(DataFormats.FileDrop, filesToDrag), DragDropEffects.Copy);
    }
}
like image 162
BFree Avatar answered Oct 21 '22 07:10

BFree


I found a better solution by extending System.Windows.Forms.DataObject
Transferring Virtual Files to Windows Explorer in C#

also found some threads here on StackOverFlow that may help
Drag and drop large virtual files from C# to Windows Explorer

like image 34
MrBassam Avatar answered Oct 21 '22 05:10

MrBassam