VB.NET: syntax highlighting

I started to learn VB.NET and I am trying to do syntax highlighting. The problem occurs when I set the color of the selected text. It modifies all richtextbox 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
+3
source share
3 answers

You are pretty close. Remember to restore SelectionColor:

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

Btw: keep your code clean. The message handler for rtb should not be called txtXxxx. These small details will shake you sooner or later (this was for me, looking for the wrong reason). Also move the initialization of the keyword from the method.

+2
source

Well, try renaming the variable and see if it helps

For Each key As KeyWord In keywords
0

This is very bad if you want to highlight the syntax, look at the Scintilla API or add-on. It is free and comes with 600 tools for creating your own code editor or preliminary IDE.

0
source

Source: https://habr.com/ru/post/1751815/


All Articles