简体   繁体   中英

Changing background color of words in richTextBox after typing a special character

Using the richTextBox control, how to change in real time the background color of words that are separated by a comma, and put a blank space instead of the comma? A bit like the keywords' presentation of Stackoverflow.

The following string: "One, Two, Three, Four" can be converted to a list of strings with the items "One" - "Two" - "Three" - "Four" with the following code:

string FullString = "One, Two, Three, Four";
Regex rx = new Regex(", ");
List<string> ListOfStrings = new List<string>();
foreach (string newString in rx.Split(FullString))
{
     ListOfStrings.Add(newString);
}

Regarding the color you can take a look here: Rich Text Box how to highlight text block

To be able to do this in realtime I suggest you use the TextChanged event for the RTB and from there you can call a function changing the color. http://msdn.microsoft.com/en-us/library/system.windows.forms.control.textchanged.aspx

When this is done you can use the String.Replace(char, char) function to remove the comas and change them to blank spaces. http://msdn.microsoft.com/en-us/library/czx8s9ts.aspx

Here you have a small code red-colouring the background when certain word ("anything") is written in a richtextbox. I hope that this will be enough to help you understand how to interact with a richtextbox at runtime. Bear in mind that it is pretty simplistic: it colours "anything" only if it is first word you introduce; and stops coloring if you write any other character after it.

    int lastStart = 0;
    int lastEnd = 0;
    private void richTextBox1_TextChanged(object sender, EventArgs e)
    {
        richTextBox1.Select(lastStart, lastEnd + 1);

        if (richTextBox1.SelectedText.ToLower() == "anything")
        {
            richTextBox1.SelectionBackColor = Color.Red;
            lastStart = richTextBox1.SelectionStart + richTextBox1.SelectionLength;
        }
        else
        {
            richTextBox1.SelectionBackColor = Color.White;
        }

        lastEnd = richTextBox1.SelectionStart + richTextBox1.SelectionLength;
        richTextBox1.Select(lastEnd, 1);
    }

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