Reputation: 79
I'd like to know how to change the color of some characters in the richtextbox.
I want to change the color for the four key words:"CONDITION","FIRSTCONDITION","SECONDCONDITION","ACTION"
Here is my text in the Richtextbox
"If (CONDITION) then"
"And (FIRSTCONDITION)&(SECONDCONDITION)"
"While (CONDITION) do(ACTION)"
At last my code
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;
}
Thanks for your help.
Upvotes: 0
Views: 530
Reputation: 870
This should work,
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;
}
}
This finds all the occurrences of a particular string and changes its color.
Upvotes: 1