给大家分享一个自定义Winform控件类

本文介绍了一种自定义TextBox控件的方法,通过继承系统提供的TextBox类并重写部分方法,实现了焦点变化时背景色的变化、特定字符过滤等功能,并提供了多个预设的子类以满足不同场景的需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;

using System.Collections.Generic;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.ComponentModel;

namespace Hzj.HzjWinForm.Control

{

    /************************************************************************************************************

     * 

     * 摘要:创建自定义TextBox基类,重写OnGotFocus与OnLostFocus事件,实现获取与失去焦点后动态改变控件背景色

     * 

     * 创始人:贺振军

     * 

     * 创建日期:2008年04月17日

     * 

     ***********************************************************************************************************/



    public class BaseTextBox : TextBox

    {

        #region 重写控件,实现获取焦点时自动变更背景色

        //高亮颜色



        private Color m_FocusHightColor = System.Drawing.Color.FromArgb(255, 255, 136);

        //开关

        private bool m_FocusHightEnable = false;



        public BaseTextBox()

        {

            //设置边框为FixedSingle类型

            this.BorderStyle = BorderStyle.FixedSingle;

            //设置默认背景颜色

            this.BackColor = Color.White;

            //设置默认字体颜色

            this.ForeColor = System.Drawing.Color.Black;



        }



        [Category("设置"),

        Description("设置控件在获取焦点后的高亮显示颜色"),

        DefaultValue(null)] 

        public Color FocusHightColor

        {

            get

            {

                return m_FocusHightColor;

            }

            set

            {

                m_FocusHightColor = value;

            }

        }

        [Category("设置"),

        Description("设置控件在获取焦点后是否高亮显示"),

        DefaultValue(null)] 

        public bool FocusHightEnable

        {

            get

            {

                return m_FocusHightEnable;

            }

            set

            {

                m_FocusHightEnable = value;

            }

        }

        protected override void OnGotFocus(EventArgs e)

        {

            base.OnGotFocus(e);

            if (m_FocusHightEnable)

            this.BackColor = m_FocusHightColor;

        }

        protected override void OnLostFocus(EventArgs e)

        {

            base.OnLostFocus(e);

            this.BackColor = System.Drawing.Color.White;

        }        

        #endregion



        /// <summary>

        /// 功能说明:只允许输入数字和小数点

        /// 创始人:贺振军  20080419

        /// </summary>

        /// <param name="e"></param>

        /// <returns></returns>

        protected bool CheckTextBoxNum(KeyPressEventArgs e)

        {

            bool flage = false;

            //实现全半角自动转换

            //e.KeyChar = SBCcaseAndDBCcase.ConvertSBCcaseToDBCcase(e.KeyChar);

            if ((e.KeyChar >= '0' && e.KeyChar <= '9'))

            {

                flage = false;

            }

            else

            {

                flage = true;

            }

            if (e.KeyChar == Convert.ToChar(Keys.Back) || e.KeyChar == '.')

            {

                flage = false;

            }

            return flage;

        }

        /// <summary>

        /// 功能说明:只允许输入数字和字母

        /// 创始人:贺振军  20080419

        /// </summary>

        /// <param name="e"></param>

        /// <returns></returns>

        protected bool CheckTextBoxCharNum(KeyPressEventArgs e)

        {

            bool flage = false;

            //实现全半角自动转换

            //e.KeyChar = SBCcaseAndDBCcase.ConvertSBCcaseToDBCcase(e.KeyChar);

            if ((e.KeyChar >= '0' && e.KeyChar <= '9') || (e.KeyChar >= 'A' && e.KeyChar <= 'Z') || (e.KeyChar >= 'a' && e.KeyChar <= 'z'))

            {

                flage = false;

            }

            else

            {

                flage = true;

            }

            if (e.KeyChar == Convert.ToChar(Keys.Back))

            {

                flage = false;

            }

            return flage;

        }

        /// <summary>

        /// 功能说明:只允许输入数字和字母

        /// 创始人:贺振军  20080419

        /// </summary>

        /// <param name="e"></param>

        /// <returns></returns>

        protected bool CheckTextBoxChar(KeyPressEventArgs e)

