Click here to Skip to main content
11,566,092 members (49,983 online)
Click here to Skip to main content

C# TextBox with Outlook 2007-style prompt

, 16 Oct 2006 CPOL 169.6K 2.2K 150
Rate this:
Please Sign up or sign in to vote.
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:

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:

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)

Share

About the Author

Matthew Noonan
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.

You may also be interested in...

Comments and Discussions

 
QuestionMultiLine Text Pin
amith sai27-Jun-12 21:35
memberamith sai27-Jun-12 21:35 
GeneralCool! Pin
Diamonddrake17-Dec-10 8:15
memberDiamonddrake17-Dec-10 8:15 
GeneralMy vote of 4 Pin
sopheak.programming13-Nov-10 16:06
membersopheak.programming13-Nov-10 16:06 
GeneralThanks.... Pin
Arjen H.27-Sep-10 21:19
memberArjen H.27-Sep-10 21:19 
GeneralNIcely done Matt Pin
Elkay15-Mar-09 18:16
memberElkay15-Mar-09 18:16 
QuestionHow to do it for the System.Windows.Forms.ToolStripTextBox? Pin
Martin Radu9-Mar-08 11:06
memberMartin Radu9-Mar-08 11:06 
GeneralRe: How to do it for the System.Windows.Forms.ToolStripTextBox? Pin
Matthew Noonan9-Mar-08 11:43
memberMatthew Noonan9-Mar-08 11:43 
GeneralFocusSelect Pin
Johnny J.8-Nov-07 21:34
memberJohnny J.8-Nov-07 21:34 
GeneralRe: FocusSelect Pin
Johnny J.8-Nov-07 21:34
memberJohnny J.8-Nov-07 21:34 
QuestionHow to do it for the ComboBox Pin
Abo Yahya26-Oct-07 13:11
memberAbo Yahya26-Oct-07 13:11 
AnswerRe: How to do it for the ComboBox Pin
Matthew Noonan26-Oct-07 19:18
memberMatthew Noonan26-Oct-07 19:18 
GeneralRe: How to do it for the ComboBox Pin
Abo Yahya26-Oct-07 23:56
memberAbo Yahya26-Oct-07 23:56 
GeneralSuggestion: keep prompt until text entered Pin
mitooki6-Jul-07 5:51
membermitooki6-Jul-07 5:51 
GeneralRe: Suggestion: keep prompt until text entered Pin
k^s17-Sep-07 1:34
memberk^s17-Sep-07 1:34 
GeneralRe: Suggestion: keep prompt until text entered Pin
veritas guy7-Dec-07 11:16
memberveritas guy7-Dec-07 11:16 
GeneralPrompted text with MaskTextBox Pin
N U Reddy13-Jun-07 7:53
memberN U Reddy13-Jun-07 7:53 
GeneralRe: Prompted text with MaskTextBox Pin
Matthew Noonan19-Jun-07 11:32
memberMatthew Noonan19-Jun-07 11:32 
GeneralSuggestion Pin
Sk8tz23-May-07 22:29
memberSk8tz23-May-07 22:29 
GeneralRe: Suggestion Pin
N U Reddy13-Jun-07 7:56
memberN U Reddy13-Jun-07 7:56 
GeneralRe: Suggestion Pin
Matthew Noonan19-Jun-07 11:34
memberMatthew Noonan19-Jun-07 11:34 
GeneralAnother suggestion Pin
lextm19-Apr-07 20:59
memberlextm19-Apr-07 20:59 
GeneralRe: Another suggestion Pin
Matthew Noonan19-Jun-07 11:38
memberMatthew Noonan19-Jun-07 11:38 
QuestionNot working for Windows 2000 Pin
Jason Law21-Jan-07 20:30
memberJason Law21-Jan-07 20:30 
AnswerRe: Not working for Windows 2000 Pin
Matthew Noonan5-Feb-07 14:12
memberMatthew Noonan5-Feb-07 14:12 
GeneralRe: Not working for Windows 2000 Pin
vachaun26-Apr-07 5:55
membervachaun26-Apr-07 5:55 
GeneralRe: Not working for Windows 2000 Pin
Matthew Noonan19-Jun-07 11:40
memberMatthew Noonan19-Jun-07 11:40 
GeneralDoes not work for Multiline textboxes.... Pin
Vampman27-Nov-06 11:04
memberVampman27-Nov-06 11:04 
GeneralRe: Does not work for Multiline textboxes.... Pin
Matthew Noonan28-Nov-06 12:35
memberMatthew Noonan28-Nov-06 12:35 
GeneralRe: Does not work for Multiline textboxes.... Pin
Vampman30-Nov-06 10:37
memberVampman30-Nov-06 10:37 
GeneralRe: Does not work for Multiline textboxes.... Pin
MartynUK8-May-08 23:58
memberMartynUK8-May-08 23:58 
GeneralRe: Does not work for Multiline textboxes.... Pin
Member 198666516-Jul-08 22:37
memberMember 198666516-Jul-08 22:37 
GeneralRe: Does not work for Multiline textboxes.... Pin
Termitehed19-Nov-08 6:34
memberTermitehed19-Nov-08 6:34 
GeneralExcellent work! Pin
Joseph S. Keller21-Nov-06 11:04
memberJoseph S. Keller21-Nov-06 11:04 
GeneralTextFormatFlags and RightToLeft alignment Pin
Laurent Muller29-Oct-06 22:55
memberLaurent Muller29-Oct-06 22:55 
GeneralRe: TextFormatFlags and RightToLeft alignment Pin
Matthew Noonan31-Oct-06 0:56
memberMatthew Noonan31-Oct-06 0:56 
GeneralGotFocus override and resetting during designtime Pin
Ajek25-Oct-06 8:37
memberAjek25-Oct-06 8:37 
QuestionDid you check EM_SETCUEBANNER ? Pin
axelriet14-Oct-06 8:30
memberaxelriet14-Oct-06 8:30 
AnswerRe: Did you check EM_SETCUEBANNER ? Pin
Matthew Noonan14-Oct-06 16:19
memberMatthew Noonan14-Oct-06 16:19 
GeneralRe: Did you check EM_SETCUEBANNER ? Pin
axelriet15-Oct-06 1:23
memberaxelriet15-Oct-06 1:23 
GeneralRe: Did you check EM_SETCUEBANNER ? Pin
Matthew Noonan15-Oct-06 4:36
memberMatthew Noonan15-Oct-06 4:36 
GeneralRe: Just in case anyone is interested... Pin
axelriet25-Oct-06 13:00
memberaxelriet25-Oct-06 13:00 
GeneralRe: Just in case anyone is interested... Pin
ArneKruger26-Oct-06 3:10
memberArneKruger26-Oct-06 3:10 
GeneralRe: Just in case anyone is interested... Pin
Matthew Noonan26-Oct-06 4:09
memberMatthew Noonan26-Oct-06 4:09 
GeneralRe: Just in case anyone is interested... Pin
axelriet26-Oct-06 5:41
memberaxelriet26-Oct-06 5:41 
GeneralRe: Just in case anyone is interested... Pin
Matthew Noonan26-Oct-06 7:44
memberMatthew Noonan26-Oct-06 7:44 
GeneralRe: Just in case anyone is interested... Pin
rbirnesser26-Oct-06 7:11
memberrbirnesser26-Oct-06 7:11 
GeneralRe: Just in case anyone is interested... Pin
Matthew Noonan26-Oct-06 7:48
memberMatthew Noonan26-Oct-06 7:48 
GeneralSuggestion about text color Pin
Styx3112-Oct-06 23:01
memberStyx3112-Oct-06 23:01 
GeneralRe: Suggestion about text color Pin
mgnoonan13-Oct-06 4:07
membermgnoonan13-Oct-06 4:07 
AnswerRe: Suggestion about text color Pin
Matthew Noonan16-Oct-06 11:24
memberMatthew Noonan16-Oct-06 11:24 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150624.2 | Last Updated 16 Oct 2006
Article Copyright 2006 by Matthew Noonan
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid