BigBug
BigBug

Reputation: 6290

C#.net WinForms how to causes text in textbox to disappear when textbox is on focus?

is there a way in which i could create light grey text that disappears when a textbox is on focus?

Currently, i have text written in the textbox but i have to select the text and manually delete it (somewhat annoying...)

I know i can do something when i get focus on the box (using events) however, i don't want it to clear the text every time the user selects that box... rather just the first time. In other words, i just want the hint text to disappear (not the text they enter if they were to select the box after typing in it once)...

I also realize i could use something like a counter to keep track of if it's the first time that box is being clicked on.. however, i was looking for a cleaner way to do this.....

Upvotes: 1

Views: 2872

Answers (2)

HerbF
HerbF

Reputation: 21

A simpler answer is

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint msg, uint wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);

public static void SetHint(TextBox textBox, string hintText)
{
 const uint EmSetCueBanner = 0x1501;
 SendMessage(textBox.Handle, EmSetCueBanner, 0, hintText);
}

Upvotes: 2

Manish Basantani
Manish Basantani

Reputation: 17499

Something like the code below. Please note, this is not a compiled code. Just sharing the idea, plus you may like to retain the default settings if user did not enter any text. For that handle a lost focus and reset to default.

   public class FancyTextBox : TextBox{

private bool _isDefaultText;
public FancyTextBox(){
     UpdateDefaultSettings(true);         
}

protected override void OnGotFocus(EventArgs e)
{
    base.OnGotFocus(e);
    UpdateDefaultSettings(false);
}

protected override void OnLostFocus(EventArgs e)
{
    base.OnLostFocus(e);
    if (String.IsNullOrEmpty(Text))
    {
        //Retain Default Setting.
        UpdateDefaultSettings(true);
    }
}

private void UpdateDefaultSettings(bool isDefault){
    _isDefaultText = isDefault;
    if(_isDefaultText){
       Text = "Please enter";
       this.ForeColor= Color.Gray;  
    }
    else{
       Text = "";
       ForeColor = Color.Black;
    }
}    

}

Upvotes: 3

Related Questions