C#开发高亮语法编辑器(一)——TextBox ,RichTextBox 下载本文

内容发布更新时间 : 2024/6/2 8:17:04星期一 下面是文章的全部内容请认真阅读。

C#开发高亮语法编辑器(一)——TextBox ,RichTextBox

C#简单实现高亮语法编辑器(一)

——TextBox ,RichTextBox的局限性

一、RichTextBox基本设置 二、实现语法高亮 三、关键字提示 四、实现行号

就简单快速得开发文本编辑器TextBox 最为简单,大家用得也多,缺点是无法实现复杂的操作。RichTextBox虽然是则功能比它强大很多。

图 1.1 输入框控件关系

这里要实现以下功能的编辑器: 1、实现语法高亮; 2、关键字提示; 3、行号。

显然TextBox 无法完成我们的任务,虽然都派生自TextBoxBase,但就控制力而言RichTextBox比它优秀很多。这里选用RichTextBox尝试开发。

注:以下只讨论简单开发,不考虑复杂的关键字查找机制。

一、RichTextBox基本设置

这里先建立一个工程,建立窗体Form1。

可以简单添加RichTextBox控件,可以在Form1_Load中建立。代码如下:

1 this.WindowState = System.Windows.Forms.FormWindowState.Maximized; 2

3 RichTextBox rich = new RichTextBox(); 4 rich.Multiline = true;

5 rich.Height = this.Height - 100; 6 rich.Width = this.Width - 100; 7 rich.Left = 40; 8 rich.Top = 40;

9 rich.WordWrap = true; 10 rich.Text = \

11 rich.ScrollBars = RichTextBoxScrollBars.ForcedVertical; 12 this.Controls.Add(rich);

这样就建立了简单的RichTextBox,宽度和高度都设置了。没有做Form1窗体缩放的处理。

二、实现语法高亮

在RichTextBox里实现语法高亮还是非常简单的。可以使用 1 rich.Select(0,1);

2 rich.SelectionFont = new Font(\宋体\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(\6 }

建立关键字

1 public static List AllClass() 2 {

3 List list = new List(); 4 list.Add(\ 5 list.Add(\ 6 list.Add(\ 7 list.Add(\ 8 list.Add(\ 9 list.Add(\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(@\ 6 x = reg.Match(x).Value; 7

8 Regex reg2 = new Regex(@\ 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(\ 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(\宋体\ 8 else

9 tb.SelectionFont = new Font(\宋体\ //以下是把光标放到原来位置,并把光标后输入的文字重置 10 tb.Select(i,0);

11 tb.SelectionFont = new Font(\宋体\12 tb.SelectionColor = Color.Black; 13 }

这样就完成了高亮工作。

三、关键字提示