如何在richtextbox C#中改变等号的颜色

how to change color of equal signs in richtextbox c#

我想更改等号的颜色,就像在用户书写文本时在 notepad++ 中发生的那样。我的代码正在运行,但光标停留在一个地方,用户不能在文本之间写任何东西,它只允许最后写,也没有检测到 = 之后是否存在换行符。怎么做?

private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{ 
    equal();     
}

public void equal()
{ 
    start = richTextBox1.Text.Length - 1;
    length = 1;

    richTextBox1.SelectionStart = start;
    richTextBox1.SelectionLength = length;
    string settext = richTextBox1.SelectedText;

    if ( settext ==Convert.ToString('='))
    {   
        richTextBox1.SelectionColor = Color.Purple;   
    }
}
Add event to your richtext box for  text changed:

private void richTextBox1_TextChanged(object sender, EventArgs e)
    {
        this.ChangeColor("=", Color.Purple);

    }



private void ChangeColor(string word, Color color)
{
    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), word.Length);
            this.richTextBox1.SelectionColor = color;
            this.richTextBox1.Select(selectStart, 0);
            this.richTextBox1.SelectionColor = Color.Black;
        }
    }
}

请使用 richTextBox_TextChanged 事件更改颜色。我在申请中遇到过一次这个问题。