Drag+Drop和MouseClick

项目中的一个树形结节,既要响应拖拽事件、又要响应点击事件。实现的时候没多想,依次实现了tree_MouseClick、tree_MouseDown、tree_MouseMove事件。出现的Bug是,偶尔会点击时不响应。

分析下来,应该是触发了MouseMove里的DoDragDrop拖拽事件,因此MouseClick被忽略了。如何正确实现呢?《Drap+Drop and MouseClick》这个帖子里给出了精确的解释,摘录如下:

Good implemented D'n'D doesn't start the operation on mouse down.
The drag operation has to start if the user presses the mouse button and
moves the mouse on a certain distance from the button-down point. Only if
this happens and all other conditions are met (see Bob's post) the
operation should be considered as starting D'n'D.

SystemInformation class has a property DragSize that should be used for
the size of the rectangle arround the click point in which the drag
operation shouldn't start.

大意就是说,不能一MouseMove就触发拖拽,而要超出一定距离之后,再触发。超出的范围,可以用系统设置SystemInformation.DragSize。于是在MouseMove里添加判断:

 1 private void tree_MouseMove(object sender, MouseEventArgs e)

 2 {

 3     if (mouseDownPosition == Point.Empty ||

 4         Math.Abs(e.X - mouseDownPosition.X) <= SystemInformation.DragSize.Width ||

 5         Math.Abs(e.Y - mouseDownPosition.Y) <= SystemInformation.DragSize.Height)

 6     {

 7         return;

 8     }

 9     (sender as TreeList).DoDragDrop(data, DragDropEffects.Copy);

10 }

搞定。

你可能感兴趣的:(click)