Skoči na vsebino

Watermarked TextBox in Windows Forms on .NET

Objavljeno dve minuti branja

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:

We would have this:

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);
    }

}