欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

WindowsForm實現(xiàn)TextBox占位符Placeholder提示功能

 更新時間:2020年07月13日 09:17:12   作者:zhuanghamiao  
這篇文章主要介紹了WindowsForm實現(xiàn)TextBox占位符Placeholder提示,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

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

SendMessage函數(shù)實現(xiàn)

創(chuàng)建一個繼承TextBox的ZhmTextBox輸入框控件,新增Placeholder屬性,在Placeholder的set方法中發(fā)送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控件,然后設(shè)置ZhmTextBox的Placeholder屬性

通過TextBox的GotFocus和LostFocus事件

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

private void Form1_Load(object sender, EventArgs e)
{
 textBox1.Text = "此處是一些提示內(nèi)容...";
 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 = "此處是一些提示內(nèi)容...";
}

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

到此這篇關(guān)于WindowsForm實現(xiàn)TextBox占位符Placeholder提示的文章就介紹到這了,更多相關(guān)TextBox占位符Placeholder提示內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論