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...
Problem with richTextBox colour
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
Federico RamirezPosted Apr 30, 2008, 6:09 AM
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.Select(richTextBox1.Text.Length - keywords[i].Length, keywords[i].Length); //richTextBox1.SelectionLength = keywords[i].Length; richTextBox1.SelectionColor = Color.Blue; richTextBox2.Text = Convert.ToString(richTextBox1.Text.Length); richTextBox1.DeselectAll(); } } } }Scott LyslePosted Apr 30, 2008, 5:04 AM
To select a word from a rich text box control, you use richtextbox.Select(startPosition, Length). Once you have selected it, you can operate on the selection; the following will cycle between bold and unbolded for example:
if (!(rtbDoc.SelectionFont == null))
{
System.Drawing.Font currentFont = rtbDoc.SelectionFont;
System.Drawing.FontStyle newFontStyle;
newFontStyle = rtbDoc.SelectionFont.Style ^ FontStyle.Bold;
rtbDoc.SelectionFont = new Font(currentFont.FontFamily, currentFont.Size,
newFontStyle);
}
To change the selection's color, you'd do something like this (this shows using a color dialog):
ColorDialog1.Color = rtbDoc.ForeColor;
if (ColorDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
rtbDoc.SelectionColor = ColorDialog1.Color;
}