fifamaniac04
fifamaniac04

Reputation: 2383

MouseMove doesn't get the right coordinate points

I have a label I am trying to drag. I click on the label, and on the MouseMove() event I am trying to relocate the position of the label.

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

Upvotes: 0

Views: 1024

Answers (1)

LarsTech
LarsTech

Reputation: 81675

You usually need to store the offset location of the initial mouse down point in the control, or else the control will move on you in a jittering fashion. Then you just do the math:

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

Upvotes: 3

Related Questions