我正在为我们在工作中使用的非常简单的脚本语言编写一个简单的代码编辑器。如果我在整个 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
最佳答案
好吧,我明白了。我在 rtbMain.TextChange 上调用偶数,认为这只会在文本实际更改时触发。 Nay Nay,格式改变也会触发。所以每次它在第一次通过并突出显示所有内容时更改某些内容时,它都会触发突出显示该行。它会一直这样做,直到没有什么可以更改为止。
我为天气设置了一个 bool 变量,它当前是否突出显示并在 TextChange sub 中添加了一个 if 条件
附言 我没有自学者徽章,所以欢迎任何向上的评级:P
关于富文本框中的 VB.NET 语法突出显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/308985/