        {

            bool flage = false;

            //实现全半角自动转换

            //e.KeyChar = SBCcaseAndDBCcase.ConvertSBCcaseToDBCcase(e.KeyChar);

            if ((e.KeyChar >= 'A' && e.KeyChar <= 'Z') || (e.KeyChar >= 'a' && e.KeyChar <= 'z'))

            {

                flage = false;

            }

            else

            {

                flage = true;

            }

            if (e.KeyChar == Convert.ToChar(Keys.Back))

            {

                flage = false;

            }

            return flage;

        }

        /// <summary>

        /// 功能说明:过滤指定的字符

        /// 创始人:贺振军  20080419

        /// </summary>

        /// <param name="e"></param>

        /// <returns></returns>

        protected bool CheckTextBoxChars(Char[] chars, KeyPressEventArgs e)

        {

            bool flage = false;

            //e.KeyChar = SBCcaseAndDBCcase.ConvertSBCcaseToDBCcase(e.KeyChar);

            if (chars != null && chars.Length > 0)

            {

                Array.Sort(chars);

                int i_Count = Array.BinarySearch(chars, (char)e.KeyChar);

                if (i_Count >= 0)

                {

                    flage = true;

                }

                else

                {

                    flage = false;

                }

            }

            return flage;

        }

        /// <summary>

        /// 功能说明:只允许输入数字和字母

        /// 创始人:贺振军  20080419

        /// </summary>

        /// <param name="e"></param>

        /// <returns></returns>

        protected bool CheckTextBoxSqlChar(KeyPressEventArgs e)

        {

            bool flage = false;

            //转换为半角

            //e.KeyChar = SBCcaseAndDBCcase.ConvertSBCcaseToDBCcase(e.KeyChar);

            if ((int)e.KeyChar == 37 || (int)e.KeyChar == 45 || (int)e.KeyChar == 61 || (int)e.KeyChar == 39 || (int)e.KeyChar == 32 || (int)e.KeyChar == 34)

            {

                flage = true;

            }

            else

            {

                flage = false;

            }

            if (e.KeyChar == Convert.ToChar(Keys.Back))

            {

                flage = false;

            }

            return flage;

        }

    }



}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

using System;

using System.Text;

using System.Collections;

using System.Collections.Generic;

using System.Data;

using System.Windows.Forms;

using System.Windows.Forms.Design;

using System.Diagnostics;

using System.ComponentModel;

namespace Hzj.HzjWinForm.Control

{

    #region 只接收数字控件类

    /// <summary>

    /// 只接收数字,包括小数点,离开焦点时自动判断数字是否合法

    /// </summary>

    public class HzjTextBoxNumber : BaseTextBox

    {



        public HzjTextBoxNumber()

        {

            this.Text = "0.00";

            this.TextAlign = HorizontalAlignment.Right;

            this.MaxLength = 30;

        }

        protected override void OnKeyPress(KeyPressEventArgs e)

        {

            base.OnKeyPress(e);

            e.Handled = CheckTextBoxNum(e);

        }

        protected override void OnMouseDown(MouseEventArgs e)

        {

            base.OnMouseDown(e);

            //屏蔽右键粘贴

            Clipboard.Clear();

        }

        protected override void OnKeyDown(KeyEventArgs e)

        {

            //屏蔽Control + V粘贴

            base.OnKeyDown(e);

            if (e.Control && e.KeyCode == Keys.V)

            {

                Clipboard.Clear();

            }

        }

        protected override void OnLeave(EventArgs e)

        {

            base.OnLeave(e);

            if (!Hzj.HzjString.Check.isbland(this.Text.ToString().Trim()))

            {

                try

                {

                    Convert.ToDecimal(this.Text.ToString());

                }

                catch

                {

                    MessageBox.Show("非法数字,请重新输入.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    this.Text = "0.00";

                    this.Focus();

                    return;

                }

            }

            else

            {

                this.Text = "0.00";

            }

        }

    }

    #endregion

    #region 接收字符和数字类控件

    /// <summary>

    /// 只接收数字和字母,不能进行粘贴和复制

    /// </summary>

    public class HzjTextBoxCharNum : BaseTextBox

    {

        public HzjTextBoxCharNum()

        {

            this.MaxLength = 30;

        }

        protected override void OnKeyPress(KeyPressEventArgs e)

        {

            base.OnKeyPress(e);

            e.Handled = CheckTextBoxCharNum(e);

        }

        protected override void OnMouseDown(MouseEventArgs e)

        {

            base.OnMouseDown(e);

            //屏蔽右键粘贴

            Clipboard.Clear();

        }

