C#richbox更改颜色

时间:2017-05-06 16:14:08

标签: c# richtextbox

    string words;
    private void Colors(object sender, EventArgs e)
    {
        Color tags = new Color();
        tags = Color.FromArgb(33, 66, 99);
    }
    private Color FromRgbExample()
    {
        // Create a green color using the FromRgb static method.
        Color myRgbColor = new Color();
        myRgbColor = Color.FromArgb(0, 255, 0);
        return myRgbColor;
    }
    private void CheckKeyword(string word, Color color, int startIndex)
    {
        words = word;
        if (this.richTextBox1.Text.Contains(word))
        {
            int index = -1;
            int selectStart = this.richTextBox1.SelectionStart;

            while ((index = this.richTextBox1.Text.IndexOf(word, (index + 1))) != -1)
            {

                this.richTextBox1.Select((index + startIndex), word.Length);
                this.richTextBox1.SelectionColor = color;
                this.richTextBox1.Select(selectStart, 0);
                this.richTextBox1.SelectionColor = Color.Black;
            }
        }
    }
    private void richTextBox1_TextChanged(object sender, EventArgs e)
    { 

        this.CheckKeyword("html", Color.Green, 0);
        this.CheckKeyword("head", Color.Green, 0);

        if (richTextBox1.Text.Contains(words) == false)
        {
            this.richTextBox1.SelectionColor = Color.Black;
        }
    }


}

如果我写“html”文字会有绿色,如果我删除“html”中的任何字母,他仍然会是绿色。 删除一封将“html”颜色改回黑色的字母后我该怎么办?

1 个答案:

答案 0 :(得分:0)

private void richTextBox1_TextChanged(object sender, EventArgs e)
{ 
    richTextBox1.Select(0,richTextBox1.Text.Length -1);
    richTextBox1.SelectionColor = Color.Black;
    richTextBox1.SelectionStart = 0;

    this.CheckKeyword("html", Color.Green, 0);
    this.CheckKeyword("head", Color.Green, 0);

    if (richTextBox1.Text.Contains(words) == false)
    {
        this.richTextBox1.SelectionColor = Color.Black;
    }
}