虽然我发布了一些与此相关的内容(这让我失去了很多次票),但我决定继续我最初尝试自己做(有一些好的结果),但我碰到了一个问题,我不能看看如何解决它。
我的代码创建了一组 n 可点击按钮,按下按钮时应该移动这些按钮。我已经设法做到了,但是当我点击它并移动它们时,它们以一种奇怪的方式“跳跃”,而不是重新定位我想要它们的方式,然后它们可以自由移动。
这是按钮类的代码:
namespace moverButtons
{
class buttonCito:Button
{
Point posActual;
bool mousePressed;
// public MouseEventHandler MouseMove;
public buttonCito(int altUra, int anchUra, Point position)
{
this.Height = altUra;
this.Width = anchUra;
this.Location = position;
}
public buttonCito()
{
// TO DO: Complete member initialization
}
protected override void OnMouseMove(MouseEventArgs e)
{
mousePressed = (e.Button == MouseButtons.Left) ? true : false;
if (e.Location != null && mousePressed)
{
moverButton(e.X, e.Y);
}
//Añadir rutina para mover con el mouse
//Add routine to move with the mouse
}
public void moverButton(int x,int y)
{
this.Location = new Point(x + posActual.X, y + posActual.Y);
posActual = this.Location;
}
}
}
这是表格的代码:
namespace moverbuttons
{
public partial class Form1 : Form
{
Point positionMouseForm;
public Form1()
{
InitializeComponent();
this.MouseMove += new MouseEventHandler(map_MouseMove);
}
private void map_MouseMove(object sender, MouseEventArgs e)//obtains the position of the mouse on the form
{ //I want to give this position to the button class, is there a way?
positionMouseForm = e.Location;
}
private void Form1_Load(object sender, EventArgs e)
{ List<buttonCito> buttons = new List<buttonCito>();
Random rnd = new Random();
int x,y;
for (int i = 0; i < 5; i++)
{
x = rnd.Next(1, 300);
y = rnd.Next(1, 300);
buttonCito newButton = new buttonCito(50,50,new Point(x,y));
buttons.Add(newButton);
this.Controls.Add(newButton);
}
}
}
}
如果可以,以某种方式将鼠标在窗体上的位置给予按钮,我可以轻松修复它。
答案 0 :(得分:2)
解决此问题的一种方法是使用delta(两个对象之间的差异)。
Point lastMousePosition;
private void MoveButton(int currentX, int currentY)
{
int deltaX = currentX - lastMousePosition.X;
int deltaY = currentY - lastMousePosition.Y;
this.Location = new Point(Location.X + deltaX, Location.Y + deltaY);
lastMousePosition = new Point(currentX, currentY);
}
按下按钮时,最初将lastMousePosition设置为鼠标位置(在释放按钮之前不会再次设置)。
请注意,重复调用此类构造函数的效果不是很好。您可能需要考虑重用仅实例化一次的Point对象。当然,一旦你有工作,你应该只担心这一点:)