Draw a Rectange in C# using Mouse

This tutorial will show you how to draw rectangle in C# using Mouse. You can normally draw a rectangle by putting the values manually. But that doesn’t always work. Sometimes you’ll require the rectangle to be drawn automatically (without putting values manually). This tutorial will show you how to do that. Let’s begin:

P.S: The source code for this tutorial is available for download. Scroll to the bottom of this post.

It is very simple and it isn’t as hard as it sounds.

First of all, declare the variable “rect”. Declaring it outside all the methods will let us access at anywhere in the current form.

Rectangle rect;

// Optional
public Form1()
{
   InitializeComponent();
   // Use the cross "+" cursor
   this.Cursor = System.Windows.Forms.Cursors.Cross;
   // This will reduce flicker (Recommended)
   this.DoubleBuffered = true;
}

Now add MouseDown event to your form and use the following code:

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
   // "e.X" and "e.Y" are used to get MousePositionX and MousePositionY
   rect = new Rectangle(e.X, e.Y, 0, 0);
   this.Invalidate();
}

The above code sets the X-coordinate and Y-coordinate of the upper-left corner of the rectangle.

Okay. Now add the MouseMove event to the form and use this code:

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
   // This makes sure that the left mouse button is pressed.
   if (e.Button == MouseButtons.Left)
   {
       // Draws the rectangle as the mouse moves
       rect = new Rectangle(rect.Left, rect.Top, e.X - rect.Left, e.Y - rect.Top);
   }
   this.Invalidate();
}

Almost done! Add the Paint event to your form and use this code:

private void Form1_Paint(object sender, PaintEventArgs e)
{
   // Replace "Color.Red" with any color and repalce "2" with any size you like.
   using (Pen pen = new Pen(Color.Red, 2))
   {
      e.Graphics.DrawRectangle(pen, rect);
   }
}

That’s it! We are done.

The source code is available for download:

Download Source Code

If you have any questions please don’t hesitate to post a comment.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • DZone
  • Reddit
  • Yahoo! Buzz
  • StumbleUpon
  • LinkedIn
  • Twitter