Bite my bytes

What I learn by day I blog at night.

  Home :: Contact :: Syndication  
  816 Posts :: 4359 Comments :: 235 Trackbacks

Search

Recent Comments.

Recent Posts

Most popular posts
in last 360 days

Categories

My Projects

Archives

Stuff


Copyright © by David Vidmar
 
Contact me!
 
LinkedIn Profile
 
 
 
Server Monitor

Phew! It's been a while since I posted some code here! Here goes...

I had a modest request from a part-time-UI-designer of application I'm currently working on. He wanted watermarked input boxes as we sometimes see on the web, except that he wanted them in desktop application.

So instead of something like this:

image

We would have this:

 image

Fair enough, I liked it.

I immediately started thinking about Enter and Leave events and overlaying Label control over TextBox control and I had a good starting point with my old LinkTextBox control.

But, man, I'm glad I googled before I started coding. It turns out, the feature is only SendMessage away.

So here are two implementations:

First one is done with subclassing  and creating WatermarkTextBox.

class WatermarkTextBox : TextBox
{
    private const uint ECM_FIRST = 0x1500;
    private const uint EM_SETCUEBANNER = ECM_FIRST + 1;

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, uint wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);

    private string watermarkText;
    public string WatermarkText
    {
        get { return watermarkText; }
        set
        {
            watermarkText = value;
            SetWatermark(watermarkText);
        }
    }

    private void SetWatermark(string watermarkText)
    {
        SendMessage(this.Handle, EM_SETCUEBANNER, 0, watermarkText);
    }       

}

Other one is a simple Extension Method.

public static class TextBoxWatermarkExtensionMethod
{
    private const uint ECM_FIRST = 0x1500;
    private const uint EM_SETCUEBANNER = ECM_FIRST + 1;

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
    private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, uint wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);

    public static void SetWatermark(this TextBox textBox, string watermarkText)
    {
        SendMessage(textBox.Handle, EM_SETCUEBANNER, 0, watermarkText);
    }

}
Posted on Wednesday, November 05, 2008 11:36 PM | Filed under: Developement |