开发者

How to implement basic syntax highlighting in Winforms RichTextBox?

开发者 https://www.devze.com 2023-03-05 05:54 出处:网络
I have a list of words I want to highlight in my RichTextBox control, I have an idea on how to do it but having a problem with p开发者_JAVA百科arsing everything to separate words.

I have a list of words I want to highlight in my RichTextBox control, I have an idea on how to do it but having a problem with p开发者_JAVA百科arsing everything to separate words.

How can I parse a line or the whole text into separate words and then enumerate over them and color them using RichTextBox.Select() method.

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


Use the RichTextBox.Find(String, Int32, Int32, RichTextBoxFinds) method to find your strings in the control. You can then iterate by changing the Start point to the point after the current word.

Not sure on the performance of this scheme but it will work.

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


You can use Avalon Edit instead of a RichTextBox, it's free. It is the editor used in #develop. I think you may have to pull the assembly out of the #develop source download but it is worth it.


You can use the RichTextBox.Find method in order to find a string in your RichTextBox. This method returns the position of the text it found. The code sample in that link will highlight the text.


Try string.Split method. It return you array of strings splitted by delimiter.

Also you may found usefull those links: link1 link2

And even more: there is a fine example of similar app


Probably not the fastest way but it works.
First call ClearHighLighting to clear previous and then call SetHighLighting

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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消