How to move PictureBox in C #?

I used this code to move the picture window in the event pictureBox_MouseMove

 pictureBox.Location = new System.Drawing.Point(e.Location); 

but when I try to flicker the image flag, the exact location cannot be identified. Can you guys help me with this. I want the image box to be stable ...

+4
source share
3 answers

You want to move the control by the amount of mouse movement:

  Point mousePos; private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { mousePos = e.Location; } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { int dx = eX - mousePos.X; int dy = eY - mousePos.Y; pictureBox1.Location = new Point(pictureBox1.Left + dx, pictureBox1.Top + dy); } } 

Note that this code does not update the mousePos variable in MouseMove. Necessary because moving the control changes the relative position of the mouse cursor.

+5
source

You need to do a few things

  • Register the start of the move operation in MouseDown and remember the initial location of the mouse.

  • In MouseMove see if you are really moving the image. Moving while maintaining the same offset in the upper left corner of the image window, that is, while moving, the mouse pointer should always point to the same point inside the image field. This causes the image field to move with the mouse pointer.

  • Register the end of the move operation with MouseUp .

 private bool _moving; private Point _startLocation; private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { _moving = true; _startLocation = e.Location; } private void pictureBox1_MouseUp(object sender, MouseEventArgs e) { _moving = false; } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (_moving) { pictureBox1.Left += e.Location.X - _startLocation.X; pictureBox1.Top += e.Location.Y - _startLocation.Y; } } 
+3
source

Try changing the SizeMode property from AutoSize to Normal

0
source

Source: https://habr.com/ru/post/1402652/


All Articles