我开始学习VB.NET,并且试图突出语法。当我设置所选文本的颜色时,会发生问题。它将更改整个richtextbox的内容。
Private Sub txtText_TextChanged_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rtbText.TextChanged
Dim keywords As ArrayList
Dim index As Integer
Dim keyboardCursorPosition As Integer
keywords = New ArrayList()
keywords.Add(New Keyword("<?php", Color.Red))
keywords.Add(New Keyword("echo", Color.Blue))
keywords.Add(New Keyword("?>", Color.Red))
keyboardCursorPosition = rtbText.SelectionStart
For Each keyword As Keyword In keywords
index = rtbText.Text.IndexOf(keyword.getKey())
If index <> -1 Then
rtbText.Select(index, keyword.getKey().Length)
rtbText.SelectionColor = keyword.getColor()
rtbText.DeselectAll()
rtbText.SelectionStart = keyboardCursorPosition
End If
Next
End Sub
最佳答案
你很亲密不要忘记恢复SelectionColor:
Dim prevColor As Color = rtbText.SelectionColor
For Each keyword As KeyWord In keywords
'' etc...
Next
rtbText.SelectionColor = prevColor
顺便说一句:保持代码干净。 rtb的消息处理程序不应命名为txtXxxx。这些小细节迟早会给您带来麻烦(对我来说,是在寻找错误的原因)。还将关键字初始化移出方法。