Create 2 identical text boxes on a windows form. Name them "RealTextBox" (set tab index to 1) and "WatermarkTextBox" (set tab index to 0, set fore color to gray). Position WatermarkTextBox exactly on top of RealTextBox, so that the latter is not visible. Create a "TextChanged event" for each text box (see code below) and a string field "watermark" to hold the watermark text. Create a "Click event" for the WatermarkTextBox. When the text box is clicked by the user, this event makes sure that the watermark text and the caret remain the same.
When the form is loaded, the WatermarkTextBox shows the watermark text and the caret is blinking in front of it. When the first character is typed, it is copied to the RealTextBox, the WatermarkTextBox is set to "invisible" and the caret is positioned after the character in the RealTextBox where the typing can be continued.
If the text in the RealTextBox is removed, the form goes back to the initial state.
My solution in code:
using System;
using System.Windows.Forms;
namespace WatermarkTextBox
{
public partial class TestForm : Form
{
string watermark = "Type here...";
public TestForm()
{
InitializeComponent();
WatermarkTextBox.Text = watermark;
WatermarkTextBox.Select(0, 0);
}
private void WatermarkTextBox_TextChanged(object sender, EventArgs e)
{
RealTextBox.Text = WatermarkTextBox.Text.Substring(0, 1);
WatermarkTextBox.Visible = false;
RealTextBox.Select(1, 0);
}
private void RealTextBox_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(RealTextBox.Text))
{
WatermarkTextBox.Text = watermark;
WatermarkTextBox.Visible = true;
WatermarkTextBox.Focus();
WatermarkTextBox.Select(0, 0);
}
}
private void WatermarkTextBox_Click(object sender, EventArgs e)
{
WatermarkTextBox.Text = watermark;
WatermarkTextBox.Select(0, 0);
}
}
}