首先,您需要实现有助于拖放控件的功能。但在此之前,您需要将控件的当前位置存储在一些类级变量中。请考虑以下代码段:
int xloc;
int yloc;
///other codes in-between
private void btn1_Click()
{
xloc = this.btn1.Location.X;
yloc = this.btn1.Location.Y;
}
现在,拖放功能:
private Point setNewLocation;
private void btn1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
setNewLocation= e.Location;
}
}
private void btn1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
btn1.Left = e.X + btn1.Left - setNewLocation.X;
btn1.Top = e.Y + btn1.Top - setNewLocation.Y;
}
}
这将帮助您移动控件。。。但是当你控制另一个的时候会发生什么呢?我的意思是,你肯定不希望一个控件与另一个控件重叠。相反,当一个控件放置在另一个控件上时,另一个控件会将其位置更改为与其重叠的控件的上一个位置。所以,在
MouseUP
当前拖动控件的事件,请使用以下选项:
private void btn1_MouseUP()
{
foreach (Control other in FlowlayoutPanel1.Controls)
{
///change control type as required
if (!other.Equals(btn1) && other is Button && btn1.Bounds.IntersectsWith(other.Bounds))
{
other.Location = new Point(xloc, yloc)
}
}
我尚未调试代码,因此如果遇到任何bug,请务必留下评论:)