背景:#EDF0F5 #FAFBE6 #FFF2E2 #FDE6E0 #F3FFE1 #DAFAF3 #EAEAEF 默认  
阅读新闻

c#自定义控件开发实例

[日期:2004-05-27] 来源:CSDN  作者:ilqtj [字体: ]

下面讲一下控件具体如何工作,首先要写他的属性以及重写他的属性,
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只改变大小

其他则是清理工作。

好了,那么赶紧编译。生成就可以了。


上一页12  GO
阅读:
录入:木鸟

推荐 】 【 打印
上一篇:开发基于Web的CSS设计器
下一篇:在.NET客户端程序中应用多线程
相关新闻      
本文评论       全部评论
  很好   (用户名 ,04月17日 )
  不錯不錯   (遊客 ,2007-02-04 )
发表评论


点评: 字数
姓名:

  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款