        protected override void OnKeyDown(KeyEventArgs e)

        {

            //屏蔽Control + V粘贴

            base.OnKeyDown(e);

            if (e.Control && e.KeyCode == Keys.V)

            {

                Clipboard.Clear();

            }

        }



    }



    #endregion

    #region 接收字符控件

    /// <summary>

    /// 只接收字母

    /// </summary>

    public class HzjTextBoxChar : BaseTextBox

    {

        public HzjTextBoxChar()

        {

            this.MaxLength = 30;

        }



        protected override void OnKeyPress(KeyPressEventArgs e)

        {

            base.OnKeyPress(e);

            //转换为半角

            e.KeyChar = Hzj.HzjString.SBCcaseAndDBCcase.ConvertSBCcaseToDBCcase(e.KeyChar);

            if ((e.KeyChar >= 'A' && e.KeyChar <= 'Z') || (e.KeyChar >= 'a' && e.KeyChar <= 'z'))

            {

                e.Handled = false;

            }

            else

            {

                e.Handled = true;

            }

            if (e.KeyChar == Convert.ToChar(Keys.Back))

            {

                e.Handled = false;

            }

        }

        protected override void OnMouseDown(MouseEventArgs e)

        {

            base.OnMouseDown(e);

            //屏蔽右键粘贴

            Clipboard.Clear();

        }

        protected override void OnKeyDown(KeyEventArgs e)

        {

            //屏蔽Control + V粘贴

            base.OnKeyDown(e);

            if (e.Control && e.KeyCode == Keys.V)

            {

                Clipboard.Clear();

            }

        }

    }



    #endregion

    #region 屏蔽SQL敏感字符

    /// <summary>

    /// 过滤SQL敏感字符(单引号、空格、%、减号、=)

    /// </summary>

    public class HzjTextBoxSQL : BaseTextBox

    {

        public HzjTextBoxSQL()

        {

            this.MaxLength = 30;

        }

        protected override void OnKeyPress(KeyPressEventArgs e)

        {

            base.OnKeyPress(e);

            e.Handled = CheckTextBoxSqlChar(e);

        }

        protected override void OnMouseDown(MouseEventArgs e)

        {

            base.OnMouseDown(e);

            //屏蔽右键粘贴

            Clipboard.Clear();

        }

        protected override void OnKeyDown(KeyEventArgs e)

        {

            //屏蔽Control + V粘贴

            base.OnKeyDown(e);

            if (e.Control && e.KeyCode == Keys.V)

            {

                Clipboard.Clear();

            }

        }

    }



    #endregion

    #region 不接收指定字符控件

    /// <summary>

    /// 过滤设定的特殊字符

    /// </summary>

    public class HzjTextBoxSpecial : BaseTextBox

    {

        //待过滤字符数组

        char[] chars;

        [Category("设置"),

Description("设置待过滤的字符"),

DefaultValue(false)]



        /// <summary>

        /// 待过滤字符

        /// </summary>

        public char[] SpecialChar

        {

            get

            {

                return chars;

            }

            set

            {

                chars = value;

            }

        }

        protected override void OnKeyPress(KeyPressEventArgs e)

        {

            base.OnKeyPress(e);

            e.Handled = CheckTextBoxChars(chars, e);

        }

        /// <summary>

        /// 重写OnMouseDown事件,屏蔽右键粘贴功能

        /// </summary>

        /// <param name="e"></param>

        protected override void OnMouseDown(MouseEventArgs e)

        {

            base.OnMouseDown(e);

            //屏蔽右键粘贴

            Clipboard.Clear();

        }

        /// <summary>

        /// 重写OnKeyDown事件,屏蔽Control + V粘贴

        /// </summary>

        /// <param name="e"></param>

        protected override void OnKeyDown(KeyEventArgs e)

        {

            //屏蔽Control + V粘贴

            base.OnKeyDown(e);

            if (e.Control && e.KeyCode == Keys.V)

            {

                Clipboard.Clear();

            }

        }



    }



    #endregion

    #region 密码控件

    public class HzjTextBoxPassWord : HzjTextBoxSQL

    {

        public HzjTextBoxPassWord()

        {

            this.Text = "密码";

            this.MaxLength = 30;

        }

        protected override void OnLeave(EventArgs e)

        {

            base.OnLeave(e);

            if (Hzj.HzjString.Check.isbland(this.Text.ToString()) || this.Text == "密码")

            {

                this.Text = "密码";

                this.PasswordChar = '/0';

            }

        }

