C# 窗口随鼠标移动:跳动问题的解决方法
很多人,在刚开始准备学习 窗口随鼠标移动 的时候
网上的绝大多数代码,都会出现这样的问题:
1.当你窗口初始位置不为 (0,0) 时,鼠标一按下窗口就会发生跳动;
2.如果你得窗口初始位置为 (0,0) 时,在进行第一次鼠标随窗口移动的操作后,若你还想继续进行此操作,则会出现和 1 中一样的,鼠标按下窗口就会跳动的情况。
出现上面的问题,一般是对窗口的初始位置设置不严谨的原因,所以我们只需要添加一个 temp 全局变量来存储相关位置坐标即可轻松解决~
具体代码如下:
private Point mousePoint = new Point();
private Point temp = new Point(50,50);
private Boolean leftflag = false;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
leftflag = true;
mousePoint = MousePosition;
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (leftflag)
{
rect_Location.X = temp.X + MousePosition.X - mousePoint.X;
rect_Location.Y = temp.Y + MousePosition.Y - mousePoint.Y;
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
leftflag = false;
temp.X = rect_Location.X;
temp.Y = rect_Location.Y;
}