0

I wanna use watermark in Text Boxes of my Windows Form using c#?

I have found this link in stackoverflow. But I really could not figure out how to use in my windows application.

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

}

Please help how to use SendMessage Method Or Suggest me any other (easy) way to use watermark.

Community
  • 1
  • 1
User13839404
  • 1,803
  • 12
  • 37
  • 46

3 Answers3

5

You have to create a new class TextBoxWatermarkExtensionMethod into your project and after you can use the method SetWatermark(string watermarkText) on your textbox

Aoi Karasu
  • 3,730
  • 3
  • 37
  • 61
Jack
  • 53
  • 1
  • 4
  • I needed to use HandleCreated event of TextBox like this: `txtVerificationCode.HandleCreated += (sender, e) => txtVerificationCode.SetWatermark("Paste verification code here");` – Jaex May 26 '15 at 15:59
0

SetWatermark is an extension method on TextBox, so anywhere on the namespace where the WatermarkTextBox class is added you can use the SetWatermark method passing the watermark string you want to apply on the TextBox like:

`myTextBox.SetWatermark("your water mark text here");`

SetWatermark will not be visible as public property of TextBox on the designer, but form your code it is accessible just like any of the bult-in methods of a TextBox object.

Biniam Eyakem
  • 545
  • 5
  • 18
0

You just add a UserControl with this code in your project. WatermarkTextBox should appear in your toolbox somewhere. Put it on your form wherever you need the watermarked textbox instead of plain old textbox, set the WatermarkText property and you should be ready to go if the code is good.

Dyppl
  • 12,161
  • 9
  • 47
  • 68