每当我需要在运行时在窗体上移动控件的位置时,都必须为其顶部和左侧属性分配新值。为什么Location属性不起作用?
例如,我应该能够:
private void btn_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
((Button)sender).Location = e.Location;
}
}
但这是行不通的,相反,我必须这样做:
private void btn_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
((Button)sender).Left = e.X + ((Button)sender).Left;
((Button)sender).Top = e.Y + ((Button)sender).Top;
}
}
这两个代码段不相同。
该MouseEventArgs
报告坐标相对于控制你附MouseMove
事件,在这种情况下按钮。
在第一个示例中,e.Location
是0,0
当鼠标位于Button的左上角时。然后将Button的位置设置为0,0
,但是由于其位置是相对于其所在的Form的,所以您的按钮将跳转到Form的左上角。
在第二个示例中,您分别通过添加e.X
和添加e.Y
到Button的现有属性Left
和Top
属性来正确设置位置。
要“修复”第一个示例,您必须对其进行修改以考虑到Button的当前位置:
if (e.Button == MouseButtons.Left)
{
var b = ((Button) sender);
b.Location = new Point(b.Left + e.X, b.Top + e.Y);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句