2010-06-25 253 views
3

我開始學習VB.NET,我試着做一個語法高亮。當我設置選定文本的顏色時,會發生問題。它改變了整個richtextbox的內容。VB.NET:語法高亮

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 

回答

2

你很親密。不要忘記恢復SelectionColor:

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

順便說一句:保持您的代碼乾淨。 rtb的消息處理程序不應被命名爲txtXxxx。這些小細節遲早會對你產生影響(它爲我做了,尋找錯誤的原因)。還要將關鍵字初始化移出方法。

+0

啊,我以爲是這樣,但我決定在發佈答案之前嘗試一下,我不明白爲什麼它不起作用(出於某種原因,我把'rtbText.SelectionColor = prevColor'放在'DeselectAll' ...),謝謝讓我感覺不那麼困惑:) – 2010-06-25 21:07:58

0

那麼,嘗試重命名變量,看看它是否有助於

For Each key As KeyWord In keywords 
0

這是一個非常糟糕的方式,如果你想語法高亮再看看Scintilla的API或附加。它是免費的,並配有600個工具來製作您自己的代碼編輯器或IDE。