2011-08-03 95 views
1

我已經使用RichTextBox爲邏輯程序創建了一個簡單的vb.net文本編輯器。除了評論以外,我已經着色(突出顯示)去工作。然而,在100行左右之後,它的運行真的很慢。有誰知道更有效的方法來做到這一點? 注意:我在RichTextBox TextChanged事件上調用SyntaxHandler。使用RichTextBox的VB.Net編輯器問題

Friend vbKeys As String = "And|As|Case|Catch|CDbl|Ceiling|CInt|Class|Const|Continue|CStr|Decimal|" & _ 
          "Default|Delegate|Dim|Do|Double|Each|End|Else|Enum|Event|" & _ 
          "Explicit|Extern|False|Finally|Floor|For|Format|GoTo|If|IIf|In|Int|Is|Long|Module|" & _ 
          "Namespace|New|Next|Not|Null|Object|Option|Or|Override|Params|PI|Private|Protected|" & _ 
          "Public|Readonly|Ref|Replace|Return|Round|Sbyte|Sealed|Select|Short|Sqrt|" & _ 
          "Static|String|Structure|Sub|Then|Throw|True|Try|TypeOf|Uint|Ulong|" & _ 
          "Unchecked|Using|With|While" 

Friend Sub SyntaxHandler(ByVal txtScript As RichTextBox) 
    Dim selPos As Integer = txtScript.SelectionStart 

    'set everything to black to start with 
    txtScript.SelectAll() 
    txtScript.SelectionColor = Color.Black 

    'Regex Variables for user 
    FormatWithRegEx("\b(?:" & regexVaribles & ")\b", txtScript, Color.DarkViolet) 

    'double quoted strings are all red 
    FormatWithRegEx("""", txtScript, Color.Red) 
    FormatWithRegEx("""[^""]*""", txtScript, Color.Red) 

    'reserved words are all blue 
    FormatWithRegEx("\b(?:" & vbKeys & ")\b", txtScript, Color.Blue) 

    'single line comments are all green 
    FormatWithRegEx("'[\w*\t*\S*\[ ]*]*", txtScript, Color.Green) 

    txtScript.Select(selPos, 0) 
    txtScript.SelectionColor = Color.Black 

End Sub 
Private Sub FormatWithRegEx(ByVal strRegEx As String, ByRef txtRTB As RichTextBox,  ByVal colour As System.Drawing.Color) 
    Dim regex As New Regex(strRegEx, _ 
    RegexOptions.IgnoreCase _ 
    Or RegexOptions.Multiline _ 
    Or RegexOptions.Singleline _ 
    Or RegexOptions.IgnorePatternWhitespace) 

    Dim myMatches As MatchCollection = regex.Matches(txtRTB.Text) 
    For Each GoodMatch As Match In myMatches 
     txtRTB.Select(GoodMatch.Index, GoodMatch.Length) 
     txtRTB.SelectionColor = colour 
    Next 
End Sub 
+0

我不知道如何讓它更快,但它可能很慢,因爲您每次按下某個鍵時都會針對控件中的所有文本運行5個正則表達式。實際解析文本會更有效率(但更難),並根據此顏色進行着色。 – Andy

+0

我想知道微軟是如何做到的? – TroyS

+0

@Andy也許你的權利。我會給你一個鏡頭。如果有更多的建議或代碼片段比RegEx更有效的解決方案,請隨時發佈。謝謝。 – TroyS

回答

1

一種選擇是使用現有庫(例如,由堆棧溢出使用的prettify)。