Is there any way to draw Rectangle with starting and ending points instead of starting point and area?. I am using the following code, to draw rectangle on form via mouse:
System.Drawing.Graphics formGraphics;
bool isDown = false;
int initialX;
int initialY;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
isDown = true;
initialX = e.X;
initialY = e.Y;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (isDown == true)
{
this.Refresh();
Pen drwaPen = new Pen(Color.Navy,1);
int width = e.X - initialX, height = e.Y - initialY;
//if (Math.Sign (width) == -1) width = width
//Rectangle rect = new Rectangle(initialPt.X, initialPt.Y, Cursor.Position.X - initialPt.X, Cursor.Position.Y - initialPt.Y);
Rectangle rect = new Rectangle(initialX, initialY, width * Math.Sign(width), height * Math.Sign(height));
formGraphics = this.CreateGraphics();
formGraphics.DrawRectangle(drwaPen, rect);
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
isDown = false;
}
I can draw rectangle with this code, when I move mouse back from its starting point the rectangle should be flip, but instead of doing this my rectangle continues to draw in the opposite direction of the mouse cursor. In short this code works fine while drawing rectangle in forward direction but doesn’t work for backward direction.
As Jamiec has mentioned, just call
Invalidatein theMouseMovehandler, and do the drawing in theOnPaintmethod /Paintevent handlerTo draw the correct rectangle forwards or backwards, try this: