关于自定义控件

来源:互联网 发布:多空资金指标公式源码 编辑:程序博客网 时间:2024/05/21 15:00
 

 前段时间纠结于自定义控件,现在想总结出来供大家分享,分享;

就此总结,自定义控件我将其分为三种

第一种,

也就是最简单的一种,就只直接继承自某个已经封装好的控件,:Label,Button,PicBox等等

public class UserLabel:System.Windows.Forms.Label

{

        public string AAA { get; set; }

        public UserLabel() { }

        public void ABC()

        { 

        }

//在该类里面,可以为UserLabel添加字段,属性,方法等;

}

第二种,

就是组合控件,VS2010的程序集中,右键,添加用户控件就是可以添加用户控件了,然后通过拖动左侧的"工具栏"可以添加控件到自己要定义的控件中

比如右图,就是Label和PicBox的合成的;

然后可以像编辑窗体一样,设计控件了;

第三种,也就是最麻烦的一种

首先要懂一些,C#中GDI的一些相关知识

比如说,现在你需要自定义一个圆形的控件

要将其继承字Control类;

using System.ComponentModel;

public partial class UserControlMake:System.Windows.Forms.Control

{

        //控件大体框架,内圆

        protected Rectangle inrect = new Rectangle();

        //外圆

        protected Rectangle outrect = new Rectangle();

        //字体风格大小

        protected Font font = new System.Drawing.Font("华文行楷", 40);

        protected string ChessName = "默认字符串";

//自己定义一些图形的模板

        public UserControlMake()

        {

            InitializeComponent();

PS:如果你想控件多一个背景颜色,透明

            SetStyle(ControlStyles.SupportsTransparentBackColor, true);

        }

//以下分别是设置控件的默认值,描述,一个类别;

//这些将在VS2010的属性栏中显示出来

        [DefaultValue("默认字符串"), Description("一个属性的描述"), Category("Chess")]

        public string CHESSNAME

        {

            get

            {

                return this.ChessName;

            }

            set

            {

                this.ChessName = value;

                this.Invalidate(); //重绘该控件

            }

        }

注意:类似这种属性添加的方式可以重载Control的的属性

eg.

        [DefaultValue("Transparent"), Description("背?景°颜?色?")]

        public override Color BackColor

        {

            get

            {

                return base.BackColor;

            }

            set

            {

                base.BackColor = value;            }

        }

现在要画控件,重载Control中的OnPaint()方法

eg.

        protected override void OnPaint(PaintEventArgs e)

        {

PS.

在此控件类中写一个Reactant,或者是Point

该图形的坐标是相对的,也就是,比如一下矩形的左上角坐标是相对于该控件(2,2)的位置

            //里面画一个圆

            inrect.X = 2;

            inrect.Y = 2;

            inrect.Width = this.Width - 2;

            inrect.Height = this.Height - 2;

            e.Graphics.FillEllipse(new SolidBrush(Color.Black), inrect);

        }

}

关于"事件"

如果想定一些事件,可以在该控件的构造方法中,为该事件添加订阅方法

eg.

        public UserControl1()

        {

            InitializeComponent();

            this.Click += new EventHandler(UserControl1_Click);

        }

        void UserControl1_Click(object sender, EventArgs e)

        {

            throw new NotImplementedException();

        }

当然也可重载继承自Control事件的的方法

eg.在该类中写下

        protected override void OnClick(EventArgs e)

        {

            base.OnClick(e);

        }

PS.

当然也可以在该控件拖入窗体后再进行添加事件,

如果写的时同一个事件,触发的时间先后顺序当然也不一样

确实想写一个控件;这些类似的这些语句是必不可少的