[英]Move button on C#
I am working on an exercise which I have to move a button by mouse but I need to save the first location of this button. 我正在做一个练习,必须通过鼠标移动一个按钮,但是我需要保存此按钮的第一个位置。
this is my code: 这是我的代码:
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);
}
}
but location's value change after moving the button , what I have to do for save the first value. 但是在移动按钮后位置的值会发生变化,我要做的是保存第一个值。
Just 只是
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;
}
If you need to save all positions then you can use a list of points 如果需要保存所有位置,则可以使用点列表
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
}
You are calling a function to read the 'Location'
variable, you should simply assign
the value. 您正在调用一个函数来读取
'Location'
变量,则只需assign
该值即可。
private Point location = new Point(button1.Location.X, button1.Location.Y);
Also, you need a mouseup
event, where you set: 另外,您需要在以下位置设置
mouseup
事件:
isMouseDown = false;
Otherwise it will be true forever. 否则,它将永远是真的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.