Drag+Drop和MouseClick

本文介绍了一种解决拖拽事件与点击事件冲突的方法。通过调整拖拽事件的触发条件,确保只有当鼠标移动超过一定距离后才启动拖拽操作,从而避免误触导致的点击事件失效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目中的一个树形结节,既要响应拖拽事件、又要响应点击事件。实现的时候没多想,依次实现了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 }

搞定。

转载于:https://www.cnblogs.com/AlexanderYao/p/3765927.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值