本文是我在学习VB.net过程中编写的,用到的技术简单,内容较粗糙。所涉及到的源代码没有
版权, 可以任意的传播、 复制及修改。 但请记得给我也发一份, 大家可以相互
学习。 我的邮箱stefsy_lee@qq HighlighterSystem.Windows.Forms.RichTextBox,添加了几个属性和方法,如下
该类使用正则表达式来获得相应的字符串匹配项集合MatchCollection,再遍历该集合, 从每个Match项来获得RichTextBox的Select方法的两个参数, 选择起始位置和选择长度。 再用RichTextBox
的SelectionColor来设置颜色(还可进行扩展,修改字体、字号等)。
源代码文件:
‘Class.vb Imports System.Drawing Imports Microsoft.VisualBasic.FileIO Imports System.Text.RegularExpressions Public Class highlighter Inherits System.Windows.Forms.RichTextBox 'RichTextBox选择起点 Dim startpos As Integer 'RichTextBox选择长度 Dim l As Integer '正则表达式匹配项 Dim regmatch As Match '正则表达式匹配项集合 Dim regmatchcol As MatchCollection '定义颜色 Dim c As Color = Color.Black '保留字正则表达式 Dim rs As String = "" Public Property CodeColor() As Color Get CodeColor = c End Get Set(ByVal value As Color) c = value End Set End Property Public Property Regstr() As String Get Regstr = rs End Get Set(ByVal value As String) rs = value End Set
End Property Public Sub loadtextfile(ByVal filename As String) Dim tmpstr As String = "" If FileSystem.FileExists(filename) Then FileOpen(1, filename, OpenMode.Input) Do While Not EOF(1) tmpstr = tmpstr &; vbCrLf &; LineInput(1) Loop MyBase.Text = tmpstr End If End Sub '代码着色采用的方法是Regex与RichTextBox的Select、SelectionColor相配合。 '先由相应的正则表达式获得匹配项,再遍历所有匹配项,从各匹配项获得匹配字符的位置和长度。 '再用RichTextBox的Select选择当前匹配项,用SelectionColor修改字体及颜色。 '一般匹配的顺序是先保留字再注释 Public Sub FormatString() regmatchcol = Regex.Matches(MyBase.Text, rs, RegexOptions.Multiline) For Each regmatch In regmatchcol startpos = regmatch.Index l = regmatch.Length MyBase.Select(startpos, l) MyBase.SelectionColor = c Next End Sub Public Sub New() MyBase.New() MyBase.ScrollBars = 19 'ForcedBoth MyBase.WordWrap = False End Sub End Class
生成完成后就可以像使用RichTextBox一样,使用loadfile或loadtextfile载入代码文件,然 后设置Highlighter类的regstr属性和codecolor属性, 再调用formatstring方法对代码进行高 亮显示。
Vb.net代码高亮显示实例:
Script.txt文件内容:
Imports System
Imports System.Text
Imports System.Text.RegularExpressions
Imports Microsoft.VisualBasic.FileIO
Public Class Form1
'RichTextBox选择起点
Dim startpos As Integer
'RichTextBox选择长度
Dim l As Integer
'正则表达式匹配项
Dim regmatch As Match
'正则表达式匹配项集合
Dim regmatchcol As MatchCollection
'保留字正则表达式
Dim Parsestr As String = "\b(AddHandler|AddressOf|AndAlso|Alias" &; _
"|And|Ansi|As|Assembly|Auto|Boolean|ByRef|Byte|ByVal|Call|Case" &; _
"|Catch|CBool|CByte|CChar|CDate|CDec|CDbl|Char|CInt|Class|CLng|CObj" &; _
"|Const|CShort|CSng|CStr|CType|Date|Decimal|Declare|Default|Delegate" &; _
"|Dim|DirectCast|Do|Double|Each|Else|ElseIf|End|Enum|Erase|Error|Event" &; _
"|Exit|False|Finally|For|Friend|Function|Get|GetType|GoTo|Handles|If" &; _
"|Implements|Imports|In|Inherits|Integer|Interface|Is|Let|Lib|Like|Lo