开发者

VB.NET: Syntax Highlight

开发者 https://www.devze.com 2023-01-05 05:58 出处:网络
I started to learn VB.NET and I\'m trying to do a syntax highlight. The problem occurs when i set the color of selected text. It changes the whole richtextbox\'s content.

I started to learn VB.NET and I'm trying to do a syntax highlight. The problem occurs when i set the color of selected text. It changes the whole richtextbox's content.

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


You are pretty close. Don't forget to restore the SelectionColor:

    Dim prevColor As Color = rtbText.SelectionColor
    For Each keyword As KeyWord In keywords
        '' etc...
    Next
    rtbText.SelectionColor = prevColor

Btw: keep your code clean. A message handler for an rtb should not be named txtXxxx. These little details will screw you up sooner or later (it did for me, looking for the wrong reason). Also move the keyword initialization out of the method.


Well, try rename the variable and see if it helps

For Each key As KeyWord In keywords


That is a very bad way, if you want to syntax highlight then look at the Scintilla API or add-on. It is free and comes with 600 tools to make your own code editor or pre IDE.

0

精彩评论

暂无评论...
验证码 换一张
取 消