Click here to Skip to main content
15,881,757 members
Articles / Desktop Programming / Windows Forms
Article

C# TextBox with Outlook 2007-style prompt

Rate me:
Please Sign up or sign in to vote.
4.72/5 (39 votes)
16 Oct 2006CPOL5 min read 236.2K   3.3K   150   54
An article on creating a prompted textbox in the style of Outlook 2007, IE7, and Firefox 2.0.

PromptedTextBox Sample

Introduction

You've probably seen these types of textboxes on your travels around the web, such as the eBay search box, which is a textbox with a prompt in it like "Enter your search string here". As soon as you click in the box, the prompt disappears, leaving an empty textbox where you can type your search string. Microsoft even has an AJAX example of this control on their Atlas web site, called the TextBoxWatermark control.

More recently, this type of control has started to appear in Windows applications like Outlook 2007, IE7, and also Firefox 2.0. This control can be very handy, as it basically works like a Textbox and a Label in one control without taking up a bunch of screen real estate. On the web, this nifty feature is usually handled by using JavaScript, but on Windows, we're left to our own devices to come up with something that provides the same functionality.

Background

In a web application, the developer would typically add JavaScript code to the onBlur and onFocus events in order to put the prompt in the TextBox. The developer must also be aware that the form submit (or "postback" in ASP.NET) may cause the prompt text to be included in the postdata, so the code must be aware of this. In addition, the JavaScript code is forced to manipulate the "value" property of the TextBox in order to accomplish this, so even the JavaScript solution has a "hack" feel to it.

The standard WinForms TextBox does not support this functionality natively, so this class will address that shortcoming by inheriting from System.Windows.Forms.TextBox and handling the display of the prompt text ourselves.

Using the code

Overriding the WndProc may seem like overkill, but in this case the code turns out to be fairly simple. For this control, we only need to be concerned about the WM_SETFOCUS and WM_KILLFOCUS messages, which should be the same as the GotFocus and SetFocus events, and WM_PAINT:

C#
protected override void WndProc(ref System.Windows.Forms.Message m)
{
    switch (m.Msg)
    {
        case WM_SETFOCUS:
            _drawPrompt = false;
            break;

        case WM_KILLFOCUS:
            _drawPrompt = true;
            break;
    }

    base.WndProc(ref m);

    // Only draw the prompt on the WM_PAINT event
    // and when the Text property is empty
    if (m.Msg == WM_PAINT && _drawPrompt && this.Text.Length == 0 && 
                      !this.GetStyle(ControlStyles.UserPaint))
        DrawTextPrompt();
}

DrawTextPrompt does most of the work. It determines the client rectangle in which to draw the prompt and any offset based on the HorizontalAlignment, then uses TextRenderer to draw the PromptText inside the rectangle:

C#
protected virtual void DrawTextPrompt(Graphics g)
{
    TextFormatFlags flags = TextFormatFlags.NoPadding | 
      TextFormatFlags.Top | TextFormatFlags.EndEllipsis;
    Rectangle rect = this.ClientRectangle;

    // Offset the rectangle based on the HorizontalAlignment, 
    // otherwise the display looks a little strange
    switch (this.TextAlign)
    {
        case HorizontalAlignment.Center:
            flags = flags | TextFormatFlags.HorizontalCenter;
            rect.Offset(0, 1);
            break;

        case HorizontalAlignment.Left:
            flags = flags | TextFormatFlags.Left;
            rect.Offset(1, 1);
            break;

        case HorizontalAlignment.Right:
            flags = flags | TextFormatFlags.Right;
            rect.Offset(0, 1);
            break;
    }

    // Draw the prompt text using TextRenderer
    TextRenderer.DrawText(g, _promptText, this.Font, rect, 
                      _promptColor, this.BackColor, flags);
}

Points of Interest

My first thought when tackling this control was to override OnGotFocus/OnLostFocus and just swap the Text and PromptText values (in addition to changing the ForeColor). This immediately turned out to be a bad idea, because as soon as I tested it I noticed that the Text property at design-time was suddenly replaced with the PromptText (and so was the ForeColor replaced with the PromptForeColor). This effectively removed the ability for the developer to set a default Text value, so it was time for a new approach.

After mulling over a couple of alternatives, I decided to override the OnPaint method and just manually draw the prompt over top of the TextBox region. This would solve the "hack" nature of trying to manipulate the Text/ForeColor properties. So I developed the DrawTextPrompt function and added a call in OnPaint. Unfortunately, this also turned out to be a problematic solution (and I have left the code in so you can test it for yourself). The prompt would simply not draw properly over top of the TextBox, displaying various weird behaviors such as disappearing text, incorrect fonts, etc. My first thought was that I had coded DrawTextPrompt incorrectly, but a simple test showed that it was indeed drawing the prompt correctly.