        protected override void OnKeyPress(KeyPressEventArgs e)

        {

            base.OnKeyPress(e);

            this.PasswordChar = '●';

        }

        protected override void OnGotFocus(EventArgs e)

        {

            base.OnGotFocus(e);

            this.BackColor = System.Drawing.Color.FromArgb(255, 255, 136);

            this.ForeColor = System.Drawing.Color.Black;

            if (this.Text == "密码")

                this.Text = "";



        }

        protected override void OnLostFocus(EventArgs e)

        {

            base.OnLostFocus(e);

            this.BackColor = System.Drawing.Color.White;

        }

    }

    #endregion

    #region 实现多种格式的验证控件

    public class HzjTextBox : BaseTextBox

    {

        //定义一个类型用于处理内部

        Validity m_CheckList;

        bool m_Check = false;

        //定义一个枚举类,设置属性的取值范围

        public enum Validity { None = 0, Email = 1, Tel = 2, Ip = 3, Decimal = 4, Date = 5, ChinaCard = 6 };



        public HzjTextBox()

        {



        }

        //定义属性

        [Category("设置"),

        Description("选择待验证的类型"),

        DefaultValue(null)]

        public Validity ValType

        {

            get

            {

                return m_CheckList;

            }

            set

            {

                m_CheckList = value;

            }



        }

        [Category("设置"),

        Description("设置为True时自动验证,否则不进行验证"),

        DefaultValue(false)]

        public bool Checked

        {

            get

            {

                return m_Check;

            }

            set

            {

                m_Check = value;

            }

        }



        /// <summary>

        /// 检测函数

        /// </summary>

        /// <param name="CheckList"></param>

        /// <returns></returns>

        private bool DataVal(Validity CheckList)

        {

            bool flage = false;     //成功标志



            switch (CheckList)

            {

                case Validity.None:

                    flage = true;

                    break;

                case Validity.Email:

                    flage = Hzj.HzjString.Check.IsValidEmail(this.Text);

                    break;

                case Validity.Tel:

                    flage = Hzj.HzjString.Check.IsValidTel(this.Text);

                    break;

                case Validity.Ip:

                    flage = Hzj.HzjString.Check.IsValidIp(this.Text);

                    break;

                case Validity.Decimal:

                    flage = Hzj.HzjString.Check.IsValidDecimal(this.Text);

                    break;

                case Validity.Date:

                    flage = Hzj.HzjString.Check.IsValidDate(this.Text);

                    break;

                case Validity.ChinaCard:

                    flage = Hzj.HzjString.Check.CheckIDCard(this.Text);

                    break;

                default:

                    flage = true;

                    break;

            }

            return flage;

        }

        /// <summary>

        /// 重写OnLeave事件,进行数据验证

        /// </summary>

        /// <param name="e"></param>

        protected override void OnLeave(EventArgs e)

        {

            base.OnLostFocus(e);

            //检测是否有字符,有字符则检测,没有则不进行检测

            if (!Hzj.HzjString.Check.isbland(this.Text))

            {

                if (!DataVal(m_CheckList))

                {

                    MessageBox.Show("验证失败,请输入正确的格式.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    this.Text = "";

                    this.Focus();

                    return;

                }

            }

        }

    }

    #endregion



    public class HzjValTextBox : BaseTextBox

    {

        //定义一个用于存放待执行的事件哈西表

        Hashtable hstab = new Hashtable();



        private char[] chars;

        //是否只能输入数字,包括小数点

        private bool m_CheckNumber = false;

        //是否只接收字母

        private bool m_CheckChar = false;

        //是否过滤SQL敏感字符

        private bool m_CheckSQLChar = false;

        //是否过滤指定的字符

        private bool m_CheckSpeChar = false;

        //是否允许进行复制粘贴

        private bool m_CopyPaste = false;

        //是否自动将全角字符转换为半角

        private bool m_AutoChangeChars = false;

        //是否自动将小写字母转换为大写字母

        private bool m_AutoUpper = false;

        //定义属性



        [Category("设置"),

Description("设置待过滤的字符"),

DefaultValue(false)]



        /// <summary>

        /// 待过滤字符

        /// </summary>

        public char[] SpecialChar

        {

            get

            {

                return chars;

            }

            set

            {

                chars = value;

            }

        }

