如何在C#中移动PictureBox?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9805598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:57:37  来源:igfitidea点击:

How to move PictureBox in C#?

c#.netwinformspicturebox

提问by SHiv

i have used this code to move picture box on the pictureBox_MouseMoveevent

我已使用此代码在pictureBox_MouseMove事件上移动图片框

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

但是当我尝试执行图片框闪烁并且无法识别确切位置时。你们能帮我吗。我要画框稳...

回答by Dor Cohen

Try to change SizeModeproperty from AutoSizeto Normal

尝试将SizeMode属性从更改AutoSizeNormal

回答by Hans Passant

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 notupdate the mousePos variable in MouseMove. Necessary since moving the control changes the relative position of the mouse cursor.

请注意,此代码并没有更新的MouseMove的mousePos结构变量。由于移动控件会改变鼠标光标的相对位置,因此很有必要。

回答by Olivier Jacot-Descombes

You have to do several things

你必须做几件事

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

  2. In MouseMovesee 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.

  1. 注册移动操作MouseDown的开始并记住鼠标的开始位置。

  2. MouseMove看看你是否真的在移动图片。移动时保持与图片框左上角相同的偏移量,即移动时,鼠标指针应始终指向图片框内的同一点。这使得图片框与鼠标指针一起移动。

  3. 在 中注册移动操作的结束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;
    }
}