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

时间:2010-04-24 03:41:46

标签: c# controls mouse position flicker

我想在用户点击并拖动控件时让控件跟随光标。问题是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 个答案:

答案 0 :(得分: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,因为 会产生影响。

答案 1 :(得分:2)

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

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

Chigook

答案 2 :(得分: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();
    }
}

答案 3 :(得分: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;
}
相关问题