How to implement basic syntax highlighting in Winforms RichTextBox?

ε祈祈猫儿з 提交于 2019-12-07 06:10:53

问题


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 parsing 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?


回答1:


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




回答2:


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.




回答3:


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.




回答4:


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




回答5:


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


来源:https://stackoverflow.com/questions/5982342/how-to-implement-basic-syntax-highlighting-in-winforms-richtextbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!