0

I have a PictureBox1 draggable with this code:

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

But I can't get bound restrictions, I just want move the Picture inside a Panel, like this: Example

Any ideas? Thanks

1 Answers1

0

Try this:

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;
    }
}
roozbeh S
  • 1,084
  • 1
  • 9
  • 16