我正在为我们在工作中使用的一种非常简单的脚本语言编写一个简单的代码编辑器。如果我在整个RichTextBox
( rtbMain
) 上执行语法高亮代码,我的代码可以正常工作,但是当我尝试让它只在该行上工作时,我可以运行带有rtbMain
更改的函数,它变得很奇怪。我似乎无法弄清楚为什么。我是否以正确的方式去做这件事?
rtbMain
是主文本框。
frmColors.lbRegExps
是要突出显示的单词列表框(稍后它将具有更强大的正则表达式。)
frmColor.lbHexColors
是另一个带有单词对应十六进制颜色的列表框。
Private Sub HighLight(ByVal All As Boolean)
Dim RegExp As System.Text.RegularExpressions.MatchCollection
Dim RegExpMatch As System.Text.RegularExpressions.Match
Dim FirstCharIndex As Integer = rtbMain.GetFirstCharIndexOfCurrentLine
Dim CurrentLine As Integer = rtbMain.GetLineFromCharIndex(FirstCharIndex)
Dim CurrentLineText As String = rtbMain.Lines(CurrentLine)
Dim CharsToCurrentLine As Integer = rtbMain.SelectionStart
Dim PassNumber As Integer = 0
LockWindowUpdate(Me.Handle.ToInt32) 'Let's lock the window so it doesn't scroll all crazy.
If All = True Then 'Highlight everything.
For Each pass In frmColors.lbRegExps.Items
RegExp = System.Text.RegularExpressions.Regex.Matches(LCase(rtbMain.Text), LCase(pass))
For Each RegExpMatch In RegExp
rtbMain.Select(RegExpMatch.Index, RegExpMatch.Length)
rtbMain.SelectionColor = ColorTranslator.FromHtml(frmColors.lbHexColors.Items(PassNumber))
Next
PassNumber += 1
Next
Else 'Highlight just that row.
For Each pass In FrmColors.lbRegExps.Items
RegExp = System.Text.RegularExpressions.Regex.Matches(LCase(CurrentLineText), LCase(pass))
For Each RegExpMatch In RegExp
rtbMain.Select(RegExpMatch.Index + (CharsToCurrentLine - RegExpMatch.Length), RegExpMatch.Length)
rtbMain.SelectionColor = Color.Blue
Next
Next
End If
rtbMain.Select(CharsToCurrentLine, 0) 'Reset colors and positon and then unlock drawing.
rtbMain.SelectionColor = Color.Black
LockWindowUpdate(0)
End Sub