-3

i got the picture box to move. But when i click down on the picture box it jumps all over the place. Can anyone help me with this at all?

namespace Move_Shapes
{
    public partial class Form1 : Form
    {
        int X = 0;
        int Y = 0;
        int mX = 0;
        int mY = 0;
        bool Move = false;

        public Form1()
        {
            InitializeComponent();
        }

        private void pic_TL_Click(object sender, EventArgs e)
        {
            //X = MousePosition.X - this.Location.X - 8 - pic_TL.Location.X; // loc of cursor in picture
            //Y = MousePosition.Y - this.Location.Y - 30 - pic_TL.Location.Y;

            //label1.Text = X.ToString();
            //label2.Text = Y.ToString();

            //X = MousePosition.X - this.Location.X - 8;
            //Y = MousePosition.Y - this.Location.Y - 30;

            //label3.Text = X.ToString();
            //label4.Text = Y.ToString();
        }

        private void pic_TL_MouseDown(object sender, MouseEventArgs e)
        {
            X = MousePosition.X - this.Location.X - 8 - pic_TL.Location.X; // loc of cursor in picture
            Y = MousePosition.Y - this.Location.Y - 30 - pic_TL.Location.Y;

            label1.Text = X.ToString();
            label2.Text = Y.ToString();
            Move = true;
        }

        private void pic_TL_MouseMove(object sender, MouseEventArgs e)
        {
            mX = MousePosition.X - this.Location.X - 8 - pic_TL.Location.X; // loc of cursor in picture
            mY = MousePosition.Y - this.Location.Y - 30 - pic_TL.Location.Y;

            if (Move)
            {
                pic_TL.Location = new Point(mX - X, mY - Y);
            }

        }

        private void pic_TL_MouseUp(object sender, MouseEventArgs e)
        {
            Move = false;
        }
    }
}
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • 1
    Please revise your title to explain your *issue* not your general situation. – O. R. Mapper May 21 '14 at 10:04
  • pretty new to this, but basically what is happening when i click down on the mouse it the picturebox jumps back and fourth and am not sure why – user3635818 May 21 '14 at 10:08
  • What are those magic constants: 8, 30? – ad1Dima May 21 '14 at 10:11
  • the distance of left side of the form and the height at the top of the form – user3635818 May 21 '14 at 10:15
  • 1
    It *jumps* because formulas are wrong. Basically, remember mouse position in `MouseDown` event (btw, take it from `e`, not from `MousePosition`) and in `MouseMove` event change location: `pic_TL.X += oldMouseX - e.X`, same for `Y`. – Sinatr May 21 '14 at 10:19

1 Answers1

0

On MoseMove you set location to difference of current mouse position and initial mouse position.

pic_TL.Location = new Point(mX - X, mY - Y);

I case mouse moved over one pixel, picture will move to left-top corner.

ad1Dima
  • 3,185
  • 2
  • 26
  • 37