简体   繁体   中英

How can i find and select text in RichTextBox by color

I have the simplest text editor with RichTextBox where user can change color of selected words. After that, I need to find the colorized words and change them depending on the color. For example, find in the text all the words of red and add an additional symbol to them. What's the simplest way to do this in C#?

A way could be to select each word of the RichTextBox and then get the color of that word.

I think you may divide your problem in subproblems:

1. Get words

You can access to the RichBoxText content using the Text property and then you can get the words by splitting by spaces, new line and tabs. Of course you can add other separator.

2. Select each word and get the color

The IndexOf method of the String class can be useful in this situation. You can get the position of a specified word (specifying the start position) in the RichTextBox by using richTextBox.Text.IndexOf("word", startIndex) . You can select that word by using the Select method of the RichTextBox and then get the color using the SelectionColor property.

3. Add a character It's simple to add a character after the specified word if you know where the latter starts and finishes. You can get the selected word by using the SelectedText property after selecting the work using the Select method (see point 2). Just assign the concatenation of the word and the character to the SelectedText property.

Here an example (usage on code comments):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM