【问题标题】:Dragging an item vertically, Y position not working垂直拖动项目,Y 位置不起作用
【发布时间】:2012-01-26 20:53:45
【问题描述】:

我有一个显示音符图像的图片框。我希望能够根据放下位置的相应 Y 位置在包含它的面板内上下拖动音高时更改音高的值。使用下面的代码,音高确实发生了变化,但似乎 Y 值只是随机的,当它应该上升时,我拖动越高,向下拖动越低。

private void StartDrag(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isDragging = true;
                pitch = e.Y;
                this.Location = new Point(this.Location.X, pitch);
            }

        }

        private void StopDrag(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isDragging = false;
                pitch = e.Y;
            }

        }

        private void NoteDrag(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (isDragging)
            {
                this.Top = this.Top + (e.Y - this.pitch); //move in Vertical direction
            }
        }

【问题讨论】:

  • 你不能为此设置一个滑块吗?
  • 我不熟悉滑块,因为我是 C# 新手。每个音符是否有可能有自己的滑块?在程序中可以添加多个注释
  • 这些拖拽音符的问题本周无休无止。一定是某种家庭作业。
  • 设置滑块样式可能是对 web/WPF/Silverlight 控件的引用。如果您不限于 winforms,这听起来很适合 WPF 或 Silverlight。这种交互会更简单。

标签: c# winforms drag-and-drop panel picturebox


【解决方案1】:

当您更改控件的位置时(通过修改this.Top),使用MouseEventArgs 返回的鼠标坐标也会更改。不要使用e 参数,您应该使用Cursor.Position 来获取绝对(屏幕)坐标,然后使用您的父级PointToClient 方法转换它们控制。这样,您的坐标将与控件的位置无关。

为了更好地了解会发生什么,在执行所有这些操作之前,在表单中添加两个标签,并在 NoteDrag 方法中添加类似这样的内容:

// show relative coordinate 
this.label1.Text = e.Y.ToString();

// show absolute coordinate 
this.label2.Text = Cursor.Position.Y.ToString();

【讨论】:

  • 我接受了,因为它真的帮助我理解了发生了什么,非常感谢!
猜你喜欢
  • 2015-09-26
  • 1970-01-01
  • 2012-06-21
  • 2017-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多