Thursday, March 25, 2010

DoDragDrop prevents DoubleClick event from firing

I've tried implementing Drag & Drop in a ListView object, however, calling DoDragDrop from either MouseMove or MouseDown prevented DoubleClick event from firing.

There are few posts online about it, mostly saying using MouseDown event and checking:
e.Clicks == 1
(see for example: here)

However this didn't work for me (DoubleClick fired some times, but most of the time it didn't). After doing further research I came with the following full solution:


bool _beginDragDrop = false;

void ListViewBase_MouseMove(object sender, MouseEventArgs e)
{
if ((e.Button == MouseButtons.Left)&&(_beginDragDrop == true))
{
// Replace this with the object you want to Drag & Drop
object draggedObject = this;
this.DoDragDrop(draggedObject, DragDropEffects.Copy);
}
}

void ListViewBase_MouseDown(object sender, MouseEventArgs e)
{
if ((e.Button == MouseButtons.Left) && (e.Clicks == 1))
_beginDragDrop = true;
else
_beginDragDrop = false;
}

2 comments:

Jonathon Reinhart said...
This comment has been removed by the author.
Jonathon Reinhart said...

Perfect, exactly what I was looking for. Thanks!

The only thing is, I added
_beginDragDrop = false;
after the DoDragDrop() call, to make sure it is cleared. In my case, I was using a common _beginDragDrop for a bunch of separate tool strip buttons.