所有的控件都加上这三个事件:
#region 移动相关
bool _moving = false;
Point _offset;
private void _MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
return;
_moving = true;
_offset = new Point(Control.MousePosition.X - ((Control)sender).Location.X, Control.MousePosition.Y - ((Control)sender).Location.Y);
}
private void _MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
return;
if (_moving)
((Control)sender).Location = new Point(Control.MousePosition.X - _offset.X, Control.MousePosition.Y - _offset.Y);
}
private void _MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
return;
_moving = false;
}
#endregion
bool flag; Point mp, bp; Timer t;
private void button1_Click(object sender, EventArgs e)
{
t = new Timer();
bp = this.button1.Location;
mp = Cursor.Position;
flag = true; t.Start();
t.Interval = 100; t.Tick += new EventHandler(t_Tick);
}
void t_Tick(object sender, EventArgs e)
{
Point mp1 = Cursor.Position;
int x = mp1.X - mp.X;
int y = mp1.Y - mp.Y;
this.button1.Location = new Point(bp.X + x, bp.Y + y);
if (flag) { if (x == 0 && y == 0)return; }
}
缺点:点击按钮无法停下,你在看看办法