利用VS2005编写文本编辑器,可以在TextBox、RichTextBox里实现语法高亮的。下面是使用RichTextBox控件实现语法高亮的方法,TextBox控件的实现方法和此类似。
1 rich.Select(0,1);
2 rich.SelectionFont = new Font("宋体", 12, (FontStyle.Regular));
3 rich.SelectionColor = Color.Blue;
意思是,先选择第一个字母,按上面的设置,选择到了数字‘1’,然后设置这个字的字体大小,再设置字的颜色。
如果对关键字进行处理(这里只处理光标向后流动的情况)
首先添加输入事件
1 rich.KeyDown += new KeyEventHandler(rich_KeyDown); //这一行添加到Form1_Load中
2
3 void rich_KeyDown(object sender, KeyEventArgs e)
4 {
5 //throw new Exception("The method or operation is not implemented.");
6 }
建立关键字
1 public static List<string> AllClass()
2 {
3 List<string> list = new List<string>();
4 list.Add("function");
5 list.Add("return");
6 list.Add("class");
7 list.Add("new");
8 list.Add("extends");
9 list.Add("var");
10 return list;
11 }
当KeyDown事件发生时,向前查找
1 //返回搜索字符
2 public static string GetLastWord(string str,int i)
3 {
4 string x = str;
5 Regex reg= new Regex(@"/s+[a-z]+/s*",RegexOptions.RightToLeft);
6 x = reg.Match(x).Value;
7
8 Regex reg2 = new Regex(@"/s");
9 x = reg2.Replace(x, "");
10 return s;
11 }
1 void rich_KeyDown(object sender, KeyEventArgs e)
2 {
3 RichTextBox rich = (RichTextBox)sender;
4 //throw new Exception("The method or operation is not implemented.");
5 string s = GetLastWord(rich.Text, rich.SelectionStart);
6
7 if (AllClass().IndexOf(s) > -1)
8 {
9 MySelect(rich, rich.SelectionStart, s, Color.CadetBlue, true);
10 }
11 }
1 //设定颜色
2 public static void MySelect(System.Windows.Forms.RichTextBox tb, int i, string s, Color c,bool font)
3 {
4 tb.Select(i - s.Length, s.Length);
5 tb.SelectionColor = c;
//是否改变字体
6 if(font)
7 tb.SelectionFont = new Font("宋体", 12, (FontStyle.Bold));
8 else
9 tb.SelectionFont = new Font("宋体", 12, (FontStyle.Regular));
//以下是把光标放到原来位置,并把光标后输入的文字重置
10 tb.Select(i,0);
11 tb.SelectionFont = new Font("宋体", 12, (FontStyle.Regular));
12 tb.SelectionColor = Color.Black;
13 }
这样就实现了RichTextBox控件的语法高亮。