欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# Winform 自定义控件——TextBox

程序员文章站 2023-10-28 19:57:28
C# winform 自定义控件之TextBox改PromtedTextBox 类似html标签里input标签里的placeHolder属性,控件继承TextBox,拥有一个描述提示信息的字段_txtPlaceHolder,重写了消息处理函数WndProc,如果windows送出来的消息是绘制控件... ......
效果:
C# Winform 自定义控件——TextBox 
描述:
类似html标签里input标签里的placeholder属性,控件继承textbox,拥有一个描述提示信息的字段_txtplaceholder,重写了消息处理函数wndproc,如果windows送出来的消息是绘制控件,就开始绘制,这里要注意的是txtplaceholder的set方法里的this.invalidate();这个是如果控件绘制失败,将重绘绘制,如果没有这句代码,拖动这个控件到窗体上,控件会报异常。
异常:
C# Winform 自定义控件——TextBox
原因:
经过我的实验,我发现只要为_txtplaceholder这个字段赋个不为null的初始值后去掉”this.invalidate();“这句,程式也能运行。原因是_txtplaceholder.length > 0
代码:
public sealed class mycustomtextbox:textbox
    {
        private const int wm_paint = 0x000f;
        private string _txtplaceholder="";

        [category("自定义属性"), description("文本框里的提示文字"), defaultvalue("请在此输入"), browsable(true)]
        public string txtplaceholder
        {
            get { return _txtplaceholder; }
            set {
                if (value == null) throw new argumentnullexception("value");

                _txtplaceholder = value;
                this.invalidate();
            }
        }
        protected override void wndproc(ref message m)
        {
            base.wndproc(ref m);
            if (m.msg == wm_paint && !this.focused && (this.textlength == 0) && (_txtplaceholder.length > 0))
            {
                textformatflags tff = (textformatflags.endellipsis |
                    textformatflags.noprefix |
                    textformatflags.left |
                    textformatflags.top | textformatflags.nopadding);

                using (graphics g = this.creategraphics())
                {

                    rectangle rect = this.clientrectangle;

                    rect.offset(4, 1);

                    textrenderer.drawtext(g, _txtplaceholder, this.font, rect, systemcolors.graytext, tff);
                }
            }
        }
    }