C# 为什么';为控件位置属性指定新值是否会在运行时更改其位置?
每当我需要在运行时移动控件在窗体上的位置时,我都必须为其顶部和左侧属性指定新值。为什么Location属性不起作用 例如,我应该能够做到:C# 为什么';为控件位置属性指定新值是否会在运行时更改其位置?,c#,winforms,C#,Winforms,每当我需要在运行时移动控件在窗体上的位置时,我都必须为其顶部和左侧属性指定新值。为什么Location属性不起作用 例如,我应该能够做到: private void btn_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { ((Button)sender).Location = e.Loc
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
。然后,按钮的位置设置为0,0
,但由于其位置相对于其所在的表单,因此按钮会跳到表单的左上角
在第二个示例中,通过将e.X
和e.Y
分别添加到按钮的现有Left
和Top
属性中,可以正确设置位置
要“修复”第一个示例,您必须修改它以考虑按钮的当前位置:
if (e.Button == MouseButtons.Left)
{
var b = ((Button) sender);
b.Location = new Point(b.Left + e.X, b.Top + e.Y);
}