简体   繁体   中英

Issues changing color in richtextbox

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

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

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

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

在此处输入图片说明

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