如何通过鼠标在Panel中移动pictureBox

时间:2017-11-09 02:39:39

标签: c# picturebox mousemove mousedown

如何通过鼠标在Panel中移动pictureBox。 Visual Studio 2015 C#Winsows Forms Application。

我制作了一个原始滑块来控制WindowsMediaPlayer的音量。 一个面板作为背景,一个pictureBox作为slider-knopf。 它运作良好。 但纯粹在视觉上它并没有那么好用。

我四处寻找,但我无法找到这个有趣的小问题的答案。

这是我的代码:

    int posY;

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

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        PictureBox box = sender as PictureBox;

        if (e.Button == MouseButtons.Left)
        {
            box.Top += e.Y - posY;
        }

        if (box.Top < 0)
        {
            box.Top = 0;
        }

        if (box.Top > 100)
        {
            box.Top = 100;
        }
        int n = box.Top;
        n = n * - 1 + 100;
        label1.Text = n.ToString();
    }

当我将pictureBox从小面板的边缘移出时,pictureBox在面板中以某种方式“收缩”。 但是当我释放鼠标时,pictureBox恢复了它的大小。

Slider.gif

为什么会这样。? 我怎么能避免它。?

感谢。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。 它不是最佳的,但它可以使用。 我将代码更改为:

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            dragging = true;
            startPoint = e.Location;
        }
    }


    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (dragging)
        {
            Debug.WriteLine("mousemove X: " + e.X + " Y: " + e.Y);
            pictureBox1.Location = new Point(0, pictureBox1.Top + e.Location.Y - startPoint.Y);

            if (pictureBox1.Location.Y < 0)
            {
                pictureBox1.Location = new Point(0, 0);
                dragging = false;
            }
            if (pictureBox1.Location.Y > 100)
            {
                pictureBox1.Location = new Point(0, 100);
                dragging = false;
            }
            this.Refresh();
        }
        int n = pictureBox1.Location.Y;
        n = n * -1 + 100;
        label1.Text = n.ToString();

        mediaPlayer1.settings.volume = n;
    }


    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        dragging = false;
    }

gif

当pictureBox1被拉出面板时,我仍然需要设置'if'来纠正。 为了避免闪烁,我不得不放一个'拖动=假'。 但是,它导致pictureBox1被冻结到边缘,所以我必须释放鼠标,然后重新点击继续。

但是很好 - 这就是生活。

感谢。