14

What is he best way to implement Watermark functionality for a System.Windows.Forms.TextBox in .Net 2.0 with C#?


Edit:

Using the ready-made component from CodeProject was very easy. It's also with a The Code Project Open License (CPOL).

Kb.
  • 7,240
  • 13
  • 56
  • 75
  • 1
    Alternative name for 'watermark' is 'cue'. – John M Apr 27 '10 at 12:53
  • *Watermark* aka *hint text* aka *placeholder text*. Related posts - [Watermark TextBox in WinForms](https://stackoverflow.com/q/4902565/465053) & [Watermark / hint text / placeholder TextBox](https://stackoverflow.com/q/833943/465053) & [Adding placeholder text to textbox](https://stackoverflow.com/q/11873378/465053) – RBT Jun 16 '18 at 02:33

2 Answers2

18

lately I needed a watermark textbox, the first thing that popped in to my head was OnLeave and OnEnter events of textbox, but first I googled it and I got two links first was the one in CodeProject which used the System.Drawing namespace and the other one was here using the SendMessage() over here http://vidmar.net/weblog/archive/2008/11/05/watermarked-textbox-in-windows-forms-on-.net.aspx.

I beleive the SendMessage one is much easier and it also has no flickering in it. though I used it.

I hope it will be helpful for you.

Peymankh
  • 1,976
  • 25
  • 30
  • 1
    @Peymankh: Thanks +1 and green checkmark. SendMessage is much easier – Kb. Sep 12 '09 at 15:41
  • Additional notes on Vidmar usage: *setting watermark = this.txtBoxA.SetWatermark("BOX"); * *references needed = using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Runtime.InteropServices;* – John M Apr 27 '10 at 12:53
  • How to use it in a windows application? – User13839404 Mar 14 '11 at 17:34
  • 1
    Tried this approach (EM_SETCUEBANNER) and the CodeProject one. The only disadvantage to EM_SETCUEBANNER is you can't set the watermark color, otherwise it rocks. The disadvantage to the codeproject approach is the flicker Peymankh mentioned and the watermark text doesn't disappear until you start typing (not on focus). – Lee Richardson Sep 07 '12 at 01:20
  • I created a small GitHub repository showing all methods to create a watermark. https://github.com/akorb/PlaceholderTextBox – Andy Jun 10 '15 at 13:44
  • While I like this solution, I'd argue that since it is rather short and the link may die in the future, the code should be included in the answer body. Please do keep linking the original source for credit though. – Armand Bernard Jun 20 '21 at 07:49
7

It is not as straightforward as one would think. You need to use using the System.Drawing namespace and override the OnPaint event.

Here are some links of some people that have already done it.

Link & Link

cgreeno
  • 31,943
  • 7
  • 66
  • 87