How to implement basic syntax highlighting in Winforms RichTextBox?

I have a list of words that I want to highlight in my control RichTextBox, I have an idea on how to do this, but I have a problem parsing everything to separate words.

How can I parse a string or all text into separate words and then list them and color them using the method RichTextBox.Select().

Is this a good way? Is there a better / faster way?

+5
source share
5 answers

RichTextBox.Find(String, Int32, Int32, RichTextBoxFinds), . , .

, .

http://msdn.microsoft.com/en-us/library/yab8wkhy.aspx

+2

Avalon Edit RichTextBox, . , # develop. , , , #develop, .

+2

string.Split. , .

: link1 link2

:

+1

You can use the RichTextBox.Find method to find a string in a RichTextBox. This method returns the position of the found text. In the sample code, text will be highlighted in this link.

+1
source

This is probably not the fastest way, but it works.
First call ClearHighLightingto delete the previous ones, and then callSetHighLighting

private readonly List<HighLight> _highLights = new List<HighLight>();
private class HighLight
{
  public int Start { get; set; }
  public int End { get; set; }
}

public void SetHighLighting(string text)
{

    // Clear Previous HighLighting
    ClearHighLighting();

    if (text.Length > 0)
    {
        int startPosition = 0;
        int foundPosition = 0;            
        while (foundPosition > -1)
        {
            foundPosition = richTextBox1.Find(text, startPosition, RichTextBoxFinds.None);
            if (foundPosition >= 0)
            {
                richTextBox1.SelectionBackColor = Color.Yellow;
                int endindex = text.Length;
                richTextBox1.Select(foundPosition, endindex);                        
                startPosition = foundPosition + endindex;                        
                _highLights.Add(new HighLight() { Start = foundPosition, End = endindex });
            }
        }
    }
}

public void ClearHighLighting()
{
    foreach (var highLight in  _highLights)
    {
        richTextBox1.SelectionBackColor = richTextBox1.BackColor;
        richTextBox1.Select(highLight.Start, highLight.End);                        
    }
    _highLights.Clear();
}
+1
source

All Articles