我正在做一个练习,必须通过鼠标移动一个按钮,但是我需要保存该按钮的第一个位置。
这是我的代码:
private Point location => new Point(button1.Location.X, button1.Location.Y);
private void button1_MouseDown(object sender, MouseEventArgs e)
{
isMouseDown = true;
}
private void button1_MouseMove(object sender, MouseEventArgs e)
{
if(isMouseDown)
{
button1.Left = e.X + button1.Left - (button1.Width / 2);
button1.Top = e.Y + button1.Top - (button1.Height / 2);
}
}
但是在移动按钮后位置的值会发生变化,我要做的是保存第一个值。
答案 0 :(得分:3)
只是
private Point location => new Point(button1.Location.X, button1.Location.Y);
private void button1_MouseDown(object sender, MouseEventArgs e) {
isMouseDown = true;
location.X = button1.Location.X;
location.Y = button1.Location.Y;
}
如果需要保存所有位置,则可以使用点列表
private List<Point> locations = new List<Point>();
private void button1_MouseDown(object sender, MouseEventArgs e) {
isMouseDown = true;
locations.Add(new Point(button1.Location.X, button1.Location.Y)); // where locations[0] is your first point
}
答案 1 :(得分:1)
您正在调用函数来读取'Location'
变量,您应该简单地assign
值。
private Point location = new Point(button1.Location.X, button1.Location.Y);
此外,您需要设置一个mouseup
事件:
isMouseDown = false;
否则,它将永远是真的。