使用RichTextBox问题的VB.Net编辑器

时间:2011-08-03 15:00:09

标签: vb.net visual-studio editor syntax-highlighting

我使用RichTextBox为逻辑程序创建了一个简单的vb.net文本编辑器。除了评论之外,我还有着色(突出显示)。然而,在100行左右后,它的运行速度非常慢。有谁知道更有效的方法来做到这一点? 注意:我在RichTextBox TextChanged事件上调用SyntaxHandler。

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

1 个答案:

答案 0 :(得分:1)

一种选择是使用现有的库(例如,由Stack Overflow使用的美化)。

相关问题