关闭

自定义控件的拖动

标签: object
929人阅读 评论(0) 收藏 举报
分类:

//添加事件
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;
}



 


 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:50159次
    • 积分:589
    • 等级:
    • 排名:千里之外
    • 原创:1篇
    • 转载:28篇
    • 译文:0篇
    • 评论:9条
    文章分类
    最新评论