views:

272

answers:

2

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.

+3  A: 

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);
    }
}
BFree
I understand this, but what I don't understand is where foo.txt gets created and filled in with its contents from the SQL table.
mlo
A: 

Here's some of the boiler plate to help you determine when to start a drag-operation:

private Rectangle _DragRect;

private void MyDragSource_MouseDown(object sender, MouseEventArgs e) {
   Size dragsize = SystemInformation.DragSize;
   _DragRect = new Rectangle(new Point(e.X - (dragsize.Width / 2), e.Y - (dragsize.Height / 2)), dragsize);
}

private void MyDragSource_MouseMove(object sender, MouseEventArgs e) {
   if (e.Button == MouseButtons.Left) {
      if (_DragRect != Rectangle.Empty && !_DragRect.Contains(e.X, e.Y)) { 
         // the mouse has moved outside of the drag-rectangle.  Start drag operation

         MyDragSource.DoDragDrop(.....)
      }
   }
}

private void MyDragSource_MouseUp(object sender, MouseEventArgs e) {
   _DragRect = Rectangle.Empty; // reset
}
Yoopergeek