如果键入的是除字母数字或者下划线外的字符,那么受影响的是以该字符为界的两个单词,比如在“intint”中间插入空格是其被分解成以空格为界的两个“int”,那么就对这两个单词进行判断就可以了。
以下代码描述了上述思想(其中GetCurrentword()用于取得指定位置处的单词,Dye()用于将指定文本染色)
1 private void richTextBox_CodeArea_TextChanged(object sender, EventArgs e)
2 {
3 RichTextBox rbx = (RichTextBox)sender;
4 int start, length;
5 int ins = this.richTextBox_CodeArea.SelectionStart;
6
7 char c = ' ';
8 string word = "";
9 if (ins > 0)
10 {
11 c = this.richTextBox_CodeArea.Text[ins - 1];
12 }
13 else
14 {
15 if (this.richTextBox_CodeArea.Text.Length > 0)
16 {
17 c = this.richTextBox_CodeArea.Text[0];
18 }
19 }
20
21 //取得插入点两边的两个单词,并判断这两个单词是否是关键字.
22 if (!char.IsLetter(c) && !Char.IsDigit(c) && c != '_')
23 {
24 //将字符c染色
25 this.Dye(ins - 1, 1, this.textColor, this.textColor);
26
27 word = this.GetCurrentword(ins - 1, out start, out length);
28
29 Color cl = IsKey(word) ? this.keyColor : this.textColor;
30 this.Dye(start, length, cl, this.textColor);
31
32 word = this.GetCurrentword(ins + 1, out start, out length);
33 cl = IsKey(word) ? this.keyColor : this.textColor;
34 this.Dye(start, length, cl, this.textColor);
35
36 }
37 else//取得插入点处的单词并判断其是否是关键字
38 {
39 word = this.GetCurrentword(ins, out start, out length);
40 Color cl = IsKey(word) ? this.keyColor : this.textColor;
41 this.Dye(start, length, cl, this.textColor);
42 }
43
44 }
45