在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类,把事件处理放在子类的构造中去调用,这样使用的时候也比较省事。具体代码就不写了,有兴趣的可以自己去实现。
到此这篇关于WindowsForm实现TextBox占位符Placeholder提示的文章就介绍到这了,更多相关TextBox占位符Placeholder提示内容请搜索社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持社区! |