服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - WindowsForm实现TextBox占位符Placeholder提示功能

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

2022-09-24 15:29zhuanghamiao C#

这篇文章主要介绍了WindowsForm实现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类,把事件处理放在子类的构造中去调用,这样使用的时候也比较省事。具体代码就不写了,有兴趣的可以自己去实现。

到此这篇关于WindowsForm实现TextBox占位符Placeholder提示的文章就介绍到这了,更多相关TextBox占位符Placeholder提示内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/zhuanghamiao/archive/2020/07/12/TextBox-Placeholder.html

延伸 · 阅读

精彩推荐