C# WinForm移除非法字符的输入框
C# WinForm移除非法字符的输入框
文章目录
namespace System.Windows.Forms
{using System.ComponentModel;/// <summary>/// 支持移除 非法字符 的输入框。/// </summary>public class RemoveInvalidCharTextBox : TextBox{/// <summary>/// 测试代码:设置 有效字符 为 整数 的字符。/// </summary>[System.Diagnostics.Conditional("DEBUG")][System.Diagnostics.CodeAnalysis.SuppressMessage("", "IDE0017")]public static void TestValidCharAsInteger(){var form = new System.Windows.Forms.Form();var textBox = new RemoveInvalidCharTextBox();textBox.Dock =System.Windows.Forms.DockStyle.Top;textBox.UpdateValidCharAsInteger();form.Controls.Add(textBox);System.Windows.Forms.Application.Run(form);}public RemoveInvalidCharTextBox(){RemoveCharService = new TextBoxBaseRemoveCharService(this);}protected override void OnTextChanged(EventArgs e){RemoveCharService?.OnTextChangedBefore();base.OnTextChanged(e);}/// <summary>/// 更新 有效字符 为 整数 的字符。/// </summary>public void UpdateValidCharAsInteger(){RemoveCharService.UpdateValidCharAsInteger();}private TextBoxBaseRemoveCharService RemoveCharService { get; set; }/// <summary>/// 禁止移除非法字符。/// </summary>[Browsable(false)][EditorBrowsable(EditorBrowsableState.Never)][DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)][DefaultValue(false)]public bool DisabledRemoveInvalidChars{get { return RemoveCharService.DisabledRemoveInvalidChars; }set { RemoveCharService.DisabledRemoveInvalidChars = value; }}}}namespace System.Windows.Forms
{using System.Collections.Generic;using System.ComponentModel;using System.Text;/// <summary>/// 移除非法字符的服务。/// </summary>public class TextBoxBaseRemoveCharService{public TextBoxBaseRemoveCharService(TextBoxBase textBox){this.TextBox = textBox;}#region 初始化函数。/// <summary>/// 更新 有效字符 为 整数 的字符。/// </summary>public void UpdateValidCharAsInteger(){ValidChars = GetIntegerChars();}/// <summary>/// 整数 的 字符。/// </summary>/// <returns></returns>public static IList<char> GetIntegerChars(){return new char[]{'0','1','2','3','4','5','6','7','8','9',};}/// <summary>/// 更新 无效字符 为 换行 的字符。/// </summary>public void UpdateInvalidCharAsNewLine(){InvalidChars = GetNewLineChars();}/// <summary>/// 换行 的字符。/// </summary>/// <returns></returns>public static IList<char> GetNewLineChars(){return new char[]{'\v','\r','\n',};}#endregion 初始化函数。#region 移除非法字符。/// <summary>/// 在 调用 <see cref="TextBoxBase.OnTextChanged(EventArgs)"/> 前执行。 <br />/// 注意:在重载函数中,调用本函数,本函数所属的对象可能为 null 。/// 所以,调用示例为 RemoveCharService?.OnTextChangedBefore()/// </summary>[System.Diagnostics.CodeAnalysis.SuppressMessage("", "S134")]public void OnTextChangedBefore(){var safeValidChars = ValidChars;var hasValidChars = safeValidChars != null && safeValidChars.Count > 0;var safeInvalidChars = InvalidChars;var hasInvalidChars = safeInvalidChars != null && safeInvalidChars.Count > 0;if (DisabledRemoveInvalidChars || (!hasValidChars && !hasInvalidChars)){return;}string oldText = TextBox.Text;if (string.IsNullOrEmpty(oldText)){return;}StringBuilder newBuilder = new StringBuilder(oldText.Length);List<int> removeIndexes = new List<int>(16);int index = -1;foreach (var ch in oldText){++index;if (hasValidChars){if (!safeValidChars.Contains(ch)){removeIndexes.Add(index);}else{newBuilder.Append(ch);}}// 等价 else if (hasInvalidChars)else{if (safeInvalidChars.Contains(ch)){removeIndexes.Add(index);}else{newBuilder.Append(ch);}}}OnTextChangedBeforeCore(oldText, newBuilder, removeIndexes);}private void OnTextChangedBeforeCore(string oldText, StringBuilder newBuilder, List<int> removeIndexes){string newText = newBuilder.ToString();if (newText != oldText){TextBox.SuspendLayout();try{// 处理重命名时,当输入非法字符时,会全选名称的问题。int selectionStartOld = 0;int selectionLengthOld = 0;var isReadySelection = !string.IsNullOrEmpty(newText) &&ReadySelect(out selectionStartOld, out selectionLengthOld);TextBox.Text = newText;// 处理重命名时,当输入非法字符时,会全选名称的问题。if (isReadySelection){selectionLengthOld -= MatchIndexCount(removeIndexes, selectionStartOld - 1, selectionStartOld + selectionLengthOld);selectionStartOld -= MatchIndexCount(removeIndexes, -1, selectionStartOld);GetSafeSelect(newText.Length, ref selectionStartOld, ref selectionLengthOld);UpdateSelect(selectionStartOld, selectionLengthOld);}}finally{TextBox.ResumeLayout();}}}private int MatchIndexCount(IList<int> indexList, int minIndex, int maxIndex){int count = 0;foreach (var index in indexList){if (index > minIndex && index < maxIndex){++count;}}return count;}private bool ReadySelect(out int selectionStart, out int selectionLength){bool isSuccessCompleted;try{selectionStart = TextBox.SelectionStart;selectionLength = TextBox.SelectionLength;isSuccessCompleted = true;}catch (Exception ex){TraceException("Ready selection exception: ", ex);selectionStart = 0;selectionLength = 0;isSuccessCompleted = false;}return isSuccessCompleted;}private void UpdateSelect(int selectionStart, int selectionLength){try{TextBox.Select(selectionStart, selectionLength);}catch (Exception ex){TraceException("Update selection exception: ", ex);}}private void GetSafeSelect(int length, ref int selectionStart, ref int selectionLength){if (selectionStart > length){selectionStart = length;}if (selectionLength > length){selectionLength = length;}}#endregion 移除非法字符。private static void TraceException(string message, Exception ex){System.Diagnostics.Trace.WriteLineIf(true, message + ex);}/// <summary>/// 禁止移除非法字符。/// </summary>[Browsable(false)][EditorBrowsable(EditorBrowsableState.Never)][DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)][DefaultValue(false)]public bool DisabledRemoveInvalidChars { get; set; }/// <summary>/// 有效字符。 <br />/// 注意:<see cref="ValidChars"/> 和 <see cref="InvalidChars"/> 最多一个不为 null 。/// </summary>[Browsable(false)][EditorBrowsable(EditorBrowsableState.Never)][DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)][DefaultValue(null)]private IList<char> ValidChars{get { return validChars; }set{if (validChars != value){if (value != null){InvalidChars = null;}validChars = value;}}}private IList<char> validChars;/// <summary>/// 无效字符。 <br />/// 注意:<see cref="ValidChars"/> 和 <see cref="InvalidChars"/> 最多一个不为 null 。/// </summary>[Browsable(false)][EditorBrowsable(EditorBrowsableState.Never)][DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)][DefaultValue(null)]private IList<char> InvalidChars{get { return invalidChars; }set{if (invalidChars != value){if (value != null){ValidChars = null;}invalidChars = value;}}}private IList<char> invalidChars;private TextBoxBase TextBox { get; set; }}}
相关文章:
C# WinForm移除非法字符的输入框
C# WinForm移除非法字符的输入框 文章目录 namespace System.Windows.Forms {using System.ComponentModel;/// <summary>/// 支持移除 非法字符 的输入框。/// </summary>public class RemoveInvalidCharTextBox : TextBox{/// <summary>/// 测试代码&#…...

智慧商城:基于请求数据动态渲染购物车列表
进入购物车列表页面,当即触发请求,打印出解构出来的data.list 查看数据是否添加到 vuex 中。 将物品加入购物车,点击购物车进入购物车列表页,点击 vue 调试工具,可以看到 cart 模块state中新增添加的几个物品信息 渲染…...

医疗信息化浪潮下 SSM+Vue 医院预约挂号系统的崛起
2相关技术 2.1 MYSQL数据库 MySQL是一个真正的多用户、多线程SQL数据库服务器。 是基于SQL的客户/服务器模式的关系数据库管理系统,它的有点有有功能强大、使用简单、管理方便、安全可靠性高、运行速度快、多线程、跨平台性、完全网络化、稳定性等,非常…...

QScreen在Qt5.15与Qt6.8版本下的区别
简述 QScreen主要用于提供与屏幕相关的信息。它可以获取有关显示设备的分辨率、尺寸、DPI(每英寸点数)等信息。本文主要是介绍Qt5.15与Qt6环境下,QScreen的差异,以及如何判断高DPI设备。 属性说明 logicalDotsPerInch࿱…...

模具生产过程中的标签使用流程图
①NFC芯片嵌入周转筐,通过读卡器读取CK_Label_v3的数据,并将这些信息上传至服务器进行存储; ②服务器随后与客户的WMS(仓库管理系统)进行交互,记录和同步注塑机的原始数据; ③当周转筐内的模具…...

Unity-URP设置单独渲染UI相机
Unity-URP设置单独渲染UI相机 1、设置主相机层级,剔除UI层 2、新建UICamera,设置RenderType为Overiay;显示层级只选择UI层 3、选择主相机,Stack参数添加UICamera 4、Canvas设置成ScreenSpace-Camera,并指定UICamera渲…...

如何使用java来解析一个pdf文件呢?
最近搞到一个任务是要解析一套雅思题目并提取其中的高频单词。那如何使用java来解析一个pdf文件呢? 首先我们要知道这需要springboot框架来进行创建,需要的PDFTextStripper是一个用于PDF文档中提取文本的类,它是Apache PDFBox的一个类用于处…...
asp.net core发布配置端口号,支持linux
方式一,修改配置文件 appsettings.json 找到文件 appsettings.json, 添加如下节点配置,在linux环境需要设置0.0.0.0才可以正常代表本机,然后被其他机器访问,此处设置端口8000, "Kestrel": {&quo…...

M3D: 基于多模态大模型的新型3D医学影像分析框架,将3D医学图像分析从“看图片“提升到“理解空间“的层次,支持检索、报告生成、问答、定位和分割等8类任务
M3D: 基于多模态大模型的新型3D医学影像分析框架,将3D医学图像分析从“看图片“提升到“理解空间“的层次,支持检索、报告生成、问答、定位和分割等8类任务 论文大纲理解1. 确认目标2. 分析过程(目标-手段分析)核心问题拆解 3. 实…...
JavaScript中,常用crypto模块进行rsa加密,crypto-js模块进行md5算法
Node.js 的 crypto 模块 Node.js 内置的 crypto 模块提供了基本的加密功能,可以用于生成 RSA 密钥对和执行加密、解密操作。 代码案例: const crypto require(crypto);const { publicKey, privateKey } crypto.generateKeyPairSync(rsa, {modulusLen…...

机器学习04-为什么Relu函数
机器学习0-为什么Relu函数 文章目录 机器学习0-为什么Relu函数 [toc]1-手搓神经网络步骤总结2-为什么要用Relu函数3-进行L1正则化修改后的代码解释 4-进行L2正则化解释注意事项 5-Relu激活函数多有夸张1-细数Relu函数的5宗罪2-Relu函数5宗罪详述 6-那为什么要用这个Relu函数7-文…...

基于Arduino的自动开瓶系统
自动瓶盖开启器:结合Arduino和线性运动系统的创新解决方案 展示视频: 基于Arduino的自动开瓶器 引言 在日常生活中,开启瓶盖看似是一件简单的事情,但对于某些人来说,这可能是一个挑战。特别是对于患有类风湿性关节炎…...
通过使用 contenteditable=“true“,我们彻底防止了 iOS 系统键盘的弹出
明白了,对于苹果手机(iOS),即使使用了 bindtap 和 e.preventDefault() 来阻止默认行为,系统键盘仍然可能会弹出。这是因为 iOS 对输入框的处理方式与 Android 不同,尤其是在处理 input 元素时,iOS 会更加积极地弹出键盘。 解决方案 为了彻底防止 iOS 系统键盘弹出,我…...

20241217使用M6000显卡在WIN10下跑whisper来识别中英文字幕
20241217使用M6000显卡在WIN10下跑whisper来识别中英文字幕 2024/12/17 17:21 缘起,最近需要识别法国电影《地下铁》的法语字幕,使用 字幕小工具V1.2【whisper套壳/GUI封装了】 无效。 那就是直接使用最原始的whisper来干了。 当你重装WIN10的时候&#…...
搜索召回:召回聚合
召回聚合 用户的查询意图往往是复杂多样的,可能涉及到不同的领域、主题和语义层面。因此,召回体系中通常通过多路召回的方式从不同角度去理解和满足用户的查询需求。此外,多路召回通过各召回通道并行计算可以在海量数据中能够快速响应&#…...

NTFS 文件搜索库
NTFS 文件搜索库 中文 | English 一个快速搜索NTFS卷文件的库 在这里插入图片描述 特性 快速扫描 NTFS 格式驱动器上的所有文件实时快速同步文件变更(创建, 更名, 删除)支持通配符查询文件名或文件路径重启自动更新文件变动, 无需重新进行全盘扫描 API描述 初始化并指定…...
【GoF23种设计模式】02_单例模式(Singleton Pattern)
文章目录 前言一、什么是单例模式?二、为什么要用单例模式?三、如何实现单例模式?总结 前言 提示:设计者模式有利于提高开发者的编程效率和代码质量: GoF(Gang of Four,四人帮)设计…...
UniApp:uni-segmented-control 自定义布局
自定义tabs选项,items 为tabs名称数组,横向滚动 <scroll-view scroll-x><view class"segmented-control"><view v-for"(item, index) in items" :key"index" class"control-item ":class"…...

【算法day17-day18】回溯:解决组合问题
不好意思呀各位,最近在忙期末考今天才彻底结束,来让我们继续算法之路吧~ 题目引用 组合电话号码的字母组合组合总和组合总和II分割回文串 1.组合 给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。 你可以按 任何顺序 返回…...
从监控异常发现网络安全
前言 最近在前端异常监控系统中,发现一些异常信息,从中做了一些分析,得到一些体会,因此作文。 发现异常 某天早上打开监控系统发现,当天凌晨1点过测试环境有2个前端上报的异常,报错的原因都是由于没有获取…...
内存分配函数malloc kmalloc vmalloc
内存分配函数malloc kmalloc vmalloc malloc实现步骤: 1)请求大小调整:首先,malloc 需要调整用户请求的大小,以适应内部数据结构(例如,可能需要存储额外的元数据)。通常,这包括对齐调整,确保分配的内存地址满足特定硬件要求(如对齐到8字节或16字节边界)。 2)空闲…...

Vue3 + Element Plus + TypeScript中el-transfer穿梭框组件使用详解及示例
使用详解 Element Plus 的 el-transfer 组件是一个强大的穿梭框组件,常用于在两个集合之间进行数据转移,如权限分配、数据选择等场景。下面我将详细介绍其用法并提供一个完整示例。 核心特性与用法 基本属性 v-model:绑定右侧列表的值&…...

Psychopy音频的使用
Psychopy音频的使用 本文主要解决以下问题: 指定音频引擎与设备;播放音频文件 本文所使用的环境: Python3.10 numpy2.2.6 psychopy2025.1.1 psychtoolbox3.0.19.14 一、音频配置 Psychopy文档链接为Sound - for audio playback — Psy…...
GitHub 趋势日报 (2025年06月08日)
📊 由 TrendForge 系统生成 | 🌐 https://trendforge.devlive.org/ 🌐 本日报中的项目描述已自动翻译为中文 📈 今日获星趋势图 今日获星趋势图 884 cognee 566 dify 414 HumanSystemOptimization 414 omni-tools 321 note-gen …...
【SSH疑难排查】轻松解决新版OpenSSH连接旧服务器的“no matching...“系列算法协商失败问题
【SSH疑难排查】轻松解决新版OpenSSH连接旧服务器的"no matching..."系列算法协商失败问题 摘要: 近期,在使用较新版本的OpenSSH客户端连接老旧SSH服务器时,会遇到 "no matching key exchange method found", "n…...

Rust 开发环境搭建
环境搭建 1、开发工具RustRover 或者vs code 2、Cygwin64 安装 https://cygwin.com/install.html 在工具终端执行: rustup toolchain install stable-x86_64-pc-windows-gnu rustup default stable-x86_64-pc-windows-gnu 2、Hello World fn main() { println…...
如何通过git命令查看项目连接的仓库地址?
要通过 Git 命令查看项目连接的仓库地址,您可以使用以下几种方法: 1. 查看所有远程仓库地址 使用 git remote -v 命令,它会显示项目中配置的所有远程仓库及其对应的 URL: git remote -v输出示例: origin https://…...
起重机起升机构的安全装置有哪些?
起重机起升机构的安全装置是保障吊装作业安全的关键部件,主要用于防止超载、失控、断绳等危险情况。以下是常见的安全装置及其功能和原理: 一、超载保护装置(核心安全装置) 1. 起重量限制器 功能:实时监测起升载荷&a…...
背包问题双雄:01 背包与完全背包详解(Java 实现)
一、背包问题概述 背包问题是动态规划领域的经典问题,其核心在于如何在有限容量的背包中选择物品,使得总价值最大化。根据物品选择规则的不同,主要分为两类: 01 背包:每件物品最多选 1 次(选或不选&#…...

工厂方法模式和抽象工厂方法模式的battle
1.案例直接上手 在这个案例里面,我们会实现这个普通的工厂方法,并且对比这个普通工厂方法和我们直接创建对象的差别在哪里,为什么需要一个工厂: 下面的这个是我们的这个案例里面涉及到的接口和对应的实现类: 两个发…...