如何在richtextbox c#中更改等号的颜色

时间:2015-09-28 09:33:23

标签: c# winforms richtext

我希望在用户编写文本时更改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;   
    }
}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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