c#在面板内拖动PictureBox

时间:2018-10-31 00:19:34

标签: c# limit draggable drag restrict

我有一个可拖动此图片的PictureBox1:

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            x = e.X;
            y = e.Y;
        }
    }

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {

        if (e.Button == MouseButtons.Left)
        {
            if (pictureBox1.Left + pictureBox1.Width> panel1.Width)
                pictureBox1.Left += (e.X - x);
        }
    }

但是我不能受到限制, 我只想将图片移动到面板内,如下所示: Example

有什么想法吗? 谢谢

1 个答案:

答案 0 :(得分:0)

尝试一下:

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        int left = 0;
        if (pictureBox1.Left >= 0 && pictureBox1.Right <= panel1.Width)
            left = pictureBox1.Left + (e.X - x);

        left = Math.Min(panel1.Width - pictureBox1.Width , left);
        left = Math.Max(0, left);
        pictureBox1.Left = left;
    }
}