在WinForm程式中,實現TextBox文本輸入框占位符的方式也很多,最常用的是方式基於Windows Api SendMessage函數發送EM_SETCUEBANNER消息,或者通過TextBox自帶的焦點事件處理。 ###SendMessage函數實現 創建一個繼承TextBox的ZhmTe ...
在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類,把事件處理放在子類的構造中去調用,這樣使用的時候也比較省事。具體代碼就不寫了,有興趣的可以自己去實現。