设置代码Code高亮显示成蓝色

时间:2023-03-09 08:11:43
设置代码Code高亮显示成蓝色

  下面方法是让设置的关键字高亮显示,考虑到了注释与字符串的影响,所以备用,以便将来能够用到.

        private static void ColorizeCode(RichTextBox rtb)
{
string[] keywords = {"as", "do", "if", "in", "is", "for", "int", "new", "out", "ref", "try", "base",
"bool", "byte", "case", "char", "else", "enum", "goto", "lock", "long", "null",
"this", "true", "uint", "void", "break", "catch", "class", "const", "event", "false",
"fixed", "float", "sbyte", "short", "throw", "ulong", "using", "where", "while",
"yield", "double", "extern", "object", "params", "public", "return", "sealed",
"sizeof", "static", "string", "struct", "switch", "typeof", "unsafe", "ushort",
"checked", "decimal", "default", "finally", "foreach", "partial", "private",
"virtual", "abstract", "continue", "delegate", "explicit", "implicit", "internal",
"operator", "override", "readonly", "volatile",
"interface", "namespace", "protected", "unchecked",
"stackalloc",
"from", "in", "where", "select", "join", "equals", "let", "on", "group", "by",
"into", "orderby", "ascending", "descending", "var"};
string text = rtb.Text; rtb.SelectAll();
rtb.SelectionColor = rtb.ForeColor; foreach (String keyword in keywords)
{
int keywordPos = rtb.Find(keyword, RichTextBoxFinds.MatchCase | RichTextBoxFinds.WholeWord);
while (keywordPos != -)
{
int commentPos = text.LastIndexOf("//", keywordPos, StringComparison.OrdinalIgnoreCase);
int newLinePos = text.LastIndexOf("\n", keywordPos, StringComparison.OrdinalIgnoreCase);
int quoteCount = ;
int quotePos = text.IndexOf("\"", newLinePos + , keywordPos - newLinePos, StringComparison.OrdinalIgnoreCase);
while (quotePos != -)
{
quoteCount++;
quotePos = text.IndexOf("\"", quotePos + , keywordPos - (quotePos + ), StringComparison.OrdinalIgnoreCase);
} if (newLinePos >= commentPos && quoteCount % == )
rtb.SelectionColor = Color.Blue; keywordPos = rtb.Find(keyword, keywordPos + rtb.SelectionLength, RichTextBoxFinds.MatchCase | RichTextBoxFinds.WholeWord);
}
} rtb.Select(, );
}