C# – 将控件移动到鼠标位置
发布时间:2020-12-16 00:13:25 所属栏目:百科 来源:网络整理
导读:当用户单击并拖动控件时,我试图让控件跟随光标.问题是1.)控制器不会移动到鼠标的位置,以及2.)控制器在整个地方闪烁和飞行.我尝试了几种不同的方法,但到目前为止都失败了. 我试过了: protected override void OnMouseDown(MouseEventArgs e){ while (e.Butto
当用户单击并拖动控件时,我试图让控件跟随光标.问题是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; } } 但这些都不奏效.任何帮助表示赞赏,并提前感谢! 解决方法
这是怎么做的:
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,因为它会产生影响. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |