繁体   English   中英

如何通过鼠标在面板内移动pictureBox

[英]How to move a pictureBox inside a Panel by Mouse

如何通过鼠标在Panel中移动pictureBox。 Visual Studio 2015 C#Winsows表单应用程序。

我制作了一个基本的滑块来控制WindowsMediaPlayer的音量。 一个面板作为背景,一个pictureBox作为滑块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

这是为什么。? 我该如何避免呢?

谢谢。

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

    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被冻结到边缘,因此我必须释放鼠标,然后重新单击以继续。

但是-与它一起生活。

谢谢。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM