I'm working on a C# winforms application (VS.NET 2008, .NET 3.5 sp 1). I have a search field on a form, and rather than have a label next to the search field I'd like to show some grey text in the background of the search field itself ('Search terms', for example). When the user starts entering text in the search field the text should disappear. How can I achieve this?
You will need to use some P/Inovke interop code to do this. Look for the Win32 API SendMessage function and the EM_SETCUEBANNER message.
There is built-in functionality in the text box control -- AutoCompleteMode and AutoCompleteSource. They may be worth a try before you go into custom or 3rd party controls.
Give the code from this link a try. It extends the winforms functionality, as it isn't possible to achieve right out of the box. The source code is available as well. Keep in mind, it only works on Win XP or higher.
http://www.aaronlerch.com/blog/2007/12/01/watermarked-edit-controls/
I think the way this is generally done is to set the color of the text to gray and prefill it with your hint text.
Then, write handlers for the text field's focus events, modifying the fields contents and color based when focus is gained and lost. Here's some pseudocode (sorry, it's totally not C# code. I have Actionscript on the brain right now):
TextInput myInput;
boolean showingHint = true;
myInput.text = "Search Terms";
myInput.color = 0xcccccc;
myInput.onFocusGained = function() {
if(showingHint) {
myInput.text = "";
myInput.color = 0x000000;
showingHint = false;
}
}
myInput.onFocusLost = function() {
if(!showingHint && myInput.text.length == 0) {
myInput.text = "Search Terms";
myInput.color = 0xcccccc;
showingHint = true;
}
}
Remember, you only want to change the text on focus lost if the user hasn't manually changed the text. Use a separate boolean to track if you're showing the hint or not so you can differentiate between the user manually typing your "hint" text as actual content. Similarly, you only want to clear the contents of the input box if the hint is being displayed so you don't get rid of user input accidentally.
Thanks, Scott. That did the trick perfectly. Looking up EM_SETCUEBANNER I found this article which went into some more detail.