VS2019(.NET4.8.1)如何遍历RichTextBox将指定电子管型号设为粗体?
电子管交叉参考程序:RichTextBox批量匹配文本粗体设置问题
环境与需求
- 开发环境:Visual Studio 2019,Windows桌面应用,基于.NET Framework 4.8.1编译
- 支持系统:Windows 7、Windows 10
- 核心需求:将RichTextBox控件中所有匹配指定电子管型号(示例:6AU8A)的文本设置为粗体
- 当前问题:已实现
FindMyText方法,但仅能定位第一个匹配项,无法遍历完成所有匹配文本的格式设置
当前搜索输出示例
Tube Cross1 Cross2 Cross3 Qty Location 6AU8 6AU8A 6BH8 6AW8 2 PM BOX 3 6AU8A 6AU8 6BH8 6AW8 6 BOX 9 6BA8A 6AU8 6AU8A 8AU8A 1 BOX 11 6CX8 6AU8A 6EB8 6GN8 2 BOX 16 6EH5 6AU8A 2081 6AW8A# 1 BOX 19 6GH8 6EA8 6GH8A 6AU8A 2 BOX 23 6GH8A 6GH8 6EA8 6AU8A 10 BOX 22 6GH8A 6GH8 6EA8 6AU8A 5 BOX 23
现有FindMyText方法代码
public int FindMyText(string text) { length = text.Length; // Initialize the return value to false by default. int returnValue = -1; // Ensure that a search string has been specified and a valid start point. if (text.Length > 0) { // Obtain the location of the first character found in the control // that matches any of the characters in the char array. int indexToText = richTextBox1.Find(text); // Determine whether the text was found in richTextBox1. if (indexToText >= 0) { // Return the location of the character. returnValue = indexToText; start = indexToText; } } return returnValue; }
解决方案:遍历所有匹配项并设置粗体
原方法仅查找第一个匹配项,需修改为循环查找所有匹配位置并逐一设置格式:
public void HighlightAllMatches(string text) { if (string.IsNullOrEmpty(text)) return; // 可选:清除之前的高亮格式,避免多次搜索后格式叠加 richTextBox1.SelectAll(); richTextBox1.SelectionFont = new Font(richTextBox1.Font, FontStyle.Regular); richTextBox1.DeselectAll(); int startIndex = 0; int textLength = text.Length; int foundIndex; // 循环查找所有匹配文本 while ((foundIndex = richTextBox1.Find(text, startIndex, RichTextBoxFinds.None)) != -1) { // 选中当前匹配的文本 richTextBox1.Select(foundIndex, textLength); // 将选中文本设置为粗体 richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold); // 更新起始搜索位置,避免重复匹配同一文本 startIndex = foundIndex + textLength; // 防止索引超出文本范围,终止循环 if (startIndex >= richTextBox1.Text.Length) break; } }
核心逻辑说明
- 循环查找:通过
RichTextBox.Find的重载方法,每次从上次匹配的结束位置开始搜索 - 格式设置:选中匹配文本后,修改
SelectionFont为粗体样式 - 索引更新:每次匹配完成后,将起始索引移至当前匹配项的下一个字符,避免无限循环
- 可选清除格式:若需要多次搜索,建议先清除原有高亮,保证格式统一
内容的提问来源于stack exchange,提问作者Ijustgiveup
相关产品推荐
相关产品推荐

