Search code examples
c#winformspictureboxonmousemove

Move a PictureBox with mouse


I'm developing an app for windows mobile (Compact Framework 2.0). It has a WinForms with a PictureBox.

I want to move the image of the PictureBox but I don't know how to do it so I choose to move the hole PictureBox.

To do it I use this event:

private void imagenMapa_MouseMove(object sender, MouseEventArgs e)
{
      imagenMapa.Left = e.X;
      imagenMapa.Top = e.Y;
      this.Refresh();
}

But when I move the PictureBox it blinks and moves every where.

What I'm doing wrong?


Solution

  • The e.X and e.Y are relative to the picture box (e.g. if the mouse is in the upper left of the picture box, that's 0,0) .

    The values for imagenMapa.Left and imagenMapa.Top are relative to the form (or whatever control contains imagenMapa)

    If you try to mix values from these two systems without conversion, you're going to get jumps (like you're seeing).

    You're probably better off converting the mouse position to the same coordinate system used by the thing that contains the picture box.

    You could use imagenMapa.PointToScreen to get the mouse coordinates in screen coordinates (or Cursor.Position to get the position directly), and yourForm.PointToClient to get them back in the form coordinates.

    Note that depending on your needs, you could accomplish "moving an image within a control" by overriding/handling the Paint event of a control and drawing the image yourself. If you did this, you could keep everything in the picturebox coordinates, since those are likely what you would use when you called graphicsObject.DrawImage.