修改 font的文本信息_C#窗体,文本框如何实现类似html的输入提示信息
发布日期:2022-02-04 01:44:00
浏览次数:26
分类:技术文章
本文共 2413 字,大约阅读时间需要 8 分钟。
文章开始之前,先看下效果图:
那么这个是如何实现的,Winform自带的TextBox是不具备这种PlaceHolder提示功能的,要实现它,我们就需要重写TextBox控件。
具体代码如下:
using System;using System.Collections.Generic;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace RevitDevelopment.CustomControls{ /// /// 带有PlaceHolder的Textbox /// /// marc public class PlaceHolderTextBox : TextBox { private bool _isPlaceHolder = true; private string _placeHolderText; /// /// 提示文本 /// public string PlaceHolderText { get { return _placeHolderText; } set { _placeHolderText = value; SetPlaceholder(); } } /// /// 文本 /// public new string Text { get { return _isPlaceHolder ? string.Empty : base.Text; } set { base.Text = value; } } /// /// 构造函数 /// public PlaceHolderTextBox() { GotFocus += RemovePlaceHolder; LostFocus += SetPlaceholder; } /// /// 当焦点失去的时候,将清空提示文本 /// private void SetPlaceholder() { if (string.IsNullOrEmpty(base.Text)) { base.Text = PlaceHolderText; this.ForeColor = Color.Gray; this.Font = new Font(this.Font, FontStyle.Italic); _isPlaceHolder = true; } } /// /// 当焦点获得的时候,将显示提示文本 /// private void RemovePlaceHolder() { if (_isPlaceHolder) { base.Text = ""; this.ForeColor = SystemColors.WindowText; this.Font = new Font(this.Font, FontStyle.Regular); _isPlaceHolder = false; } } /// /// 失去焦点 /// /// /// private void SetPlaceholder(object sender, EventArgs e) { SetPlaceholder(); } /// /// 获得焦点 /// /// /// private void RemovePlaceHolder(object sender, EventArgs e) { RemovePlaceHolder(); } }}
代码是简单明了的,它提供了属性PlaceHolderText,用于填写提示信息,当焦点获得或者失去时,将触发事件。
将该代码,写好后编译,将会在“工具箱”中出现这个组件:
将该组件拖入您想要使用的地方,然后设置如下属性:
如此,便可以实现开篇的效果图。
祝您用餐愉快。
转载地址:https://blog.csdn.net/weixin_39603908/article/details/110812631 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月13日 09时24分40秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
idea中创建maven文件时,maven路径是自己设置的
2019-04-25
使用FFmpeg将pcm数据编码为aac
2019-04-25
使用FFmpeg将S16格式音频数据重采样为FLTP格式
2019-04-25
推荐系统实践学习系列(七)推荐系统实例
2019-04-25
推荐系统实践 学习总结
2019-04-25
Python3 Flask+nginx+Gunicorn部署(下)
2019-04-25
python 爬取fcoin比特币交易市场
2021-06-28
python 爬取fcoin比特币交易市场 下文
2021-06-28
python scrapy爬取全部豆瓣电影(可能是54万数据)
2021-06-28
centos7 安装jdk1.8
2021-06-28
python3调用js的库之execjs
2021-06-28
python3 爬取36氪新闻网页
2021-06-28
程序员个性注释专属(保存下)
2021-06-28
广州八月份面试(一篇为断更写抱歉的小总结)
2021-06-28
mysql表复制操作
2021-06-28
【Android面试题】Activity的生命周期
2021-06-28
【Android面试】Activity的四种启动模式
2019-04-25
【Android面试】Fragment相关
2019-04-25