0
votes

I'm trying to iterate through some pre-typed text in a Richtextbox and change the color of specific words/lines to a color depending on their prefix, thus far the different prefix's are [b], [f], and [e]. In this example I only use [b]. I've tried using while/foreach loops but they don't seem to iterate through the text. Below is the closest I've come to making it work but it only works on the first line of text. Any chance someone can point me in the correct direction?

 private void AboutBox_Load(object sender, EventArgs e)
    {
        textBox1.Select(0, 0);
        using (StringReader reader = new StringReader(richTextBox1.Text))
        {
            string line = string.Empty;
            do
            {
                line = reader.ReadLine();

                if ((line != null && line.Contains("[b]")))
                  {
                      richTextBox1.Select(richTextBox1.Text.IndexOf("[b]"), "[b]".Length);
                      richTextBox1.SelectionColor = Color.Green;
                  }
            } while (line != null);
        }
    }
3

3 Answers

3
votes

Instead of copying the text to a string, you can work directly with the RichTextBox via its Find() method:

    void AboutBox_Load(object sender, EventArgs e)
    {
        this.ColorPrefix(richTextBox1, "[b]", Color.Green);
        this.ColorPrefix(richTextBox1, "[f]", Color.Red); // change the color!
        this.ColorPrefix(richTextBox1, "[e]", Color.Yellow); // change the color!
    }

    private void ColorPrefix(RichTextBox rtb, string prefix, Color color)
    {
        int position = 0, index = 0;
        while ((index = rtb.Find(prefix, position, RichTextBoxFinds.None)) >= 0)
        {
            rtb.Select(index, prefix.Length);
            rtb.SelectionColor = color;
            position = index + 1;
        }
        rtb.Select(rtb.TextLength, 0);
    }
2
votes

This line will always select the same item:

richTextBox1.Select(richTextBox1.Text.IndexOf("[b]"), "[b]".Length);

So I would suggest something like this:

    private void AboutBox_Load(object sender, EventArgs e)
    {
        string text = richTextBox1.Text;
        int position = 0, index = 0;
        while ((index = text.IndexOf("[b]", position)) >= 0)
        {
            richTextBox1.Select(index, 3);
            richTextBox1.SelectionColor = Color.Green;
            position = index + 1;
        }
    }
0
votes

If you like to highlight syntax, I suggest using the FastColoredTextBox control:

enter image description here