本文共 2908 字,大约阅读时间需要 9 分钟。
源码地址:
以上链接是用积分下载的,如果没有积分,可以用以下链接付费下载:
实现功能:实现自由拖拽控件,按住鼠标控件拖拽时有黑框显示,松开鼠标控件位置即为黑框位置
实现思路:在按住鼠标时,得到所点击控件的Size以及Location,在鼠标移动时,得到鼠标的坐标,并且在光标坐标处绘制一个与控件大小相同的黑框,松开鼠标时得到黑框的Location,并将黑框的坐标值赋值给控件坐标,即实现了控件拖拽
效果图:
直接上代码,代码中解释的很详细了。我这里是把控件都放在gbConfig容器中的,所以记得加上gbConfig控件的Paint事件
//记录鼠标拖放Point po = Point.Empty;//生成的控件Label lbl = null;//鼠标按下坐标(control控件的相对坐标) Point mouseDownPoint = Point.Empty;//显示拖动效果的矩形 Rectangle rect = Rectangle.Empty;//是否正在拖拽 bool isDrag = false;private void Form1_Load(object sender, EventArgs e){ CreateControls(); this.gbConfig.AllowDrop = true;}////// 生成三个label控件/// private void CreateControls(){ int x = 10; int y = 20; int xx = 0; for (int i = 0; i < 3; i++) { string lbltext = "序号" + xx; string lblname = "lbl" + xx; 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 > gbConfig.Width - x) { x = 10; y += lbl.Height + 10; } lbl.AllowDrop = false; // 默认为 false,即不可拖动 lbl.MouseDown += new MouseEventHandler(lbl_MouseDown); lbl.MouseUp += new MouseEventHandler(lbl_MouseUp); lbl.MouseMove += new MouseEventHandler(lbl_MouseMove); this.gbConfig.Controls.Add(lbl); xx++; }}////// 鼠标拖动控件操作/// /// /// private void lbl_MouseDown(object sender, MouseEventArgs e){ if (e.Button == MouseButtons.Left) { lbl = (Label)sender; //记录控件的大小 rect = lbl.Bounds; po = e.Location;//鼠标点击时相对于控件的位置进行记录 }}private void lbl_MouseUp(object sender, MouseEventArgs e){ if (e.Button == MouseButtons.Left) { if (isDrag) { isDrag = false; //移动control到放开鼠标的地方 lbl.Location = rect.Location; this.Refresh(); } reset(); }}private void lbl_MouseMove(object sender, MouseEventArgs e){ if (e.Button == MouseButtons.Left) { isDrag = true; //重新设置rect的位置,跟随鼠标移动 rect.Location = getPointToForm(new Point(e.Location.X - gbConfig.Location.X-po.X, e.Location.Y - gbConfig.Location.Y- po.Y)); this.Refresh(); }}//把相对与control控件的坐标,转换成相对于窗体的坐标。private Point getPointToForm(Point p){ return this.PointToClient(lbl.PointToScreen(p));}//重置变量 private void reset(){ rect = Rectangle.Empty; isDrag = false;}////// 绘制黑框/// /// /// private void gbConfig_Paint(object sender, PaintEventArgs e){ if (rect != Rectangle.Empty) { if (isDrag) {//画一个和Control一样大小的黑框 e.Graphics.DrawRectangle(Pens.Black, rect); } else { e.Graphics.DrawRectangle(new Pen(this.BackColor), rect); } }}
转载地址:http://wyulf.baihongyu.com/