c# - 遍历 RichTextBox 使特定单词加粗

标签 c# .net winforms richtextbox highlight

我写了一个真空管交叉引用程序。 我不知道如何迭代 RichTextBox1 以使请求的管值变为粗体。

搜索 6AU8A 时的现有输出

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

因此,我需要以粗体显示任何搜索词(本例中为 6AU8A)。 使用 VS 2019,针对 .NET 4.8.1 编译的 Windows 应用程序可在 Windows 7 和 10 PC 上运行。

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;
        }

最佳答案

一旦调用Find(),该值将被选择(如果存在)。然后您可以更改字体以包括粗体。 Find() 函数有一个“开始”位置,可让您查找下一个出现的位置。因此,您从 0 开始,然后添加搜索字符串的长度以获得下一个起始位置。如果返回的值为 -1,则不再有匹配项,您可以停止。

看起来像这样:

private void button1_Click(object sender, EventArgs e)
{
    BoldText("6AU8A"); // get your input from somewhere...
}

private void BoldText(String value)
{
    int startAt = 0;
    int indexToText = richTextBox1.Find(value, startAt, RichTextBoxFinds.None);
    while (indexToText != -1)
    {
        richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold);
        startAt = startAt + value.Length;
        indexToText = richTextBox1.Find(value, startAt, RichTextBoxFinds.None);
    }
}

这是在行动:

enter image description here

关于c# - 遍历 RichTextBox 使特定单词加粗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74744935/

相关文章:

c# - C# 中的三次鼠标单击?

c# - 动态编译 LINQ 查询以验证字典值

c# - 如何在两组数据中找到部分不同的项目子集?

c# - 以编程方式调用 C# 编译器来编译 C# 代码

c# - Webclient 的 DownloadStringCompleted 事件处理程序从未调用过

c# - ListView onScroll 事件

c# - 如何存储 Switch 语句中的 Cases 列表?

c# - 通过 COM 使用 C# 进行 InDesign Server 开发

c# - 获得最前沿的控制

c# - 将 ListBox DataSource 属性设置为 null 以更改列表项是否错误?