Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move PictureBox in C#?

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...

like image 377
SHiv Avatar asked Jan 17 '23 03:01

SHiv


2 Answers

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.

like image 72
Hans Passant Avatar answered Jan 25 '23 11:01

Hans Passant


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;
    }
}
like image 24
Olivier Jacot-Descombes Avatar answered Jan 25 '23 10:01

Olivier Jacot-Descombes