C # Drawing a Rectangle on a mouse event

I want to draw a rectangle. What I want is to show the user a rectangle on the mouse event. enter image description here

As in the image. This is for a C # .net Forms application.

Help me achieve this. Any help is appreciated.

Thanks yoan

+4
source share
3 answers

You can do this in three steps:

  • First check if the mouse is down.
  • If this happens, then at the mouse move event, continue to initialize the rectangle with new positions when the mouse is dragged.
  • Then draw a rectangle in the drawing event. (It will be raised for almost every mouse event, depending on the refresh rate of the mouse and dpi).

You can do something like this (in Form ):

 public class Form1 { Rectangle mRect; public Form1() { InitializeComponents(); //Improves prformance and reduces flickering this.DoubleBuffered = true; } //Initiate rectangle with mouse down event protected override void OnMouseDown(MouseEventArgs e) { mRect = new Rectangle(eX, eY, 0, 0); this.Invalidate(); } //check if mouse is down and being draged, then draw rectangle protected override void OnMouseMove(MouseEventArgs e) { if( e.Button == MouseButtons.Left) { mRect = new Rectangle(mRect.Left, mRect.Top, eX - mRect.Left, eY - mRect.Top); this.Invalidate(); } } //draw the rectangle on paint event protected override void OnPaint(PaintEventArgs e) { //Draw a rectangle with 2pixel wide line using(Pen pen = new Pen(Color.Red, 2)) { e.Graphics.DrawRectangle(pen, mRect); } } } 

later, if you want to check whether the buttons (shown on the diagram) are in the rectangle or not, you can do this by checking the Button area and check if they are in the drawn rectangle.

+5
source

The Shekhar_Pro solution draws a rectangle in only one direction (from top to bottom, from left to right), if you want to draw a rectangle regardless of mouse position and direction of movement, the solution:

 Point selPoint; Rectangle mRect; void OnMouseDown(object sender, MouseEventArgs e) { selPoint = e.Location; // add it to AutoScrollPosition if your control is scrollable } void OnMouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Point p = e.Location; int x = Math.Min(selPoint.X, pX) int y = Math.Min(selPoint.Y, pY) int w = Math.Abs(pX - selPoint.X); int h = Math.Abs(pY - selPoint.Y); mRect = new Rectangle(x, y, w, h); this.Invalidate(); } } void OnPaint(object sender, PaintEventArgs e) { e.Graphics.DrawRectangle(Pens.Blue, mRect); } 
+3
source

These blue rectangles are very similar to controls. Drawing a string on top of a control is difficult to do in Winforms. You must create a transparent window that overlays the design surface and draws a rectangle in this window. It also works as a Winforms designer. Sample code here .

+2
source

Source: https://habr.com/ru/post/1341765/


All Articles