c#自定义控件开发实例(2)
2024-07-21 02:19:53
供稿:网友
 
源文件: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只改变大小
其他则是清理工作。
好了,那么赶紧编译。生成就可以了。
中国最大的web开发资源网站及技术社区,