Click here to Skip to main content
15,867,756 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 235.7K   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

 
QuestionMultiLine Text Pin
amith sai27-Jun-12 21:35
amith sai27-Jun-12 21:35 
GeneralCool! Pin
Diamonddrake17-Dec-10 8:15
Diamonddrake17-Dec-10 8:15 
GeneralMy vote of 4 Pin
sopheak.programming13-Nov-10 16:06
sopheak.programming13-Nov-10 16:06 
GeneralThanks.... Pin
Arjen H.27-Sep-10 21:19
Arjen H.27-Sep-10 21:19 
GeneralNIcely done Matt Pin
Elkay15-Mar-09 18:16
Elkay15-Mar-09 18:16 
QuestionHow to do it for the System.Windows.Forms.ToolStripTextBox? Pin
Martin Radu9-Mar-08 11:06
Martin Radu9-Mar-08 11:06 
GeneralRe: How to do it for the System.Windows.Forms.ToolStripTextBox? Pin
Matthew Noonan9-Mar-08 11:43
Matthew Noonan9-Mar-08 11:43 
GeneralFocusSelect Pin
Johnny J.8-Nov-07 21:34
professionalJohnny J.8-Nov-07 21:34 
GeneralRe: FocusSelect Pin
Johnny J.8-Nov-07 21:34
professionalJohnny J.8-Nov-07 21:34 
QuestionHow to do it for the ComboBox Pin
Abo Yahya26-Oct-07 13:11
Abo Yahya26-Oct-07 13:11 
This is a great and very useful control BUT how can we create a similar ComboBox control??
AnswerRe: How to do it for the ComboBox Pin
Matthew Noonan26-Oct-07 19:18
Matthew Noonan26-Oct-07 19:18 
GeneralRe: How to do it for the ComboBox Pin
Abo Yahya26-Oct-07 23:56
Abo Yahya26-Oct-07 23:56 
GeneralSuggestion: keep prompt until text entered Pin
mitooki6-Jul-07 5:51
mitooki6-Jul-07 5:51 
GeneralRe: Suggestion: keep prompt until text entered Pin
JoanComasFdz17-Sep-07 1:34
JoanComasFdz17-Sep-07 1:34 
GeneralRe: Suggestion: keep prompt until text entered Pin
veritas guy7-Dec-07 11:16
veritas guy7-Dec-07 11:16 
GeneralPrompted text with MaskTextBox Pin
N U Reddy13-Jun-07 7:53
N U Reddy13-Jun-07 7:53 
GeneralRe: Prompted text with MaskTextBox Pin
Matthew Noonan19-Jun-07 11:32
Matthew Noonan19-Jun-07 11:32 
GeneralSuggestion Pin
Sk8tz23-May-07 22:29
professionalSk8tz23-May-07 22:29 
GeneralRe: Suggestion Pin
N U Reddy13-Jun-07 7:56
N U Reddy13-Jun-07 7:56 
GeneralRe: Suggestion Pin
Matthew Noonan19-Jun-07 11:34
Matthew Noonan19-Jun-07 11:34 
GeneralAnother suggestion Pin
Lex Li19-Apr-07 20:59
professionalLex Li19-Apr-07 20:59 
GeneralRe: Another suggestion Pin
Matthew Noonan19-Jun-07 11:38
Matthew Noonan19-Jun-07 11:38 
QuestionNot working for Windows 2000 Pin
Jason Law21-Jan-07 20:30
Jason Law21-Jan-07 20:30 
AnswerRe: Not working for Windows 2000 Pin
Matthew Noonan5-Feb-07 14:12
Matthew Noonan5-Feb-07 14:12 
GeneralRe: Not working for Windows 2000 Pin
vachaun26-Apr-07 5:55
vachaun26-Apr-07 5:55 

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.