Share via


C# Moving a picturebox

Question

Thursday, July 26, 2012 11:57 AM

Hi there,

I have a slight problem, I want to add pictures to my form and allow the user to move them as he pleases…

So I don’t know if I should write this whole thing in code or put a lot of picture boxes on my form and every time he adds a new picture, I just write code so that it select a the next picture box…. (I’ll try and figure this part out later)

My actual question is, how do I allow the user to move the picture box as he pleases via mouse click and drag it, I looked at the properties but can’t find anything there so is it a code I should write or a property that I missed?

All replies (4)

Thursday, July 26, 2012 12:48 PM ✅Answered | 1 vote

Do you want to move the whole control of pictureBox?

For example you place an image into the pictureBox, then by a mouse click on it, you want to move to the position where mouse left click will be dropped (unclicked)? By using 

Ofr did you have any thing else in mind?

Here is the code of my explanation:

    public partial class Form1 : Form
    {
        Point location = Point.Empty;
        public Form1()
        {
            InitializeComponent();
            pictureBox1.Image = new Bitmap(@"C:\1\backward.png");
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                location = new Point(e.X, e.Y);
            }
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (location != Point.Empty)
            {
                Point newlocation = this.pictureBox1.Location;
                newlocation.X += e.X - location.X;
                newlocation.Y += e.Y - location.Y;
                this.pictureBox1.Location = newlocation;
            }
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            location = Point.Empty;
        }
    }

Hope it helps.

bye

Mitja


Thursday, July 26, 2012 1:19 PM

Exactly what I wanted!

You’re the Best!

Thank you so much!!!


Thursday, July 26, 2012 1:21 PM

:) anytime mate

Mitja


Thursday, July 26, 2012 2:20 PM

The code posted by Mitia sometimes can't keep up with the mouse if the mouse is moved rapidly.  The following general code for moving a control is usually more reliable:

class MovablePictureBox : PictureBox  {    protected override void OnMouseDown(MouseEventArgs e)    {      base.OnMouseDown(e);      if (e.Button == MouseButtons.Left)      {        this.Capture = false;        Message msg = Message.Create(this.Handle, 0XA1, new IntPtr(2), IntPtr.Zero);        this.WndProc(ref msg);      }    }  }

This code can be used to move the control's parent by changing "this.Handle" to "Parent.Handle".