4

i have used this code to move picture box on the pictureBox_MouseMove event

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

but when i try to execute the picture box flickers and the exact position cannot be identified. can you guys help me with it. I want the picture box to be steady...

abatishchev
  • 98,240
  • 88
  • 296
  • 433
SHiv
  • 264
  • 4
  • 10
  • 22
  • 1
    Concerning the flickering: I'm not certain, but perhaps [double buffering](http://msdn.microsoft.com/en-us/library/b367a457.aspx "'Double Buffered Graphics' on MSDN") could help in this case. – stakx - no longer contributing Jul 20 '12 at 15:55

3 Answers3

5

You want to move the control by the amount that the mouse moved:

    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 = e.X - mousePos.X;
            int dy = e.Y - 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 since moving the control changes the relative position of the mouse cursor.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • ,@Dor,@olivier i had tried your ideas but during MouseMove event the picture box is splitted into 4 boxes help with some idea. – SHiv Mar 22 '12 at 06:59
4

You have to do several things

  1. Register the start of the moving operation in MouseDown and remember the start location of the mouse.

  2. In MouseMove see if you are actually moving the picture. Move by keeping the same offset to the upper left corner of the picture box, i.e. while moving, the mouse pointer should always point to the same point inside the picture box. This makes the picture box move together with the mouse pointer.

  3. Register the end of the moving operation in 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;
    }
}
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
0

Try to change SizeMode property from AutoSize to Normal

Dor Cohen
  • 16,769
  • 23
  • 93
  • 161