0

我有一个要拖动的标签。我单击标签,然后在 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
  }
}
4

1 回答 1

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);
  }
}
于 2013-10-30T18:44:03.127 回答