鼠标移动无法获得正确的坐标点

本文关键字:坐标 移动 鼠标 | 更新日期: 2023-09-27 18:37:27

我有一个标签,我试图拖动。我单击标签,在 MouseMove() 事件中,我正在尝试重新定位标签的位置。

public void MyLabel_MouseMove(object sender, MouseEventArgs e)
{
  if (e.Button == MouseButtons.Left)
  {
    ((Label)sender).Location = Cursor.Position;
    // I have also tried e.Location but none of these moves the label to
    // where the the cursor is, always around it, sometimes completely off
  }
}

鼠标移动无法获得正确的坐标点

通常需要在控件中存储初始鼠标按下点的偏移位置,否则控件将以抖动方式在您身上移动。 然后你只需做数学:

Point labelOffset = Point.Empty;
void MyLabel_MouseDown(object sender, MouseEventArgs e) {
  if (e.Button == MouseButtons.Left) {
    labelOffset = e.Location;
  }
}
void MyLabel_MouseMove(object sender, MouseEventArgs e) {
  if (e.Button == MouseButtons.Left) {
    Label l = sender as Label;
    l.Location = new Point(l.Left + e.X - labelOffset.X,
                           l.Top + e.Y - labelOffset.Y);
  }
}