C#Richtextbox特殊字符的字体和颜色

时间:2015-07-18 21:54:40

标签: c# fonts richtextbox

我想知道如何更改richtextbox中某些字符的颜色。

我想更改四个关键字的颜色:"CONDITION","FIRSTCONDITION","SECONDCONDITION","ACTION"

以下是我在Richtextbox中的文字

"If (CONDITION) then"
"And (FIRSTCONDITION)&(SECONDCONDITION)"
"While (CONDITION) do(ACTION)"

最后我的代码

public Form1()
{
    InitializeComponent();


}

private void MyRichTextBox(object sender, EventArgs e)
{
    richTextBox1.Font = new Font("Arial", 12f, FontStyle.Bold);
    string[] words =
    {  "If (CONDITION) then","And (FIRSTCONDITION)&(SECONDCONDITION)",
"While (CONDITION) do(ACTION)"
    };

    for (int i = 0; i < words.Length; i++)
    {
    string word = words[i];
    {
        richTextBox1.AppendText(word);
    }
    }
MyRichTextBox.Settings.Keywords.Add("CONDITION");
MyRichTextBox.Settings.Keywords.Add("FIRSTCONDITION");
MyRichTextBox.Settings.Keywords.Add("SECONDCONDITION");
MyRichTextBox.Settings.Keywords.Add("ACTION");
MyRichTextBox.Settings.KeywordColor = Color.Blue;
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这应该有效,

using System.Text.RegularExpressions;

List<string> l = new List<string>();
        l.Add("CONDITION");
        l.Add("FIRSTCONDITION");
        l.Add("SECONDCONDITION");
        l.Add("ACTION");

            foreach (var v in l)
            {
                int count = Regex.Matches(rtbxTest.Text, v).Count;//count occurrences of string
                int WordLen = v.Length;
                int startFrom=0;
                for (int i = 0; i < count; i++)    
                {
                    rtbxTest.SelectionStart = rtbxTest.Text.IndexOf(v, startFrom);
                    rtbxTest.SelectionLength = WordLen;
                    rtbxTest.SelectionColor = Color.Red;
                    startFrom = rtbxTest.Text.IndexOf(v, startFrom) + WordLen;

                }
            }

这会查找特定字符串的所有匹配项并更改其颜色。