How to move PictureBox in C#?

空扰寡人 提交于 2019-12-06 06:16:01

问题


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


回答1:


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.




回答2:


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;
    }
}



回答3:


Try to change SizeMode property from AutoSize to Normal



来源:https://stackoverflow.com/questions/9805598/how-to-move-picturebox-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!