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

4 回答 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将此代码中的 s切换为whiles,因为它有所作为。

于 2010-04-24T04:05:47.950 回答
2

答案有错误1 1.设置鼠标处理程序来控制,而不是像button1_MouseMove那样形成2.不要使用这个向量,而是你的控件(Point newlocation = button1.Location;) 3.你不需要覆盖处理程序.

在我的测试中,这些更改按钮(或其他控件)移动正常。

志高

于 2013-03-01T16:17:26.160 回答
1

试试这个根据鼠标的位置移动对象,下面给出的代码是收集鼠标的移动路径和保存在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();
    }
}
于 2015-03-21T11:17:52.400 回答
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;
}
于 2013-05-15T07:18:28.630 回答