利用VS2005编写文本编辑器,可以在TextBox、RichTextBox里实现语法高亮的。下面是使用RichTextBox控件实现语法高亮的方法,TextBox控件的实现方法和此类似。
2 rich.SelectionFont = new Font("宋体", 12, (FontStyle.Regular));
3 rich.SelectionColor = Color.Blue;
意思是,先选择第一个字母,按上面的设置,选择到了数字‘1’,然后设置这个字的字体大小,再设置字的颜色。
如果对关键字进行处理(这里只处理光标向后流动的情况)
首先添加输入事件
2
3 void rich_KeyDown(object sender, KeyEventArgs e)
4 {
5 //throw new Exception("The method or operation is not implemented.");
6 }
建立关键字
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事件发生时,向前查找
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 }
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 }
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控件的语法高亮。
若转载请注明出处: Spirit's Home
本文地址: http://www.7788sky.cn/post/CSharp_RichTextBox_yufagaoliang.html
0 Response to “C#实现TextBox、RichTextBox语法高亮”