TextBox with a cue

 Posted by  Programming  Add comments  Tagged with:
Mar 132013
 

TextBox cuesOn web it became very popular to have gray, watermarked, text that offers a cue for filling out a field. As you start writing, cue disappears.

For a while now, Windows have full support of this feature. However, Windows Forms in .NET framework are bit behind. Fortunately implementing this feature is not really hard. All we need is property (e.g. CueText) in a class inherited from TextBox.

Setting value is done by sending a EM_SETCUEBANNER message to TextBox:

NativeMethods.SendMessage(this.Handle,
                          EM_SETCUEBANNER,
                          new IntPtr(1),
                          new StringBuilder(value));

There is no need to check this function for success. If visual styles are turned on, it will not fail. And even if it fails, there is not a thing we can do to fix it. Ignoring result code is as good solution as any.

Retrieving value via EM_GETCUEBANNER is a bit more involved:

var text = new StringBuilder(256);
var res = NativeMethods.SendMessage(this.Handle,
                                    EM_GETCUEBANNER,
                                    text,
                                    new IntPtr(text.Capacity));
if (res.ToInt64() != 0) {
    return text.ToString();
} else {
    return null;
}

This time check for valid result is warranted. If result is good, string will be returned. Otherwise, null gets to mess things up.

These few lines (along with Interop definitions) are all that is needed for this useful functionality.

Sample project is available for download.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>