Drawing a shape and moving it by mouse (using C#.Net)


Suppose we have an image or a shape drawn on a Picturebox control on a Windows Form. And we wanted to move the shape or image by mouse. The code is very quick to implement using C#.Net.

  1.  Create a new Windows Form project
  2. Insert a picturebox onto the form
  3. Add Paint, MouseDown, MouseMove, and MouseUp event handlers for the picturebox
  4. Create a rectangle object
  5. Create a boolean object to check whether the mouse button is held down (so that the shape moves when we click and drag it around)
  6. Draw the rectangle inside the Paint() event hander
  7. Inside the other event handlers, if the mouse button is clicked down, then isMouseDown = true. If this condition is true, then make the rectangle’s location follow the mouse location. Also we dont want to have our shape be dragged out of the picturebox bounds so we add some conditions. Finally, you need to call Refresh(). In MouseUp, since we’re not holding the mouse button down anymore, then isMouseDown = false.
public partial class Form1 : Form
    {
        Rectangle rect = new Rectangle(125, 125, 50, 50);
        bool isMouseDown = false;
        public Form1()
        {
            InitializeComponent();
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.FillRectangle(new SolidBrush(Color.RoyalBlue), rect);
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            isMouseDown = true;
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (isMouseDown == true)
            {
                rect.Location = e.Location;

                if (rect.Right > pictureBox1.Width)
                {
                    rect.X = pictureBox1.Width - rect.Width;
                }
                if (rect.Top < 0)
                {
                    rect.Y = 0;
                }
                if (rect.Left < 0 )
                {
                    rect.X =  0;
                }
                if (rect.Bottom > pictureBox1.Height)
                {
                    rect.Y = pictureBox1.Height - rect.Height;
                }
                Refresh();
            }
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            isMouseDown = false;
        }
    }