Set placeholder text for textbox (cue text)
Setting placeholder text for your textboxes helps the users to identify better what kind of information it’s needed from them.
Instead of handling the focus enter and focus leave events in order to set and remove the placeholder text it is possible to use the Windows SendMessage
function to send a EM_SETCUEBANNER
message to our textbox to do the work for us.
This can be done with two easy steps. First we need to expose the Windows SendMessage function.
1 2 3 | private const int EM_SETCUEBANNER = 0x1501; [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern Int32 SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)]string lParam); |
Then simply call the method with the handle of our textbox, EM_SETCUEBANNER’s value and the text we want to set.
1 2 | SendMessage(textBox1.Handle, EM_SETCUEBANNER, 0, "Username"); SendMessage(textBox2.Handle, EM_SETCUEBANNER, 0, "Password"); |
The result will be a textbox with a placeholder text of our choice. The placeholder text will be automatically be removed when the textbox gains focus and will only reappear if the textbox loses focus and has no characters typed in it.
Is there an answer for combo boxes?
necesitan declarar
using System.Runtime.InteropServices;
Thank you. Getting the missing ‘using’ options drives me crazy. Without this additional declaration I would have given up on getting this working.
Ctrl+. will offer you the correct using most of the time.
When i put this code in my application, compiler does not give any error But It is not giving me expected output… Very Sad….
thank you so much! :)
Thankx for your effort, can I use this same for “ComboBox” also?
THIS CODE CANT WORKING IN MY PROJECT PLEASE I NEED EXAMPLE PLACE HOLDER IN TEXTBOX C# WINFORMS
but this code is for C#
Styling of Cue Text also not possible?
Sadly that is not possible as edit controls don’t support custom cue banner colors.
This was exactly what I was looking for! Very easy. Too bad it doesn’t work with multiline textboxes.
This is sadly by design.
"You cannot set a cue banner on a multiline edit control or on a rich edit control."
http://msdn.microsoft.com/en-us/library/windows/desktop/bb761639%28v=vs.85%29.aspx