Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Topics

Recent Status Updates

View All Updates

- - - - -

C# Tutorial - Drawing rectangles with the mouse

csharp c c# drawing rectangle rectangles drawing with mouse graphics tutorial c# tutorial

  • Please log in to reply
No replies to this topic

#1 DeadLine


    CC Regular

  • Member
  • PipPipPip
  • 41 posts
  • Location:Belgium
  • Programming Language:Java, C#, PHP, (Visual) Basic, JavaScript, PL/SQL, Delphi/Object Pascal, Visual Basic .NET, Pascal, VBScript
  • Learning:C++, JavaScript, Delphi/Object Pascal, Pascal

Posted 06 June 2014 - 01:02 PM



In this small tutorial I will teach you how you can draw a simple rectangle on your form with the mouse. The rectangle will be drawn dynamically as soon as the user presses any mouse button. This also means that if you move your mouse while pressing any of the mouse buttons, the rectangle will either get larger or smaller depending on which direction you moved your mouse to.




Step 1:


We will be using a simple Windows Forms Application for this tutorial. The first thing you will need to do, is start a new project:




Step 2:


Right now, it's time to edit the design of the form a bit. Change the following properties:

  • Optional: [Backcolor : ActiveCaption]
  • DoubleBuffered : True
  • Optional: [FormBorderStyle : None]
  • Optional: [Opacity : 50% | (0.5 if you're doing it manually)]
  • Optional: [WindowState : Maximized]

DoubleBuffered will have to be set to true, to reduce or prevent flicker.


Step 3:


We will be 'using' the following references in our code:

using System;
using System.Drawing;
using System.Windows.Forms;

To keep track of wheter the user pressed a mouse button or not, we will need to add a variable to the code. We will also have to keep track of the start X and start Y position of the mouse. Add the following variables to our class:

private bool _canDraw;
private int _startX, _startY;

Now, it's time to add an event handler for the MouseDown event. You can find a list of all events in the Form Properties window:



Double click on this event and Visual Studio will generate an empty event handler for the MouseDown event. When any of the mouse buttons have been pressed, we want the system to know that it can now draw a rectangle and we also want to know the start position of the mouse. You can do all of this, by using the following code:

        private void Form1_MouseDown(object sender, MouseEventArgs e)
            //The system is now allowed to draw rectangles
            _canDraw = true;
            //Initialize and keep track of the start position
            _startX = e.X;
            _startY = e.Y;

We will also want the system to know when it is no longer allowed to draw rectangles. Since this should only happen when the mouse button has been released, we will be using the MouseUp event. Go back to the Designer and add the MouseUp event:



All this event handler has to do, is set the _canDraw variable to false:

        private void Form1_MouseUp(object sender, MouseEventArgs e)
            //The system is no longer allowed to draw rectangles
            _canDraw = false;

We will need to add a Rectangle variable to the class:

private Rectangle _rect;

We want the system to draw the rectangle when a mouse button is down and when the user moves his or her mouse. To do this, we will need to add an event handler for the MouseMove event:



In the MouseMove event handler, we will want to initialize the _Rect variable and give it the correct values for x, y, width and height:

        private void Form1_MouseMove(object sender, MouseEventArgs e)
            //If we are not allowed to draw, simply return and disregard the rest of the code
            if (!_canDraw) return;

            //The x-value of our rectangle should be the minimum between the start x-value and the current x-position
            int x = Math.Min(_startX, e.X);
            //The y-value of our rectangle should also be the minimum between the start y-value and current y-value
            int y = Math.Min(_startY, e.Y);

            //The width of our rectangle should be the maximum between the start x-position and current x-position minus
            //the minimum of start x-position and current x-position
            int width = Math.Max(_startX, e.X) - Math.Min(_startX, e.X);

            //For the hight value, it's basically the same thing as above, but now with the y-values:
            int height = Math.Max(_startY, e.Y) - Math.Min(_startY, e.Y);
            _rect = new Rectangle(x, y, width, height);
            //Refresh the form and draw the rectangle

With the code we have so far, we won't be able to actually draw the rectangle yet. We will need to override the OnPaint event in order to draw the rectangle. That is why we use 'Refresh();' in the code above. The OnPaint handler should look like this:

        protected override void OnPaint(PaintEventArgs e)
            //Create a new 'pen' to draw our rectangle with, give it the color red and a width of 2
            using (Pen pen = new Pen(Color.Red, 2))
                //Draw the rectangle on our form with the pen
                e.Graphics.DrawRectangle(pen, _rect);

Step 4:


Now it's time to spam the F5 key and actually test your code !


Attached Files

  • 0

Also tagged with one or more of these keywords: csharp, c, c#, drawing, rectangle, rectangles, drawing with mouse, graphics, tutorial, c# tutorial

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download