This Blog is Mainly intended to Draw a rectangle or Square at Runtime using the MouseDown, MouseUp, MouseMove and the Paint Events of the Form. The User can draw a Rectangle at runtime to what ever size rectangle he can want to draw. So, finally a rectangle Object from the Rectangle class will be resultant using which the user can make the remaining actions.
bool canResize;
int mX, mY;
Rectangle rect = new Rectangle();
RectangleShape[] rec = new RectangleShape[20];
RectangleShape TempRec;
int RecCount = 0;
public Form2()
{
InitializeComponent();
}
private void Form2_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(new Pen(Brushes.Purple, 2), rect);
}
private void Form2_MouseDown(object sender, MouseEventArgs e)
{
canResize = true;
mX = e.X; mY = e.Y;
rect.Location = new Point(mX, mY);
}
private void Form2_MouseUp(object sender, MouseEventArgs e)
{
canResize = false;
button1.Enabled = true;
}
private void Form2_MouseMove(object sender, MouseEventArgs e)
{
if (canResize)
{
if (mX < e.X)
{
rect.X = mX;
rect.Width = e.X - mX;
}
else
{
rect.X = e.X;
rect.Width = mX - e.X;
}
if (mY < e.Y)
{
rect.Y = mY;
rect.Height = e.Y - mY;
}
else
{
rect.Y = e.Y;
rect.Height = mY - e.Y;
}
this.Invalidate();
}
}