MouseMove无法获得正确的坐标点

时间:2013-10-30 18:25:05

标签: c# winforms

我有一个标签,我试图拖动。我点击了标签,在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
  }
}

1 个答案:

答案 0 :(得分:3)

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

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);
  }
}