using System; using System.Windows.Forms; using System.Diagnostics; using System.Drawing; using System.ComponentModel; public partial class TextBoxWithPrompt : TextBox { // originated at http://danielmoth.com/Blog protected override void OnGotFocus(EventArgs e) { base.OnGotFocus(e); if (this.UsePrompt) { this.UsePrompt = false; this.Text = string.Empty; } } protected override void OnLostFocus(EventArgs e) { if (this.TextLength == 0 || this.Text == this.TextPrompt) { this.UsePrompt = true; this.Text = this.TextPrompt; } base.OnLostFocus(e); } private string textPrompt = "enter a moth"; public string TextPrompt { get { return textPrompt; } set { textPrompt = value; if (this.UsePrompt && !string.IsNullOrEmpty(this.textPrompt)) { this.Text = value; } } } private bool usePrompt; private bool UsePrompt { get { return usePrompt; } set { usePrompt = value; if (usePrompt) { this.Font = new Font(this.Font.Name, this.Font.Size, FontStyle.Italic); this.ForeColor = Color.Gray; } else { // TODO don't hardcode the user given values. this.Font = new Font(this.Font.Name, this.Font.Size, FontStyle.Regular); this.ForeColor = Color.Black; } } } protected override void OnParentChanged(EventArgs e) { if (string.IsNullOrEmpty(this.Text)) { this.UsePrompt = true; this.Text = this.TextPrompt; } base.OnParentChanged(e); } public override string Text { get { if (this.UsePrompt) { return string.Empty; } return base.Text; } set { if (this.UsePrompt && (!string.IsNullOrEmpty(value) && value != this.TextPrompt)) { this.UsePrompt = false; } if (string.IsNullOrEmpty(value) && !this.Focused && !string.IsNullOrEmpty(this.textPrompt)) { this.UsePrompt = true; this.Text = this.TextPrompt; return; } base.Text = value; } } }