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
.NET Framework
Here is an implementation of a TextBox
which supports showing hint (or watermark or cue):
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:
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.