C#实现TextBox、RichTextBox语法高亮



利用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控件的语法高亮。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值