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个前端上报的异常,报错的原因都是由于没有获取…...
iOS 26 携众系统重磅更新,但“苹果智能”仍与国行无缘
美国西海岸的夏天,再次被苹果点燃。一年一度的全球开发者大会 WWDC25 如期而至,这不仅是开发者的盛宴,更是全球数亿苹果用户翘首以盼的科技春晚。今年,苹果依旧为我们带来了全家桶式的系统更新,包括 iOS 26、iPadOS 26…...
脑机新手指南(八):OpenBCI_GUI:从环境搭建到数据可视化(下)
一、数据处理与分析实战 (一)实时滤波与参数调整 基础滤波操作 60Hz 工频滤波:勾选界面右侧 “60Hz” 复选框,可有效抑制电网干扰(适用于北美地区,欧洲用户可调整为 50Hz)。 平滑处理&…...
2024年赣州旅游投资集团社会招聘笔试真
2024年赣州旅游投资集团社会招聘笔试真 题 ( 满 分 1 0 0 分 时 间 1 2 0 分 钟 ) 一、单选题(每题只有一个正确答案,答错、不答或多答均不得分) 1.纪要的特点不包括()。 A.概括重点 B.指导传达 C. 客观纪实 D.有言必录 【答案】: D 2.1864年,()预言了电磁波的存在,并指出…...
拉力测试cuda pytorch 把 4070显卡拉满
import torch import timedef stress_test_gpu(matrix_size16384, duration300):"""对GPU进行压力测试,通过持续的矩阵乘法来最大化GPU利用率参数:matrix_size: 矩阵维度大小,增大可提高计算复杂度duration: 测试持续时间(秒&…...
华为云Flexus+DeepSeek征文|DeepSeek-V3/R1 商用服务开通全流程与本地部署搭建
华为云FlexusDeepSeek征文|DeepSeek-V3/R1 商用服务开通全流程与本地部署搭建 前言 如今大模型其性能出色,华为云 ModelArts Studio_MaaS大模型即服务平台华为云内置了大模型,能助力我们轻松驾驭 DeepSeek-V3/R1,本文中将分享如何…...
Typeerror: cannot read properties of undefined (reading ‘XXX‘)
最近需要在离线机器上运行软件,所以得把软件用docker打包起来,大部分功能都没问题,出了一个奇怪的事情。同样的代码,在本机上用vscode可以运行起来,但是打包之后在docker里出现了问题。使用的是dialog组件,…...
JS手写代码篇----使用Promise封装AJAX请求
15、使用Promise封装AJAX请求 promise就有reject和resolve了,就不必写成功和失败的回调函数了 const BASEURL ./手写ajax/test.jsonfunction promiseAjax() {return new Promise((resolve, reject) > {const xhr new XMLHttpRequest();xhr.open("get&quo…...
Web后端基础(基础知识)
BS架构:Browser/Server,浏览器/服务器架构模式。客户端只需要浏览器,应用程序的逻辑和数据都存储在服务端。 优点:维护方便缺点:体验一般 CS架构:Client/Server,客户端/服务器架构模式。需要单独…...
WPF八大法则:告别模态窗口卡顿
⚙️ 核心问题:阻塞式模态窗口的缺陷 原始代码中ShowDialog()会阻塞UI线程,导致后续逻辑无法执行: var result modalWindow.ShowDialog(); // 线程阻塞 ProcessResult(result); // 必须等待窗口关闭根本问题:…...
微服务通信安全:深入解析mTLS的原理与实践
🔥「炎码工坊」技术弹药已装填! 点击关注 → 解锁工业级干货【工具实测|项目避坑|源码燃烧指南】 一、引言:微服务时代的通信安全挑战 随着云原生和微服务架构的普及,服务间的通信安全成为系统设计的核心议题。传统的单体架构中&…...
