自由是冠军

制作软件,并以此获得自由!

自定义控件的拖动

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



 


阅读更多
文章标签: object
个人分类: .net编程全景
上一篇单元测试应该测试什么?——Right-BICEP
下一篇UserControl的单击事件对鼠标左右键都有效,怎样使之像按钮控件那样只对鼠标左键敏感?
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