我开始学习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
答案 0 :(得分:2)
你非常接近。不要忘记恢复SelectionColor:
Dim prevColor As Color = rtbText.SelectionColor
For Each keyword As KeyWord In keywords
'' etc...
Next
rtbText.SelectionColor = prevColor
顺便说一下:保持你的代码干净。不应将rtb的消息处理程序命名为txtXxxx。这些小细节迟早会让你搞砸了(这对我来说,找错了理由)。同时将关键字初始化移出方法。
答案 1 :(得分:0)
好吧,尝试重命名变量,看看是否有帮助
For Each key As KeyWord In keywords
答案 2 :(得分:0)
这是一种非常糟糕的方式,如果你想要语法高亮,那么看看Scintilla API或附加组件。它是免费的,并附带600个工具来制作您自己的代码编辑器或预IDE。