[ToolboxBitmap(typeof(TextBox))]
    public class WatermarkTextBox : TextBox
    {
        private string _emptyTextTip;
        private Color _emptyTextTipColor = Color.DarkGray;
        private const int WM_PAINT = 0xF;

        public WatermarkTextBox()
            : base()
        {
        }

        [DefaultValue("")]
        public string EmptyTextTip
        {
            get { return _emptyTextTip; }
            set
            {
                _emptyTextTip = value;
                Invalidate();
            }
        }

        [DefaultValue(typeof(Color), "DarkGray")]
        public Color EmptyTextTipColor
        {
            get { return _emptyTextTipColor; }
            set
            {
                _emptyTextTipColor = value;
                Invalidate();
            }
        }

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

        private void WmPaint()
        {
            using (Graphics graphics = Graphics.FromHwnd(Handle))
            {
                if (Text.Length == 0
                    && !string.IsNullOrEmpty(_emptyTextTip)
                    && !Focused)
                {
                    TextFormatFlags format =
                        TextFormatFlags.EndEllipsis |
                        TextFormatFlags.VerticalCenter;

                    if (RightToLeft == RightToLeft.Yes)
                    {
                        format |= TextFormatFlags.RightToLeft | TextFormatFlags.Right;
                    }

                    TextRenderer.DrawText(
                        graphics,
                        _emptyTextTip,
                        Font,
                        ClientRectangle,
                        _emptyTextTipColor,
                        format);
                }
            }
        }
    }

 

相关文章:

  • 2021-10-27
  • 2022-01-11
  • 2022-12-23
  • 2021-07-13
  • 2022-12-23
猜你喜欢
  • 2021-11-16
  • 2022-12-23
  • 2022-01-08
  • 2022-12-23
  • 2022-12-23
  • 2021-08-08
  • 2021-12-17
相关资源
相似解决方案