自定义控件的拖动

2008-02-23 09:15:26来源:互联网 阅读 ()

新老客户大回馈,云服务器低至5折

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



上一篇: NetBeans vs eclipse 的主要方面的介绍
下一篇: 两种意见之二:用Eclipse与弃NetBeans

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:ChartDirector的柱状图初步使用方法

下一篇:Will NetBeans 6.0 Be an Eclipse Killer?