1.代码块:
//记录鼠标拖放
bool bMouseDown;
Point po = Point.Empty;
//生成的控件
Label lbl = null;
TextBox txt = null;
/// <summary>
/// 窗体加载
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AreaPicQuery_Load(object sender, EventArgs e)
{
CreateControls();
}
/// <summary>
/// 默认容器属性
/// </summary>
private void AreaShow()
{
// 默认为 false,即不接受用户拖动到其上的控件
//this.gbName.AllowDrop = true;
this.gbConfig.AllowDrop = true;
// 拖动对象进入控件边界时触发
this.gbName.DragEnter += new DragEventHandler(groupBox_DragEnter);
this.gbConfig.DragEnter += new DragEventHandler(groupBox_DragEnter);
// 完成拖动时触发
this.gbName.DragDrop += new DragEventHandler(groupBox_DragDrop);
this.gbConfig.DragDrop += new DragEventHandler(groupBox_DragDrop);
}
/// <summary>
/// 区域名称初始化
/// </summary>
private void CreateControls()
{
int x = 10;
int y = 20;
list = rsqm.AreaConfigInfo();
for (int i = 0; i < list.Count; i++)
{
string lbltext = list[i].AreaName;
string lblname = "lbl" + list[i].SystemID;
lbl = new Label();
lbl.Left = x;
lbl.Top = y;
lbl.Font = new Font("楷书", 14, FontStyle.Bold);
lbl.Name = lblname;
lbl.Text = lbltext;
lbl.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
lbl.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
x += lbl.Width + 5;
if (lbl.Width > gbName.Width - x)
{
x = 10;
y += lbl.Height + 10;
}
lbl.AllowDrop = false; // 默认为 false,即不可拖动
lbl.MouseDown += new MouseEventHandler(lbl_MouseDown);
lbl.MouseUp += new MouseEventHandler(lbl_MouseUp);
this.gbName.Controls.Add(lbl);
}
}
/// <summary>
/// 鼠标拖动控件到容器边界触发
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void groupBox_DragEnter(object sender, DragEventArgs e)
{
//定义拖动类型
e.Effect = DragDropEffects.Copy;
bMouseDown = true;
}
/// <summary>
/// 鼠标控件进入另外的容器内
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void groupBox_DragDrop(object sender, DragEventArgs e)
{
if (bMouseDown)
{
//从事件参数 DragEventArgs 中获取被拖动的元素
lbl = (Label)e.Data.GetData(typeof(Label));
GroupBox grp = (GroupBox)lbl.Parent;
//grp.Controls.Remove(lbl);
((GroupBox)sender).Controls.Add(lbl);
bMouseDown = false;
}
}
/// <summary>
/// 鼠标拖动控件操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lbl_MouseDown(object sender, MouseEventArgs e)
{
lbl = (Label)sender;
}
private void lbl_MouseUp(object sender, MouseEventArgs e)
{
lbl.Location = getPointToForm(new Point(e.Location.X - gbConfig.Location.X, e.Location.Y));
lbl.DoDragDrop(lbl, DragDropEffects.Copy);
}
//把相对与control控件的坐标,转换成相对于窗体的坐标。
private Point getPointToForm(Point p)
{
return this.PointToClient(lbl.PointToScreen(p));
}
2.效果图: