Skip to content

Instantly share code, notes, and snippets.

@sinairv
Created May 14, 2012 13:45
Show Gist options
  • Save sinairv/2694067 to your computer and use it in GitHub Desktop.
Save sinairv/2694067 to your computer and use it in GitHub Desktop.
Find string and set its color in a RichTextBox
// searches an arbitrary string
public static void FindStringAndSetColor(RichTextBox rtb, string key, Color color)
{
int lastIndex = -1;
do
{
int found = rtb.Find(key, lastIndex + 1, RichTextBoxFinds.None);
if (found >= 0)
{
rtb.Select(found, key.Length);
rtb.SelectionColor = color;
}
lastIndex = found;
} while (lastIndex >= 0);
}
// searches the whole word
public static void FindTokenAndSetColor(RichTextBox rtb, string key, Color color)
{
int newLineOffset = Environment.NewLine.Length - 1; // "\r\n" - "\n";
int lineStart = 0;
foreach (string line in rtb.Lines)
{
foreach (Match match in Regex.Matches(line, String.Format(@"\b{0}\b", key)))
{
rtb.Select(lineStart + match.Index, match.Length);
rtb.SelectionColor = color;
}
lineStart += line.Length + newLineOffset;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment