当前位置: 首页 > 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;报错的原因都是由于没有获取…...

Qt之自定义标题栏拓展(十)

Qt开发 系列文章 - user-defined-titlebars&#xff08;十&#xff09; 目录 前言 一、方式一 1.效果演示 2.创建标题栏类 3.可视化UI设计 4.定义相关函数 5.使用标题栏类 二、方式二 1.效果演示 2.创建标题栏类 3.定义相关函数 1.初始化函数 2.功能函数 3.窗口关…...

Verilog中initial的用法

在 Verilog 语言中&#xff0c;initial 语句用于在仿真开始时执行一次性初始化操作。它是顺序执行的&#xff0c;用来描述在仿真启动时立即运行的代码块&#xff0c;通常用于赋初值、生成波形或控制信号行为。 语法 initial begin // 语句1 // 语句2 ... end特点 只…...

(14)D-FINE网络,爆锤yolo系列

yolo过时了&#xff1f;传统的yolo算法在小目标检测方面总是不行&#xff0c;最新算法DEIM爆锤yolo&#xff0c;已经替yolo解决。 一、创新点 ​ 这个算法名为DEIM&#xff0c;全称是DETR with Improved Matching for Fast Convergence&#xff0c;其主要创新点在于提出了一…...

Python :冬至快乐

第1部分&#xff1a;基础设置 首先创建一个新的 Python 文件&#xff0c;命名为 fireworks.py。 步骤 1.1: 导入必要的库 import pygame import random import sys from pygame.locals import * import math import time这些库的作用&#xff1a; pygame: 用于创建游戏和图…...

重拾设计模式--状态模式

文章目录 状态模式&#xff08;State Pattern&#xff09;概述状态模式UML图作用&#xff1a;状态模式的结构环境&#xff08;Context&#xff09;类&#xff1a;抽象状态&#xff08;State&#xff09;类&#xff1a;具体状态&#xff08;Concrete State&#xff09;类&#x…...

稀疏矩阵的存储与计算 gaxpy

1, gaxpy 数学公式 其中&#xff1a; &#xff0c; &#xff0c; 2, 具体实例 3&#xff0c;用稠密矩阵的方法 本节将用于验证第4节中的稀疏计算的结果 hello_gaxpy_dense.cpp #include <stdio.h> #include <stdlib.h>struct Matrix_SP {float* val; //…...

基于LabVIEW的USRP信道测量开发

随着无线通信技术的不断发展&#xff0c;基于软件无线电的设备&#xff08;如USRP&#xff09;在信道测量、无线通信测试等领域扮演着重要角色。通过LabVIEW与USRP的结合&#xff0c;开发者可以实现信号生成、接收及信道估计等功能。尽管LabVIEW提供了丰富的信号处理工具和图形…...

基于LSTM长短期记忆神经网络的多分类预测【MATLAB】

在深度学习中&#xff0c;长短期记忆网络&#xff08;LSTM, Long Short-Term Memory&#xff09;是一种强大的循环神经网络&#xff08;RNN&#xff09;变体&#xff0c;专门为解决序列数据中的长距离依赖问题而设计。LSTM因其强大的记忆能力&#xff0c;广泛应用于自然语言处理…...

物联网:全面概述、架构、应用、仿真工具、挑战和未来方向

中文论文标题&#xff1a;物联网&#xff1a;全面概述、架构、应用、仿真工具、挑战和未来方向 英文论文标题&#xff1a;Internet of Things: a comprehensive overview, architectures, applications, simulation tools, challenges and future directions 作者信息&#x…...

volatility2工具的使用vol2工具篇

vol2工具 命令格式&#xff1a;vol.py -f [image] --profile[profile] [plugin] 1、查看系统的操作版本&#xff0c;系统镜像信息 2.查看用户名密码信息&#xff0c;当前操作系统中的password hash&#xff0c;例如SAM文件内容 3.从注册表提取LSA密钥信息&#xff08;已解密&…...