Watermark TextBox in WinForms

前端 未结 10 1848
说谎
说谎 2020-11-22 00:35

Can anyone point me to a good implementation of a basic Windows Forms TextBox that will initially show watermark text that disappears when the cursor enters it? I think I ca

10条回答
  •  忘了有多久
    2020-11-22 01:01

    .NET Framework

    Here is an implementation of a TextBox which supports showing hint (or watermark or cue):

    • It also shows the hint when MultiLine is true.
    • It's based on handling WM_PAINT message and drawing the hint. So you can simply customize the hint and add some properties like hint color, or you can draw it right to left or control when to show the hint.
    using System.Drawing;
    using System.Windows.Forms;
    public class ExTextBox : TextBox
    {
        string hint;
        public string Hint
        {
            get { return hint; }
            set { hint = value; this.Invalidate(); }
        }
        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            if (m.Msg == 0xf)
            {
                if (!this.Focused && string.IsNullOrEmpty(this.Text)
                    && !string.IsNullOrEmpty(this.Hint))
                {
                    using (var g = this.CreateGraphics())
                    {
                        TextRenderer.DrawText(g, this.Hint, this.Font,
                            this.ClientRectangle, SystemColors.GrayText , this.BackColor, 
                            TextFormatFlags.Top | TextFormatFlags.Left);
                    }
                }
            }
        }
    }
    

    If you use EM_SETCUEBANNER, then there will be 2 issues. The text always will be shown in a system default color. Also the text will not be shown when the TextBox is MultiLine.

    Using the painting solution, you can show the text with any color that you want. You also can show the watermark when the control is multi-line:

    Download

    You can clone or download the working example:

    • Download Zip
    • Github repository

    .NET CORE - TextBox.PlaceholderText

    The same approach has been used in .NET CORE implementation of TextBox and in Windows Forms .NET CORE, you can use PlaceholderText property.

    It supports both multi-line and single-line text-box.

提交回复
热议问题