復制代碼 代碼如下:
using System.Windows.Forms;
namespace WinFormsApp_DragControls
{
public class DragControl
{
//待拖動的控件
private Control m_Control;
//鼠標按下時的x,y坐標
private int m_X;
private int m_Y;
public DragControl(Control control)
{
m_Control = control;
m_Control.MouseDown += new MouseEventHandler(control_MouseDown);
m_Control.MouseMove += new MouseEventHandler(contro_MouseMove);
}
private void control_MouseDown(object sender, MouseEventArgs e)
{
m_X = e.X;
m_Y = e.Y;
}
private void contro_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
int x = e.X - m_X;
int y = e.Y - m_Y;
this.m_Control.Left += x;
this.m_Control.Top += y;
}
}
}
}
調用:
DragControl obj1 = new DragControl(button1);
則表示在運行的界面上,支持隨意拖動button1
另外還可以進一步實現改變控件大小、GDI+實現加邊界腳點、保存控件的位置到xml下次可以讀取(布局)以及自動布局N個Control的算法等,想進一步了解可與本人聯系,此處不多敘述..