当前位置: 首页 > news >正文

WinForms开发基础:实现带X按钮的ClearableTextBox控件

在这里插入图片描述

前言

我们经常看到这样的带X按钮的输入框在这里插入图片描述
如果使用WinForms开发中,该如何进行设计,普通的TextBox控件如何进行改造?为了提升用户体验,在TextBox文本框内添加一个“x”按钮,方便用户一键清除内容。本文将介绍如何通过继承TextBox控件实现自定义的ClearableTextBox

功能需求

  1. 当文本框为空时,隐藏“x”按钮。
  2. 当文本框有输入内容时,显示“x”按钮。
  3. 点击“x”按钮时,清空文本框内容并隐藏按钮。

实现步骤

1. 创建ClearableTextBox控件

首先,在项目中添加一个新类ClearableTextBox,继承自TextBox

using System;
using System.Drawing;
using System.Windows.Forms;public class ClearableTextBox : TextBox
{private Button clearButton;public ClearableTextBox(){InitializeClearButton();AttachEventHandlers();}private void InitializeClearButton(){clearButton = new Button{Text = "x",Font = new Font(FontFamily.GenericSansSerif, 8, FontStyle.Bold),Size = new Size(18, 18),FlatStyle = FlatStyle.Flat,Visible = false,Cursor = Cursors.Hand,Dock = DockStyle.Right};clearButton.FlatAppearance.BorderSize = 0;Controls.Add(clearButton);}private void AttachEventHandlers(){TextChanged += (s, e) => clearButton.Visible = !string.IsNullOrEmpty(Text);clearButton.Click += (s, e) => ClearText();}private void ClearText(){Text = string.Empty;clearButton.Visible = false;}protected override void OnResize(EventArgs e){base.OnResize(e);PositionClearButton();}private void PositionClearButton(){clearButton.Location = new Point(Width - clearButton.Width - 2, (Height - clearButton.Height) / 2);}
}

2. 关键逻辑解析

  • 按钮显示与隐藏:通过TextChanged事件,根据文本是否为空来控制按钮的可见性。
  • 文本框内容清除:按钮点击时调用ClearText()方法,清空文本并隐藏按钮。
  • 按钮位置调整:重写OnResize方法,确保在控件大小改变时,按钮始终位于右侧中央。

3. 在WinForms窗体中使用

编译之后,可以在工具箱中查看新的ClearableTextBox控件
在这里插入图片描述
在窗体设计器中拖拽一个ClearableTextBox控件,或通过代码添加:

public partial class Form1 : Form
{public Form1(){InitializeComponent();var textBox = new ClearableTextBox{Location = new Point(20, 20),Width = 200};Controls.Add(textBox);}
}

在这里插入图片描述

总结

通过继承TextBox并添加Button控件,我们实现了一个带“x”按钮的文本框,提升了用户操作的便捷性。此方法不仅简化了UI逻辑,还易于在项目中复用。

http://www.xdnf.cn/news/29089.html

相关文章:

  • spring-batch批处理框架(2)
  • EAGLE代码研读+模型复现
  • Windows使用SonarQube时启动脚本自动关闭
  • 运算符重载
  • 小刚说C语言刷题——1035 判断成绩等级
  • firewalld 防火墙
  • 深入实战:使用C++开发高性能RESTful API
  • 详解反射型 XSS 的后续利用方式:从基础窃取到高级组合拳攻击链
  • 基于Python的中国象棋小游戏的设计与实现
  • CiteULike 数据集介绍与下载指南
  • AI时代下 你需要和想要了解的英文缩写含义
  • 基于单片机的热释电红外报警器(论文+源码)
  • 基于单片机的按摩器控制系统设计
  • 单例设计模式
  • springCloud/Alibaba常用中间件全集(上)
  • MySql 三大日志(redolog、undolog、binlog)详解
  • ubuntu24.04上使用qemu+buildroot+uboot+linux+tftp+nfs模拟搭建vexpress-ca9嵌入式linux开发环境
  • 关于viewpager常见的泄漏
  • 部署rocketmq集群
  • django基于爬虫的网络新闻分析系统的设计与实现(源码+lw+部署文档+讲解),源码可白嫖!
  • 【PyTorch】colab上跑VGG(深度学习)数据集是 CIFAR10
  • B端APP设计:打破传统限制,为企业开启便捷新通道
  • 软件架构分层策略对比及Go项目实践
  • 深度解析 SOA:架构原理、核心优势与实践挑战
  • 2025年渗透测试面试题总结-拷打题库06(题目+回答)
  • LeetCode每日一题4.19
  • 【Bluedroid】蓝牙存储模块配置管理:启动、读写、加密与保存流程解析
  • sqlilabs-Less之HTTP头部参数的注入——基础篇
  • [HCIP] OSPF 综合实验
  • Vue3+TS中svg图标的使用