First paste the code
Private bool isMouseDown = false;
Private Point mouseOffset; // records the coordinates of the mouse pointer.
Private void PicBox_MouseDown (object sender, MouseEventArgs e)
{
If (e. Button = MouseButtons. Left)
{
MouseOffset. X = e. X;
MouseOffset. Y = e. Y;
IsMouseDown = true;
}
}
Private void PicBox_MouseMove (object sender, MouseEventArgs e)
{
If (isMouseDown)
{
Int left = PicBox. Left + e. X-mouseOffset. X;
Int top = PicBox. Top + e. Y-mouseOffset. Y;
PicBox. Location = new Point (left, top );
}
}
Private void PicBox_MouseUp (object sender, MouseEventArgs e)
{
If (e. Button = MouseButtons. Left)
{
IsMouseDown = false;
}
}
MouseEventArgs e in the event:
According to the coordinates obtained by e,It is not the coordinate between the mouse and the upper left corner of the Form, but the coordinate relative to the upper left corner of the image box,So when calculating the mouse offset, you only need to calculate the difference between the coordinates of the two event object e!
Save the coordinates relative to the upper left corner of the image box when you press the mouse.
MouseOffset. X = e. X;
MouseOffset. Y = e. Y;
Offset obtained when moving
E. X-mouseOffset. X;
E. Y-mouseOffset. Y;
Calculate the new position of the image frame.
Int left = PicBox. Left + e. X-mouseOffset. X;
Int top = PicBox. Top + e. Y-mouseOffset. Y;