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

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>/// 测试代码&#…...

智慧商城:基于请求数据动态渲染购物车列表

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

医疗信息化浪潮下 SSM+Vue 医院预约挂号系统的崛起

2相关技术 2.1 MYSQL数据库 MySQL是一个真正的多用户、多线程SQL数据库服务器。 是基于SQL的客户/服务器模式的关系数据库管理系统&#xff0c;它的有点有有功能强大、使用简单、管理方便、安全可靠性高、运行速度快、多线程、跨平台性、完全网络化、稳定性等&#xff0c;非常…...

QScreen在Qt5.15与Qt6.8版本下的区别

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

模具生产过程中的标签使用流程图

①NFC芯片嵌入周转筐&#xff0c;通过读卡器读取CK_Label_v3的数据&#xff0c;并将这些信息上传至服务器进行存储&#xff1b; ②服务器随后与客户的WMS&#xff08;仓库管理系统&#xff09;进行交互&#xff0c;记录和同步注塑机的原始数据&#xff1b; ③当周转筐内的模具…...

Unity-URP设置单独渲染UI相机

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

如何使用java来解析一个pdf文件呢?

最近搞到一个任务是要解析一套雅思题目并提取其中的高频单词。那如何使用java来解析一个pdf文件呢&#xff1f; 首先我们要知道这需要springboot框架来进行创建&#xff0c;需要的PDFTextStripper是一个用于PDF文档中提取文本的类&#xff0c;它是Apache PDFBox的一个类用于处…...

asp.net core发布配置端口号,支持linux

方式一&#xff0c;修改配置文件 appsettings.json 找到文件 appsettings.json&#xff0c; 添加如下节点配置&#xff0c;在linux环境需要设置0.0.0.0才可以正常代表本机&#xff0c;然后被其他机器访问&#xff0c;此处设置端口8000&#xff0c; "Kestrel": {&quo…...

M3D: 基于多模态大模型的新型3D医学影像分析框架,将3D医学图像分析从“看图片“提升到“理解空间“的层次,支持检索、报告生成、问答、定位和分割等8类任务

M3D: 基于多模态大模型的新型3D医学影像分析框架&#xff0c;将3D医学图像分析从“看图片“提升到“理解空间“的层次&#xff0c;支持检索、报告生成、问答、定位和分割等8类任务 论文大纲理解1. 确认目标2. 分析过程&#xff08;目标-手段分析&#xff09;核心问题拆解 3. 实…...

JavaScript中,常用crypto模块进行rsa加密,crypto-js模块进行md5算法

Node.js 的 crypto 模块 Node.js 内置的 crypto 模块提供了基本的加密功能&#xff0c;可以用于生成 RSA 密钥对和执行加密、解密操作。 代码案例&#xff1a; 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的自动开瓶系统

自动瓶盖开启器&#xff1a;结合Arduino和线性运动系统的创新解决方案 展示视频&#xff1a; 基于Arduino的自动开瓶器 引言 在日常生活中&#xff0c;开启瓶盖看似是一件简单的事情&#xff0c;但对于某些人来说&#xff0c;这可能是一个挑战。特别是对于患有类风湿性关节炎…...

通过使用 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 缘起&#xff0c;最近需要识别法国电影《地下铁》的法语字幕&#xff0c;使用 字幕小工具V1.2【whisper套壳/GUI封装了】 无效。 那就是直接使用最原始的whisper来干了。 当你重装WIN10的时候&#…...

搜索召回:召回聚合

召回聚合 用户的查询意图往往是复杂多样的&#xff0c;可能涉及到不同的领域、主题和语义层面。因此&#xff0c;召回体系中通常通过多路召回的方式从不同角度去理解和满足用户的查询需求。此外&#xff0c;多路召回通过各召回通道并行计算可以在海量数据中能够快速响应&#…...

NTFS 文件搜索库

NTFS 文件搜索库 中文 | English 一个快速搜索NTFS卷文件的库 在这里插入图片描述 特性 快速扫描 NTFS 格式驱动器上的所有文件实时快速同步文件变更(创建, 更名, 删除)支持通配符查询文件名或文件路径重启自动更新文件变动, 无需重新进行全盘扫描 API描述 初始化并指定…...

【GoF23种设计模式】02_单例模式(Singleton Pattern)

文章目录 前言一、什么是单例模式&#xff1f;二、为什么要用单例模式&#xff1f;三、如何实现单例模式&#xff1f;总结 前言 提示&#xff1a;设计者模式有利于提高开发者的编程效率和代码质量&#xff1a; GoF&#xff08;Gang of Four&#xff0c;四人帮&#xff09;设计…...

UniApp:uni-segmented-control 自定义布局

自定义tabs选项&#xff0c;items 为tabs名称数组&#xff0c;横向滚动 <scroll-view scroll-x><view class"segmented-control"><view v-for"(item, index) in items" :key"index" class"control-item ":class"…...

【算法day17-day18】回溯:解决组合问题

