WindowsForm實現TextBox占位符Placeholder提示


在WinForm程序中,實現TextBox文本輸入框占位符的方式也很多,最常用的是方式基於Windows Api SendMessage函數發送EM_SETCUEBANNER消息,或者通過TextBox自帶的焦點事件處理。

SendMessage函數實現

創建一個繼承TextBox的ZhmTextBox輸入框控件,新增Placeholder屬性,在Placeholder的set方法中發送EM_SETCUEBANNER消息

public class ZhmTextBox: TextBox
{
    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);

    private string placeholder = string.Empty;
    public string Placeholder
    {
        get { return placeholder; }
        set
        {
            placeholder = value;
            SendMessage(Handle, EM_SETCUEBANNER, 0, Placeholder);
        }
    }
}

重新編譯下項目,就可以在工具箱中找到ZhmTextBox控件,然后設置ZhmTextBox的Placeholder屬性

通過TextBox的GotFocus和LostFocus事件

不知道為啥微軟要將TextBox的這兩個事件標注Browsable為false,所以在VS的屬性面板中是找不到這兩個事件的,只能手動擼了。

private void Form1_Load(object sender, EventArgs e)
{
    textBox1.Text = "此處是一些提示內容...";
    textBox1.LostFocus += TextBox1_LostFocus;
    textBox1.GotFocus += TextBox1_GotFocus;
}

private void TextBox1_GotFocus(object sender, EventArgs e)
{
    textBox1.Text = "";
}

private void TextBox1_LostFocus(object sender, EventArgs e)
{
    if (string.IsNullOrWhiteSpace(textBox1.Text))
        textBox1.Text = "此處是一些提示內容...";
}


如果針對每個控件都這樣擼還是有些麻煩,可以擴展下TextBox類,把事件處理放在子類的構造中去調用,這樣使用的時候也比較省事。具體代碼就不寫了,有興趣的可以自己去實現。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM