软件编程
位置:首页>> 软件编程>> C#编程>> WindowsForm实现TextBox占位符Placeholder提示功能

WindowsForm实现TextBox占位符Placeholder提示功能

作者:zhuanghamiao  发布时间:2023-03-18 12:57:44 

标签:TextBox,占位符,Placeholder

在WinForm程序中,实现TextBox文本输入框占位符的方式也很多,最常用的是方式基于Windows Api SendMessage函数发送EM_SETCUEBANNER消息,或者通过TextBox自带的焦点事件处理。

WindowsForm实现TextBox占位符Placeholder提示功能

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属性

WindowsForm实现TextBox占位符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 = "此处是一些提示内容...";
}

WindowsForm实现TextBox占位符Placeholder提示功能

如果针对每个控件都这样撸还是有些麻烦,可以扩展下TextBox类,把事件处理放在子类的构造中去调用,这样使用的时候也比较省事。具体代码就不写了,有兴趣的可以自己去实现。

来源:https://www.cnblogs.com/zhuanghamiao/archive/2020/07/12/TextBox-Placeholder.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com