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); }
source share