        [Category("设置"),

        Description("只接收数字,包括小数点"),

        DefaultValue(false)]



        public bool CheckNumber

        {

            get

            {

                return m_CheckNumber;

            }

            set

            {

                m_CheckNumber = value;

            }

        }

        //定义属性

        [Category("设置"),

        Description("只接收大小写字母"),

        DefaultValue(false)]



        public bool CheckChar

        {

            get

            {

                return m_CheckChar;

            }

            set

            {

                m_CheckChar = value;

            }

        }

        //定义属性

        [Category("设置"),

        Description("过滤SQL敏感字符"),

        DefaultValue(false)]

        public bool CheckSQLChar

        {

            get

            {

                return m_CheckSQLChar;

            }

            set

            {

                m_CheckSQLChar = value;

            }

        }

        //定义属性

        [Category("设置"),

        Description("过滤指定字符"),

        DefaultValue(false)]

        public bool CheckSpeChar

        {

            get

            {

                return m_CheckSpeChar;

            }

            set

            {

                m_CheckSpeChar = value;

            }

        }

        //定义属性

        [Category("设置"),

        Description("是否允许进行复制粘贴"),

        DefaultValue(false)]

        public bool CopyPaste

        {

            get

            {

                return m_CopyPaste;

            }

            set

            {

                m_CopyPaste = value;

            }

        }

        //定义属性

        [Category("设置"),

        Description("是否自动将全角字符转换为半角"),

        DefaultValue(false)]

        public bool AutoChangeChars

        {

            get

            {

                return m_AutoChangeChars;

            }

            set

            {

                m_AutoChangeChars = value;

            }

        }

        //定义属性

        [Category("设置"),

        Description("是否自动将小写字母转换为大写"),

        DefaultValue(false)]

        public bool AutoUpper

        {

            get

            {

                return m_AutoUpper;

            }

            set

            {

                m_AutoUpper = value;

            }

        }

        protected override void OnKeyPress(KeyPressEventArgs e)

        {

            base.OnKeyPress(e);

            //自动将全角字符转换为半角

            if (m_AutoChangeChars)

            {

                e.KeyChar = Hzj.HzjString.SBCcaseAndDBCcase.ConvertSBCcaseToDBCcase(e.KeyChar);

            }

            //自动将小写转转为大写

            if (m_AutoUpper)

            {

                e.KeyChar = char.ToUpper(e.KeyChar);

                //return;

            }

            //指定字符

            if (m_CheckSpeChar)

            {

                e.Handled = CheckTextBoxChars(chars, e);

                if (e.Handled)

                    return;

            }



            //SQL敏感字符处理

            if (m_CheckSQLChar)

            {

                e.Handled = CheckTextBoxSqlChar(e);

                if (e.Handled)

                    return;

            }



            //检测数字

            if (m_CheckNumber)

            {

                e.Handled = CheckTextBoxNum(e);

                if (!e.Handled)

                    return;

            }

            //检测字母

            if (m_CheckChar)

            {

                e.Handled = CheckTextBoxChar(e);

                if (!e.Handled)

                    return;

            }

            //数字和字母

            if (m_CheckChar && m_CheckNumber)

            {

                e.Handled = CheckTextBoxCharNum(e);

                if (!e.Handled)

                    return;

            }



        }

        protected override void OnMouseDown(MouseEventArgs e)

        {

            base.OnMouseDown(e);

            //屏蔽右键粘贴

            if (!m_CopyPaste)

                Clipboard.Clear();

        }

        /// <summary>

        /// 重写OnKeyDown事件,屏蔽Control + V粘贴

        /// </summary>

        /// <param name="e"></param>

        protected override void OnKeyDown(KeyEventArgs e)

        {

            //屏蔽Control + V粘贴

            base.OnKeyDown(e);

            if (e.Control && e.KeyCode == Keys.V && !m_CopyPaste)

            {

                Clipboard.Clear();

            }

        }

        protected override void OnLeave(EventArgs e)

        {

            base.OnLeave(e);

            if (!Hzj.HzjString.Check.isbland(this.Text.ToString().Trim()) && m_CheckNumber)

            {

                try

                {

                    Convert.ToDecimal(this.Text.ToString());

                }

                catch

                {

                    MessageBox.Show("非法数字,请重新输入.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    this.Text = "0.00";

                    this.Focus();

                    return;

                }

            }

        }

    }

}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值