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

当用户单击并拖动控件时,我试图让控件跟随光标.问题是1.)控制器不会移动到鼠标的位置,以及2.)控制器在整个地方闪烁和飞行.我尝试了几种不同的方法,但到目前为止都失败了.

我试过了:

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

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

但这些都不奏效.任何帮助表示赞赏,并提前感谢!

解决方法:

这是怎么做的:

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在这里用于两个目的:在最初点击鼠标时跟踪鼠标在控件上的位置,并跟踪鼠标按钮是否关闭(这样当鼠标按下时控件不会被拖动光标越过它而按钮没有按下).

你绝对不希望将此代码中的ifs切换为while,因为它会产生影响.

上一篇:如何在一个侦听器中识别mouseDragged和mousePressed事件?


下一篇:javascript – 在画布上绘图时偏移