C# - 将控件移动到鼠标位置

3

我试图让控件在用户单击并拖动控件时跟随光标移动。问题是:1)控件没有到达鼠标的位置,2)控件闪烁并飞来飞去。我尝试了几种不同的方法,但迄今为止都失败了。

我尝试过:

protected override void OnMouseDown(MouseEventArgs e)
{
     while (e.Button == System.Windows.Forms.MouseButtons.Left)
     {
          this.Location = e.Location;
     }
}

并且

protected override void OnMouseMove(MouseEventArgs e)
{
     while (e.Button == System.Windows.Forms.MouseButtons.Left)
     {
          this.Location = e.Location;
      }
}

但是这两种方法都不起作用。非常感谢您的帮助,提前致谢!
4个回答

10

以下是实现方法:

private Point _Offset = Point.Empty;

protected override void MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        _Offset = new Point(e.X, e.Y);
    }
}

protected override void MouseMove(object sender, MouseEventArgs e)
{
    if (_Offset != Point.Empty)
    {
        Point newlocation = this.Location;
        newlocation.X += e.X - _Offset.X;
        newlocation.Y += e.Y - _Offset.Y;
        this.Location = newlocation; 
    }
}

protected override void MouseUp(object sender, MouseEventArgs e)
{
    _Offset = Point.Empty;
}

_Offset 在这里有两个作用:一是跟踪鼠标在初始点击控件时的位置,二是跟踪鼠标按钮是否按下(以便当鼠标光标经过控件并且按钮没有按下时,控件不会被拖动)。

在这段代码中绝对不要将if换成while,否则会有所不同。


我已经尝试过,但并没有什么改变。不过还是非常感谢你的努力。 - Adam P
3
+1:MusiGenesis的代码对我非常有效,只做了一些修改:我创建了一个新的用户控件 -> 覆盖了三个方法OnMouseDown,OnMouseUp和OnMouseMove -> 这些方法中的第一行都调用了基础方法,即base.OnMouseDown(e),base.OnMouseMove(e)和base.OnMouseUp(e) -> 其余代码按照MusiGenesis的讨论进行。 - Sameh Deabes
1
非常感谢!这个新答案非常好用!我真的很感激! - Adam P

2

答案1中存在错误: 1.将鼠标处理程序设置为控件而不是表单,例如button1_MouseMove。 2.不要使用this向量,而是使用您的控件代替(Point newlocation = button1.Location)。 3.您不需要重写处理程序。

在我的测试中,经过这些更改后,按钮(或其他控件)移动得很好。

Chigook


1
尝试使用以下代码通过鼠标位置移动对象,并收集鼠标移动路径和存储在ArrayList中的位置,以获取鼠标指针移动的路径。您需要全局声明ArrayList。
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        ArrayList inList = new ArrayList();
        inList.Add(e.X);
        inList.Add(e.Y);
        list.Add(inList);
    }
}

当用户点击按钮时,控件必须沿着用户在屏幕上拖动的路径移动。
private void button1_Click_2(object sender, EventArgs e)
{
    foreach (ArrayList li in list)
    {
        pic_trans.Visible = true;
        pic_trans.Location = new Point(Convert.ToInt32(li[0]), Convert.ToInt32(li[1]));
        pic_trans.Show();
    }
}

0
private Point ptMouseDown=new Point();

protected override void MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        ptMouseDown = new Point(e.X, e.Y);
    }
}

protected override void MouseMove(object sender, MouseEventArgs e)
{
    if (_Offset != Point.Empty)
    {
        Pointf[] ptArr=new Pointf[]{this.Location};
        Point Diff=new Point(e.X-ptMouseDown.X,e.Y-ptMouseDown.Y);
        Matrix mat=new Matrix();
        mat.Translate(Diff.X,Diff.Y);
        mat.TransFromPoints(ptArr);
        this.Location=ptArr[0];
    }
}   

protected override void MouseUp(object sender, MouseEventArgs e)
{
    _Offset = Point.Empty;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接