自定义控件的一些总结

来源:互联网 发布:php公司网站源码 编辑:程序博客网 时间:2024/05/22 01:55
       自定义控件功能:隐藏自定义控件中TextBox控件的边框,在 textBox 控件下面划一条直线。并可以通过属性控制是否只可以输入正整数
注意:
       1.属性的特性描述既可以填也可以不填,如果不填该属性将默认显示到自定义控件的杂项分组。
        Description   该属性在属性栏中的描述
        Browsable     是否显示到属性栏
        Category        指定该属性属于那个分组
        DefaultValue 控件默认值
        还有好多属性可以填,有兴趣的话自己研究一下。
        2. CtrlUnderlineTextBox_Paint  事件用于在控件下面划一条直线,当然,改改 PointF  你可以随意在两个点之间划线, Graphics  类里面的东西还是很丰富的。
        3. ctrlUnderlineTextBox_KeyPress 事件可以控制 textBox 只输入不能大于8位的正整数和删除键。
        4.自定义属性 TextBoxText  用于获取和设置 textBox 的文本值。
        5.自定义属性 IntBool 用于控制是否只可以输入正整数。
        6.如果你想控制根据属性是否为自定义控件加载事件(像本例中的ctrlUnderlineTextBox_KeyPress),那么你最好写在属性的Set访问器中,写在自定义控件的构造函数下边,不管属性是什么,都不会被触发的。
自定义控件源代码:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Drawing;using System.Data;using System.Linq;using System.Text;using System.Windows.Forms;namespace GCIMS.CommonCtrl{    public partial class ctrlUnderlineTextBox : UserControl    {        #region 属性        /// <summary>        /// 控件的文本        /// </summary>        [Description("文本值"), Browsable(true), Category("自定义属性")]        public string TextBoxText        {            get            {                return textBox.Text;            }            set            {                textBox.Text = value;            }        }        private bool intBool;        [Description("输入正整数"), Browsable(true), Category("自定义属性"), DefaultValue(false)]        public bool IntBool        {            get            {                return intBool;            }            set            {                intBool = value;                if (intBool)                {                    textBox.KeyPress += new KeyPressEventHandler(ctrlUnderlineTextBox_KeyPress);                }            }        }        #endregion        public ctrlUnderlineTextBox()        {            InitializeComponent();        }        private void ctrlUnderlineTextBox_KeyPress(object sender, KeyPressEventArgs e)        {            if ((int)e.KeyChar >= 48 && (int)e.KeyChar <= 57 && textBox.Text.Length < 8 || (int)e.KeyChar == 8) //只能输入0-9数字和BackSpace            {                e.Handled = false;            }            else            {                e.Handled = true;            }        }        private void CtrlUnderlineTextBox_Paint(object sender, PaintEventArgs e)        {            Graphics g = Graphics.FromHwnd(this.Handle);            System.Drawing.Pen pen = new Pen(Color.Black);            PointF point1 = new PointF(textBox.Location.X, textBox.Location.Y + textBox.Height);            PointF point2 = new PointF(textBox.Location.X + textBox.Width, textBox.Location.Y + textBox.Height);            g.DrawLine(pen, point1, point2);        }    }}


1 0