C # Winform custom control --TextBox

effect:
 
description:
Similarly html tag input tag of placeHolder property, control inherits TextBox, have a descriptive prompt field _txtPlaceHolder information, rewriting the message processing function WndProc, if the message is sent out of the windows draw the control, began to draw to note here is TxtPlaceHolder Set methods in the this.Invalidate (); this is a failure if the controls are drawn, will redraw draw, if not this code, drag this control onto a form, the controls will be reported anomalies.
abnormal:
the reason:
After my experiment, I found that as long as _txtPlaceHolder this field is assigned a null value is not removed after the initial "this.Invalidate ();" phrase, the program can run. The reason is _txtPlaceHolder.Length> 0
Code:
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);
                }
            }
        }
    }

  


 
 

Guess you like

Origin www.cnblogs.com/HelloQLQ/p/11285766.html