VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > C#教程 >
  • WindowsForm实现TextBox占位符Placeholder提示

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

文章出处:https://www.cnblogs.com/zhuanghamiao/p/TextBox-Placeholder.html


相关教程