源文件:http://ded.nuaa.edu.cn/download/Windows%20Extended%20Controls.rar
示例代码:http://ded.nuaa.edu.cn/download/WindowsApplication6.rar
下面讲一下控件具体如何工作,首先要写他的属性以及重写他的属性,
private Color _BorderColor=new Color();
[DefaultValue("Black"),Description("边框颜色"),Category("Appearance")]
public Color BorderColor
{
get
{
// Insert code here.
return _BorderColor;
}
set
{
_BorderColor=value;
this.Invalidate();
}
}
DefaultValue:设定默认值,Description:描述,就是属性下面的说明,Category:属性分类.其他的同理
设置好属性以后应该重写他的绘制过程,也就是
protected override void OnPaint(PaintEventArgs pe)
{
// Calling the base class OnPaint
base.OnPaint(pe);
ReDrawControl(pe.Graphics);
}
private void ReDrawControl(Graphics graphics)
{
try
{
//绘制边框
Rectangle rectBorder=new Rectangle();
Pen borderPen=new Pen(this._BorderColor,1);
rectBorder.X = 7;
rectBorder.Y = 7;
rectBorder.Height = this.Height-15;
rectBorder.Width = this.Width-15;
graphics.DrawRectangle(borderPen, rectBorder);
//绘制编辑框
if (_ReSizeble)
{
DrawSelector(graphics);
}
}
catch(Exception E)
{
throw E;
}
finally
{
graphics.Dispose();
}
}
[Description("控件选择区域"),Category("Behavior")]
public Rectangle SelectRectangle
{
get
{
Rectangle selectRectangler=new Rectangle();
selectRectangler.X = this.Location.X+7;
selectRectangler.Y = this.Location.Y+7;
selectRectangler.Height = this.Height-15;
selectRectangler.Width = this.Width-15;
return selectRectangler;
}
}
ReDrawControl中定义了Rectangle (矩形),让后填充改矩形的边框:graphics.DrawRectangle(borderPen, rectBorder);,这里要说明的是边框外面还有编辑框,所以大小不是控件的大小。DrawSelector就是绘制8个选择框的,基本和绘制边框差不多,即使定义好坐标就可以了。干好了之后不要忘了释放资源:graphics.Dispose();
SelectRectangle:控件所选择的Rectangle,最终要得就是它了
ok,这样一个基本的东西出来了,下面我们要写他的move和resize函数了,先添加事件:
this.Resize += new System.EventHandler(this.ShapeEx_Resize);
this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.ShapeEx_MouseUp);
this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.ShapeEx_MouseMove);
this.MouseLeave += new System.EventHandler(this.ShapeEx_MouseLeave);
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.ShapeEx_MouseDown);
原理:当鼠标点击的时候this.MouseDown,记录鼠标的位置,控件的原始位置和大小,判断位置:_rectLeftBottomSelector.Contains(e.X,e.Y):表示点击的是左下,设置鼠标,记录状态this._SelectSelctedIndex:判断点击了那个选择框,取值0-8:0代表移动整个控件,1是右上移动,2-8顺时针索引选择框。this.MouseMove处理如何改变控件的大小和位置
case 0://只移动位置
this.Location=new Point(Cursor.Position.X-(_MouseLocation.X-_SelfLocation.X),Cursor.Position.Y-(_MouseLocation.Y-_SelfLocation.Y));
break;
1,5不仅移动位置,还改变大小,2,3,4,6,7,8只改变大小
其他则是清理工作。
好了,那么赶紧编译。生成就可以了。
本文地址:http://com.8s8s.com/it/it44729.htm