24 December 2013

Placeholder text on TextBox in C#

Hi Friends,

To set the place holder text in html we just use the placeholder attribute of that input type="text".

<input type="Text" placeholder="Username" />

<input type="Password" placeholder="Password" />


it looks like -



To do the same thing in C# window form, we do not have such attribute of properties on TextBox class in C#.
But we can accomplish this task by importing the user32.dll.  We have to use the following syntax to set the placeholder text.

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

public partial class Form1 : Form
{
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern Int32
            SendMessage(
                            IntPtr hWnd, 
                            int msg, 
                            int wParam,
                            [MarshalAs(UnmanagedType.LPWStr)]string lParam
                        );
    
    private const int EM_SETCUEBANNER = 0x1501;
        
    public Form1()
    {      
      InitializeComponent();      
   
   // set the placeholder text to the user name and password field.
      SendMessage(txtUser.Handle, EM_SETCUEBANNER, 0, "Username");
      SendMessage(txtPassword.Handle, EM_SETCUEBANNER, 0, "Password");
    }
}  

And you will get the same required result.


Thanks for Reading..!!

Happy Knowledge sharing..!! :)

No comments:

Post a Comment