//添加事件
this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.DragEnd);
this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.DragMove);
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.DragBegin);
private Point p1;//拖动前鼠标的屏幕坐标
private Point p2;//拖动后鼠标的屏幕坐标
private bool _isDrag;//是否正在被拖动
private bool _allowDragMove;
/// <summary>
/// 是否允许被拖动。
/// </summary>
public bool AllowDragMove
{
get
{
return this._allowDragMove;
}
set
{
this._allowDragMove = value;
}
}
private void DragBegin(object sender, System.Windows.Forms.MouseEventArgs e)
{
if(e.Button == MouseButtons.Left & this.AllowDragMove)
{
this._isDrag = true;
//记录下拖动前的坐标
this.p1 = this.PointToScreen(new Point(e.X, e.Y));
}
}
private void DragEnd(object sender, System.Windows.Forms.MouseEventArgs e)
{
if(e.Button == MouseButtons.Left & this._isDrag)
{
this._isDrag = false;
//记录下拖动后的坐标
this.p2 = this.PointToScreen(new Point(e.X, e.Y));
//计算位移
int x = p2.X - p1.X;
int y = p2.Y - p1.Y;
//移动控件位置
this.Left += x;
this.Top += y;
}
}
private void DragMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if(this._isDrag)
{
//记录下拖动后的坐标
this.p2 = this.PointToScreen(new Point(e.X, e.Y));
//计算位移
int x = p2.X - p1.X;
int y = p2.Y - p1.Y;
//移动控件位置
this.Left += x;
this.Top += y;
//把拖动后的顶点作为新的拖动前顶点
p1 = p2;
}
}