当前位置: 首页 > 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; }}}

http://www.mrgr.cn/news/80590.html

相关文章:

  • 采用qL-MPC技术进行小型固定翼无人机的路径跟随控制
  • LeetCode 2475 数组中不等三元组的数目
  • 【WRF教程第二期】WRF编译全过程:以4.5版本为例
  • SpringSpringBoot常用注解
  • Vue简介:构建现代Web应用的前端框架
  • 渗透利器-kali工具 (第五章-5) Metasploit漏洞利用模块二
  • 四、CSS3
  • Java集合 HashMap 原理解读(含源码解析)
  • 灵当crm pdf.php存在任意文件读取漏洞
  • C#速成(GID+图形编程)
  • C++之二:类和对象
  • 基于STM32设计的粮食仓库(粮仓)环境监测系统_284
  • GIN
  • Latex 转换为 Word(使用GrindEQ )(英文转中文,毕业论文)
  • ubuntu升级python版本
  • 15.初始接口1.0 C#
  • Windows环境 (Ubuntu 24.04.1 LTS ) 国内镜像,用apt-get命令安装RabbitMQ,java代码样例
  • Yolo中OBB的角度范围和角度损失设计思路
  • flink SQL实现mysql source sink
  • 面试题整理2---Nginx 性能优化全方案
  • next.js 存在缓存中毒漏洞(CVE-2024-46982)
  • Qt之修改窗口标题、图标以及自定义标题栏(九)
  • 登陆harbor发现证书是错误的, 那么如何更新harbor的证书呢
  • day4:tomcat—maven-jdk
  • SQL server学习07-查询数据表中的数据(下)
  • 24-12 空间转录组数据分析之分子niche与细胞niche