Created
May 14, 2012 13:45
-
-
Save sinairv/2694067 to your computer and use it in GitHub Desktop.
Find string and set its color in a RichTextBox
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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