Draw a Rectangle in C# using Mouse

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.

30 thoughts on “Draw a Rectangle in C# using Mouse

  1. Pingback: Twitted by farooqaaa

  2. sathish

    This above source code works fine.

    I selected a text in the image by drawing a rectangle. How to capture(copy) and paste the selected text image…any idea…?

    regards
    M.Sathish Kumar

    Reply
  3. Farooq Azam Post author

    Hello Sathish,

    I can’t understand you. Can you be more specific?

    On which image did you draw the rectangle? And what are you trying to copy/paste?

    Thanks.

    Reply
  4. sathish

    Hi Farooz

    I loaded a tiff image (which contains some text) in a picture box and using the above code i can draw a rectangle over a particular text in the TIFF image.

    I want to convert that particular selected (via rectanlge) text image to bitmap image…can u pls help..?

    regards
    M.Sathish Kumar

    Reply
  5. sathish

    Farooz

    One more thing..

    iam initlally converting the tiff image to bitmap and then only loading in to picture box… actually i want read the rectangular selection area to send as a bitmap parameter to the MODI object (for OCR conversion).

    Thanks
    M.Sathish Kumar

    Reply
    1. Farooq Azam Post author

      Yea, you can quote it as long as you add a link to the original post. And yes, I have got a Twitter account.

      Reply
  6. Replica Rolex Watches

    Hey there I just wanted to say that I really enjoyed reading your blog but it’s taking a while to load up for me. I don’t have a slow internet connection either, so I think it may be your site? Or maybe there is just a lot of people trying to load up right now, either way I advise you look into it and also, keep up the nice blog posts.

    Reply
  7. deedee

    hi!
    Thank you so much ! You’re a life saver ! This is the only place where i could find a drawing example in which the mouse moves.

    Reply
  8. Aleks

    Unbelievable simple solution!!!
    Others’ solutions are way too stupid and complex.
    This one is brilliant.
    Thanks so much!!!

    Reply
  9. karthik

    Hi
    Here when u drag it from the top to the bottom the rectangle is drawn but when the mouse is dragged from the bottom to top rectangle is not drawn .Is There any Function i have to use to avoid this ?
    Help me.

    Thanks ,
    Karthik

    Reply
  10. yogesh

    I wanna draw Ellipse in Richtextbox at Button_Click event using Mouse But I could not?
    help me how can i make this using C#

    Reply
  11. anonymous

    Hi Farooq,
    Thank you so much! I’ve been searching for hours on end, on a good tutorial related with drawing shapes on mouse move. This solves all of my problems.. Thanks again…

    Reply
  12. raghu

    hi ,

    Your article was really nice .When iam using that in my program to draw a similar rectangle i could get it at runtime.

    To be specific i am having a bitmap image where i need to locate few points based on the values given on the border of the image.there fore i require a rectangle,by which i can make sure i am pointing on correct pixels to match the values on the border.so the third part i.e paint is not working properly for me.i need it to work this way ‘ when we drag mouse on the desktop screen we get a erasable rectangle to select some part ‘.If you can provide some assistance i will be really grateful to you!!

    Reply
  13. Emad

    Hi Farooq,
    This is a superb article really, its simple and elegant and took no time to make it work. I used this in a small utility for capturing the portrait image on customer forms.

    Reply
  14. Jim P

    It’s a nice tutorial but the problem with all the tutorial’s I’ve seen is that you can only draw images one time and they are lost if you call Paint for a new rectangle. What if I want to be able to draw many rectangles using this mouse code with out loosing the previous rectangle? Do I have to keep track of each one and repaint all of them each time I add a new rectangle? Seems very inefficient when drawing lots of objects.

    Reply
  15. navdeep singh

    hi i want to make two an application that will draw two shape using mouse
    after click on specific button .. please tell me how to do that… in c#

    Reply
  16. Steve

    I’m doing something very similar but finding that the Paint handler doesn’t get called until I release the left mouse button, meaning I can’t see the rectangle until I’m through drawing it. Any Ideas?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>