c#: TextBox添加水印效果(PlaceHolderText)

基于他人代码修改,不闪,以做备忘。

与SendMessage EM_SETCUEBANNER消息相比,它能改变字体绘制颜色,EM_SETCUEBANNER只限定了DimGray颜色,太深

    //与SendMessage EM_SETCUEBANNER消息相比,它能改变字体绘制颜色,EM_SETCUEBANNER只限定了DimGray颜色,太深
    [ToolboxBitmap(typeof(TextBox))]
    public class TextBoxEx : TextBox
    {
        private const int WM_PAINT = 0xF;
        private Color placeHolderColor = Color.Gray;
        private string placeHolderText;

        [DefaultValue("")]
        [Localizable(true)]
        [Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
        public string PlaceHolderText
        {
            get { return this.placeHolderText; }
            set
            {
                this.placeHolderText = value;
                Invalidate();
            }
        }

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            if (m.Msg == WM_PAINT)
                WmPaint(ref m);
        }

        private void WmPaint(ref Message m)
        {
            if (!string.IsNullOrEmpty(this.Text) || string.IsNullOrEmpty(this.placeHolderText) || Focused)
                return;

            using (var g = Graphics.FromHwnd(this.Handle))
            {
                var flag = TextFormatFlags.EndEllipsis;
                //它反着来
                if (RightToLeft == RightToLeft.Yes)
                {
                    if (TextAlign == HorizontalAlignment.Left)
                        flag |= TextFormatFlags.Right;
                    else if (TextAlign == HorizontalAlignment.Right)
                        flag |= TextFormatFlags.Left;
                }
                else
                {
                    switch (TextAlign)
                    {
                        case HorizontalAlignment.Center:
                            flag |= TextFormatFlags.HorizontalCenter;
                            break;
                        case HorizontalAlignment.Right:
                            flag |= TextFormatFlags.Right;
                            break;
                        default:
                            break;
                    }
                }

                var r = this.ClientRectangle;
                r.Offset(-1, 1);
                TextRenderer.DrawText(
                    g,
                    this.placeHolderText,
                    Font,
                    r,
                    this.placeHolderColor,
                    flag
                );
            }
        }
    }

效果如图:

参考资料:

C# WinForm TextBox添加水印效果 - ZCoding - 博客园

猜你喜欢

转载自www.cnblogs.com/crwy/p/10595308.html