不好意思呀各位&#xff0c;最近在忙期末考今天才彻底结束&#xff0c;来让我们继续算法之路吧~ 题目引用 组合电话号码的字母组合组合总和组合总和II分割回文串 1.组合 给定两个整数 n 和 k&#xff0c;返回范围 [1, n] 中所有可能的 k 个数的组合。 你可以按 任何顺序 返回…...

从监控异常发现网络安全

前言 最近在前端异常监控系统中&#xff0c;发现一些异常信息&#xff0c;从中做了一些分析&#xff0c;得到一些体会&#xff0c;因此作文。 发现异常 某天早上打开监控系统发现&#xff0c;当天凌晨1点过测试环境有2个前端上报的异常&#xff0c;报错的原因都是由于没有获取…...

【ElevenLabs情绪模拟技术深度解密】:20年AI语音工程师亲测的5大情感建模陷阱与避坑指南

更多请点击&#xff1a; https://intelliparadigm.com 第一章&#xff1a;ElevenLabs情绪模拟技术深度解密 ElevenLabs 的情绪模拟并非简单调节语调或语速&#xff0c;而是通过多维度声学特征建模——包括基频&#xff08;F0&#xff09;动态包络、能量分布、共振峰偏移、微停…...

2026年AI大模型API中转站深度测评:谁能成为生产环境下的最优解决方案?

2026年&#xff0c;AI模型的迭代速度进一步加快。从年初在技术社区引起轰动的OpenClaw架构&#xff0c;到GPT - 5.4、Claude 4.6等性能领先的通用模型&#xff0c;再到视频生成领域的Sora2与Veo3&#xff0c;模型之间的竞争愈发激烈。然而&#xff0c;国内开发者在调用这些模型…...

R公司摆线针轮减速机装配线优化【附代码】

✨ 长期致力于装配线优化、多目标优化、改进粒子群算法、Flexsim仿真研究工作&#xff0c;擅长数据搜集与处理、建模仿真、程序编写、仿真设计。 ✅ 专业定制毕设、代码 ✅ 如需沟通交流&#xff0c;点击《获取方式》 &#xff08;1&#xff09;基于工业工程的装配线瓶颈识别与…...

ARM调试工具AXD与armsd实战指南

1. ARM调试工具概述在嵌入式系统开发中&#xff0c;调试器是不可或缺的核心工具。ARM平台提供了两种主流的调试解决方案&#xff1a;AXD&#xff08;ARM eXtended Debugger&#xff09;和armsd&#xff08;ARM Symbolic Debugger&#xff09;。这两个工具构成了RealView开发套件…...

从《致爱丽丝》到《野蜂飞舞》:通过经典钢琴曲片段,手把手教你识别小字组、大字组在五线谱上的位置

从《致爱丽丝》到《野蜂飞舞》&#xff1a;用经典旋律解锁五线谱的密码 第一次翻开钢琴谱时&#xff0c;那些上下翻飞的音符就像天书般令人困惑。为什么同样的音符在不同位置听起来音高差异巨大&#xff1f;为什么低音谱号和高音谱号的"Do"位置完全不同&#xff1f;其…...

抖音内容批量下载技术方案:构建高效的多策略下载系统

抖音内容批量下载技术方案&#xff1a;构建高效的多策略下载系统 【免费下载链接】douyin-downloader A practical Douyin downloader for both single-item and profile batch downloads, with progress display, retries, SQLite deduplication, and browser fallback suppor…...

晨芯阳HC9616带防止逆流功能,500mA高速LDO

HC9616是一系列高精度&#xff0c;低功耗LDO线性稳压器&#xff0c;内部集成防止逆流保护功能、短路保护&#xff0c;过流保护等功能。输出具有高精度、低噪声、高纹波抑制比、低压差等特点&#xff0c;输出可使用小型陶瓷电容&#xff0c;良好的线性和负载调整特性。且具有使能…...

11个系统、8000张表,这家环保集团如何让沉睡的数据真正“用起来”

很多大型集团企业都有过这样一段经历&#xff1a;信息化建设做了好几轮&#xff0c;ERP上线了&#xff0c;OA部署了&#xff0c;生产监控系统也跑起来了&#xff0c;业务数据越积越厚——看起来数字化建设卓有成效。但真到需要数据的时候&#xff0c;才发现麻烦来了。财务要汇报…...

抖音无水印批量下载终极指南:3分钟学会免费下载视频、音乐和直播

抖音无水印批量下载终极指南&#xff1a;3分钟学会免费下载视频、音乐和直播 【免费下载链接】douyin-downloader A practical Douyin downloader for both single-item and profile batch downloads, with progress display, retries, SQLite deduplication, and browser fall…...

【AI面试临阵磨枪-57】如何防止 Prompt 注入、越狱、敏感信息泄露

一、 面试题目随着 Agent 接入业务系统&#xff0c;Prompt 注入&#xff08;Injection&#xff09;、越狱&#xff08;Jailbreak&#xff09;和敏感信息泄露&#xff08;PII Leakage&#xff09; 成为核心威胁。你如何从工程架构角度设计一套完整的安全防御体系&#xff1f;二、…...