2
Answers

Problem with richTextBox colour

Federico Ramirez

Federico Ramirez

16y
5.7k
1
Hi, im trying to make a very simple syntax highlighter, just highlight some keywords, but i cant get it to work, this is the code i hav so far

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
Regex r = new Regex("\\n");
String [] lines = r.Split(richTextBox1.Text);
foreach (string l in lines)
{
ParseLine(l);
}
}

void ParseLine(string line)
{
Regex r = new Regex("[\\s\\t\\n{}():;]");
String[] tokens = r.Split(line);
foreach (string token in tokens)
{
richTextBox1.SelectionColor = Color.Black;

String[] keywords = { "program", "begin", "end" };

for (int i = 0; i < keywords.Length; i++)
{
if (keywords[i] == token)
{
//richTextBox1.SelectionStart = richTextBox1.Text.Length - keywords[i].Length;
//richTextBox1.SelectionLength = keywords[i].Length;
richTextBox1.SelectionColor = Color.Blue;
}
}
}
}
It seems i have to select the text to colour it, but when i do it then starts from the beggining of the keyword...
Answers (2)