控件拖拽基本方法
//在窗体放置一个按钮 button1
private bool isMouseDown = false; //记录按钮是否被按下
private Point mouseOffset; //记录鼠标指针的坐标
public Form1()
{
InitializeComponent();
this.button1.MouseMove += new MouseEventHandler(button1_MouseMove);
this.button1.MouseDown += new MouseEventHandler(button1_MouseDown);
this.button1.MouseUp += new MouseEventHandler(button1_MouseUp);
}
void button1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isMouseDown = false; //如果左边按钮弹起
}
}
void button1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mouseOffset.X = e.X;
mouseOffset.Y = e.Y;
isMouseDown = true;
}
}
void button1_MouseMove(object sender, MouseEventArgs e)
{
if (isMouseDown)
{
int left = button1.Left + e.X - mouseOffset.X;
int top = button1.Top + e.Y - mouseOffset.Y;
button1.Location = new Point(left, top);
}
}