【问题标题】:How can i find and select text in RichTextBox by color如何在 RichTextBox 中按颜色查找和选择文本
【发布时间】:2018-01-31 17:02:52
【问题描述】:

我有最简单的带有 RichTextBox 的文本编辑器,用户可以在其中更改所选单词的颜色。之后,我需要找到彩色单词并根据颜色进行更改。例如,在文本中找到所有红色的单词并为其添加一个附加符号。在 C# 中执行此操作的最简单方法是什么?

【问题讨论】:

  • 最简单的就是使用第三者
  • 向后循环并选择每个单词并检查 SelectionColor 值。

标签: c# .net richtextbox


【解决方案1】:

一种方法是选择 RichTextBox 的每个单词,然后获取该单词的颜色。

我认为您可以将问题划分为子问题:

1.获取单词

您可以使用Text 属性访问RichBoxText 内容,然后您可以通过空格、换行符和制表符拆分来获取单词。当然你可以添加其他分隔符。

2。选择每个单词并获取颜色

String 类的IndexOf 方法在这种情况下很有用。可以通过richTextBox.Text.IndexOf("word", startIndex)获取指定单词在RichTextBox中的位置(指定起始位置)。您可以使用 RichTextBox 的 Select 方法选择该单词,然后使用 SelectionColor 属性获取颜色。

3.添加角色 如果您知道后者的开始和结束位置,那么在指定单词之后添加一个字符很简单。在使用Select 方法选择作品后,您可以使用SelectedText 属性获取所选单词(见第2 点)。只需将单词和字符的串联分配给SelectedText 属性即可。

这里是一个例子(在代码 cmets 上的用法):

// Word with specified color to which add a symbol
var searchedColor = Color.Gray;

// Reset selection
richTextBox1.SelectionStart = 0;
richTextBox1.SelectionLength = 0;

// Symbol to add to the word
const string symbol = "!";

// List of words, maybe you want to use a custom separator
var words = richTextBox1.Text.Split(new char[] { ' ', '\n', '\t' }, StringSplitOptions.RemoveEmptyEntries);

int index = -1;

foreach (var word in words)
{
    index = richTextBox1.Text.IndexOf(word, (index + 1));

    if (index > -1)
    {
        richTextBox1.Select(index, word.Length);

        // If the selected text as the specified color
        if (richTextBox1.SelectionColor == searchedColor)
        {
            //Add the symbol
            richTextBox1.SelectedText = word + symbol;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2014-03-11
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多