So after pulling my hair out some more, I finally rolled up my sleeves and decided to override WndProc. I knew that I would have to figure out which message was the key to the solution (WM_PAINT was the obvious choice, but wasn't that what OnPaint was supposed to do?). After a few hours of frustration, and not having any other candidates, I decided to try and see if WM_PAINT would produce any different results. So I added the call to DrawTextPrompt and, lo and behold, it worked!!! I don't yet have an explanation as to why WM_PAINT works and OnPaint doesn't, but you can try it for yourself by un-commenting the SetStyle line in the constructor. My working theory is that the SetStyle call disables additional behavior that I have not accounted for.

As you go through the code, notice all the places where there is a call to Invalidate(). This is so the control will redraw itself as the design-time properties change. The control should behave the same at design-time as it does at run-time. If there is a value in the Text property, the PromptText will not be displayed. If you change the PromptText, PromptForeColor or the TextAlign properties, the control should change right away.

I also added a FocusSelect boolean property (a feature I have longed for since VB3, where inheritance was not an option) that, when set to true, will select all the text in the control when it receives the focus.

Compared to EM_SETCUEBANNER

As pointed out in the user comments below, Windows XP and newer has a message that you can send to a TextBox control that will accomplish almost the same goal, and that is EM_SETCUEBANNER. Using this message has a few advantages:

  • Also supported by the ComboBox control
  • Forward compatibility with future versions of Windows
  • Better support for different UI enhancements and layouts, including things like themes, Aero, TabletPC, etc.

But, there are also some disadvantages:

  • Only supported on Windows XP and newer.
  • Windows CE/Mobile is not supported.
  • Doesn't work with a multiline TextBox.
  • Developer must also include a manifest for Comctl32.dll with the EXE.
  • Developer has no control over the prompt's font properties or color.
  • Apparently, there is a bug that causes EM_SETCUEBANNER not to work if you install one of the Asian language packs on XP.

I haven't verified that PromptedTextBox runs on all the older platforms (or CE), but the approach doesn't require anything special. In fact, the theory should apply as far back as Windows 3.1, but of course .NET only supports Windows 98 and above.

In short, if you find a situation where PromptedTextBox doesn't behave as expected and you have the option, see if EM_SETCUEBANNER will do the trick. If not, drop me a line and I will see what I can do.

Release History

  • Version 1.0: 04-Oct-2006 - Initial posting.
  • Version 1.1: 16-Oct-2006 - Added the PromptFont property to allow more developer control of the prompt display. Also changed the default prompt color to SystemColors.GrayText.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
I have been a software developer for almost 20 years, focusing primarily on Microsoft based technologies. I recently started my own consulting company and haven't looked back.

I also developed a product called EasyObjects.NET to enable developers to produce better code in a shorter time frame.

Comments and Discussions

 
GeneralGotFocus override and resetting during designtime Pin
Ajek25-Oct-06 8:37
Ajek25-Oct-06 8:37 
QuestionDid you check EM_SETCUEBANNER ? Pin
Axel Rietschin14-Oct-06 8:30
professionalAxel Rietschin14-Oct-06 8:30 
AnswerRe: Did you check EM_SETCUEBANNER ? Pin
Matthew Noonan14-Oct-06 16:19
Matthew Noonan14-Oct-06 16:19 
GeneralRe: Did you check EM_SETCUEBANNER ? Pin
Axel Rietschin15-Oct-06 1:23
professionalAxel Rietschin15-Oct-06 1:23 
GeneralRe: Did you check EM_SETCUEBANNER ? Pin
Matthew Noonan15-Oct-06 4:36
Matthew Noonan15-Oct-06 4:36 
GeneralRe: Just in case anyone is interested... Pin
Axel Rietschin25-Oct-06 13:00
professionalAxel Rietschin25-Oct-06 13:00 
GeneralRe: Just in case anyone is interested... Pin
ArneKruger26-Oct-06 3:10
ArneKruger26-Oct-06 3:10 
GeneralRe: Just in case anyone is interested... Pin
Matthew Noonan26-Oct-06 4:09
Matthew Noonan26-Oct-06 4:09 
You have to include a manifest with your executable, as described in this article:
http://vbnet.mvps.org/index.html?code/textapi/setcuebanner.htm

Also, as I stated in the article, there are several limitations to this approach.


GeneralRe: Just in case anyone is interested... Pin
Axel Rietschin26-Oct-06 5:41
professionalAxel Rietschin26-Oct-06 5:41 
GeneralRe: Just in case anyone is interested... Pin
Matthew Noonan26-Oct-06 7:44
Matthew Noonan26-Oct-06 7:44 
GeneralRe: Just in case anyone is interested... Pin
rbirnesser26-Oct-06 7:11
rbirnesser26-Oct-06 7:11 
GeneralRe: Just in case anyone is interested... Pin
Matthew Noonan26-Oct-06 7:48
Matthew Noonan26-Oct-06 7:48 
GeneralSuggestion about text color Pin
Styx3112-Oct-06 23:01
Styx3112-Oct-06 23:01 
GeneralRe: Suggestion about text color Pin
Matthew Noonan13-Oct-06 4:07
Matthew Noonan13-Oct-06 4:07 
AnswerRe: Suggestion about text color Pin
Matthew Noonan16-Oct-06 11:24
Matthew Noonan16-Oct-06 11:24 
GeneralThanks and Suggestion Pin
davepermen12-Oct-06 22:11
davepermen12-Oct-06 22:11 
GeneralRe: Thanks and Suggestion Pin
Matthew Noonan13-Oct-06 4:08
Matthew Noonan13-Oct-06 4:08 
AnswerRe: Thanks and Suggestion Pin
Matthew Noonan16-Oct-06 11:22
Matthew Noonan16-Oct-06 11:22 
GeneralRe: Thanks and Suggestion Pin
davepermen16-Oct-06 14:03
davepermen16-Oct-06 14:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.