First on
Three mouse events
Private voidForm1_mousedown (Objectsender, MouseEventArgs e) { //Record start point This. MouseDown =true; This. StartPoint =e.location; } Private voidForm1_mousemove (Objectsender, MouseEventArgs e) { //record the end point. Drawing to the window if(MouseDown) { This. Endpoint =e.location; This. Refresh (); Gform. DrawImage ( This. Bmsave,NewPoint (0,0)); Rectangle rect=NewRectangle (); This. Rect_play (refrect); Gform. DrawRectangle (NewPen (Color.Black), rect); } } Private voidForm1_mouseup (Objectsender, MouseEventArgs e) { //record the end point. Draw to bitmap This. Endpoint =e.location; This. MouseDown =false; Rectangle rect=NewRectangle (); This. Rect_play (refrect); G.drawrectangle (NewPen (Color.Black), rect); Gform. DrawImage ( This. Bmsave,NewPoint (0,0)); }
Determine the rectangle location and width,heigth to draw according to StartPoint and endpoint two points
Private voidRect_play (refRectangle Rect) { //determines the upper-left corner of the rectangle based on two points location if( This. StartPoint. X > This. Endpoint. X && This. StartPoint. Y < This. Endpoint. Y) {rect. Location=NewPoint ( This. Endpoint. X This. StartPoint. Y); } Else if( This. StartPoint. X < This. Endpoint. X && This. StartPoint. Y > This. Endpoint. Y) {rect. Location=NewPoint ( This. StartPoint. X This. Endpoint. Y); } Else if( This. StartPoint. X > This. Endpoint. X && This. StartPoint. Y > This. Endpoint. Y) {rect. Location= This. Endpoint; } Else{rect. Location= This. StartPoint; } //get the X, y distance of two pointsRect. Width = Math.Abs ( This. StartPoint. X This. Endpoint. X); Rect. Height= Math.Abs ( This. StartPoint. Y This. Endpoint. Y); if(Rect. Width = =0&& rect. Height = =0) { //prevent the drawing when it is delayed } Else if(Rect. Width = =0) {rect. Width=1; } Else if(Rect. Height = =0) {rect. Height=1; } }
Full instance Code link: Http://pan.baidu.com/s/1sjkpic1
The window flash when the painting is particularly powerful, because a lot of refresh and draw, open double buffering does not play much role
Late Time with QT C + + to do one, QT written should not blink
Draw a rectangle on a C # form