Use the mouse to draw a rectangular box on a C # PictureBox image

Source: Internet
Author: User

C # in the picture frame, through the mouse to achieve the main four message response function MouseDown, MouseMove, MouseUp, paint redraw function implementation. When the mouse button is pressed to start the frame, the mouse button lifted up when the frame ends.

Point start; The start point of the frame end,//the end point of the frame
BOOL blndraw;//judge whether to draw
Rectangel rect;

Mouse Down response

private void Picturebox1_mousedown (object sender, MouseEventArgs e) {      start = e.location;      Invalidate ();      Blndraw = true;}

Mouse Motion Response

private void Picturebox1_mousemove (object sender, MouseEventArgs e) {    if (Blndraw)    {        if (e.button! = MouseButtons.Left)//Determine whether to press the left key            return;        Point tempendpoint = e.location; The position and size of the record box is        rect. Location = new Point (        math.min (start). X, Tempendpoint.x),        math.min (start. Y, Tempendpoint.y));        Rect. size = new Size (        math.abs (start). X-tempendpoint.x),        math.abs (start. Y-TEMPENDPOINT.Y));        Picturebox1.invalidate ();     }}        

mouse button Lift response

private void Picturebox1_mouseup (object sender, MouseEventArgs e) {    Blndraw = false;//End Drawing}

Redraw response

private void Imagebox1_paint (object sender, PaintEventArgs e) {     if (Blndraw)     {         if (imagebox1.image! = null) c3/>{             if (rect! = null && rect. Width > 0 && rect. Height > 0)              {                  e.graphics.drawrectangle (new Pen (Color.Red, 3), rect);//Redraw color to Red               }          }}}      

Note: In drawing if the imported image is SizeMode to StretchImage, the image is scaled after the frame, causing the box to not be in PictureBox, and the functionmode of the PictureBox need to be modified to minimum.

Use the mouse to draw a rectangular box on a C # PictureBox image

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.