【背景】
编写Winform控件时,经常会遇到鼠标拖动物件,然后显示同步等需求。
【问题】
鼠标拖动物件时,物件会“加速移动”。
一般情况下,我们会在MouseDown事件中记录拖动物件开始(也就是鼠标左键按下)时的变量值。如:是否拖动中 isDragging, 按下时的位置 mouseDownLocation等。
然后,再在MouseMove事件中,使用当前鼠标位置e.Location的值,减去mouseDownLocation。再在Paint事件中绘制拖动后的结果进行显示。
private bool isDragging = false;
private Point mouseDownLocation;
private void ControlObject_MouseDown(object sender, MouseEventArgs e)
{
// 其他代码....
mouseDownLocation = e.Location;
isDragging=true;
// 其他代码....
}
private void ControlObject_MouseMove(object sender, MouseEventArgs e)
{
if(isDragging)
{
int dx=e.Location.X - mouseDownLocation.X;
int dy=e.Location.Y - mouseDownLocation.Y;
UpdateControlLocation(dx, dy);
// 其他代码....
}
// 其他代码....
}
private void ControlObject_Paint(...)
{
//显示代码
}
如按以上的