Draw a Rectangle in C# using Mouse

Draw a Rectange in C# using Mouse

This tutorial will show you how to draw a 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 down to the bottom of this post.

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

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

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

Now we will use the MouseMove event to capture the position of the cursor as it moves and use it to set the width and height of the rect variable.

So far we have only captured the dimensions for the rectangle. We will now use it to actually draw the rectangle. We will use the Paint event for that.

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.

Leave a Reply

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