C # Move the image frame with the mouse

Source: Internet
Author: User

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;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.