语法突出显示无法正常工作

Syntax Highlighting not working properly

因此,我在 Visual Studio 2013 年一直在使用 C# 编写脚本编辑器,当然我希望将语法突出显示作为一项功能。 我有以下代码:

programTextBox.Enabled = false;
Regex cKeyWords = new Regex("(auto|break|case|char|const|continue|defaut|double|else|enum|extern|float|for|goto|if|int" +
                            "|long|register|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|while)");
int selectStart = this.programTextBox.SelectionStart;
int programCurrentLine = programTextBox.GetLineFromCharIndex(programTextBox.SelectionStart);
MatchCollection matches = cKeyWords.Matches(programTextBox.Lines[programCurrentLine].ToString());
foreach (Match match in matches)
{
   programTextBox.Select(match.Index, match.Length);
   programTextBox.SelectionColor = Color.Blue;
}
programTextBox.Select(selectStart, 0);
programTextBox.SelectionColor = Color.Black;
programTextBox.Enabled = true;

那么,它有什么作用?它在当前行中搜索一些特定的词。通过我的测试,我可以看出它实际上可以在几毫秒内找到这些单词。

但这并没有真正起作用。找到匹配项后,它会更改第一行的颜色。我的意思是?这是一个例子。假设我使用我的脚本编辑器编写这段代码:

#include <stdio.h>
int main(){
    ...
}

这段代码中int是关键字,所以必须变成Blue。但是,第一行的前三个字母变为 Blue。我还应该提到,这个示例 int 位于第二行的开头,这就是第一行的前三个字符发生变化的原因。

因此,我的代码可以找到关键字并找到它们的位置,但它不会更改这些词的颜色,而是在第一行应用更改。

有人可以提供解决方案吗?

编辑:我找到了解决这个问题的方法。只需检查下面我的回答。

苏哥,我居然找到解决办法了!

foreach (Match match in matches)
{
    programTextBox.Select(programTextBox.GetFirstCharIndexOfCurrentLine() + match.Index, match.Length);
    programTextBox.SelectionColor = Color.Blue;
}

(其余代码其实是一样的。)

Hans Passant 实际上是对的,match.Index 才是问题的根源。在玩弄并在评论的帮助下我发现使用 programTextBox.GetFirstCharIndexOfCurrentLine() + match.Index 解决了问题。

为什么?使用 programTextBox.GetFirstCharIndexOfCurrentLine() 我可以知道我必须在哪一行更改颜色,使用 match.Index 我可以知道当前行中找到的关键字所在的位置。

无论如何,我要感谢你 Hans Passant,因为你的建议实际上给了我这个想法!