Moving a control by dragging it with the mouse in C#

Paul Ghiran picture Paul Ghiran · May 5, 2013 · Viewed 60.9k times · Source

I'm trying to move the control named pictureBox1 by dragging it around. The problem is, when it moves, it keeps moving from a location to another location around the mouse, but it does follow it... This is my code. and I would really appreciate it if you could help me

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    bool selected = false;
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        selected = true;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (selected == true)
        {
            pictureBox1.Location = e.Location;
        }
    }

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

}

Answer

astef picture astef · May 5, 2013

All you need:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }


    private Point MouseDownLocation;


    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            MouseDownLocation = e.Location;
        }
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            pictureBox1.Left = e.X + pictureBox1.Left - MouseDownLocation.X;
            pictureBox1.Top = e.Y + pictureBox1.Top - MouseDownLocation.Y;
        }
    }

}