【问题标题】:How to move a pictureBox inside a Panel by Mouse如何通过鼠标在面板内移动图片框
【发布时间】:2017-11-09 02:39:38
【问题描述】:

如何通过鼠标在面板内移动图片框。 Visual Studio 2015 C# Winsows 表单应用程序。

我制作了一个原始滑块来控制我的 WindowsMediaPlayer 的音量。 一个面板作为背景,内部的一个图片框作为滑块旋钮。 而且效果很好。 但纯粹在视觉上它并没有那么好。

我已经四处搜索,但我找不到这个有趣的小问题的答案。

这是我的代码:

    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 恢复了它的大小。

Slider.gif

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

谢谢。

【问题讨论】:

    标签: c# picturebox mousemove mousedown


    【解决方案1】:

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

        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' 来纠正。 并且为了避免闪烁,我不得不放一个'dragging = false'。 但是,它导致pictureBox1被冻结到边缘,所以我必须松开鼠标,然后重新单击才能继续。

    但是很好 - 它可以忍受。

    谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-08
      • 1970-01-01
      • 2010-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多