VB.NET问题:怎么让For...Next...循环加速?


我设计了一个程序,在 RichTextBox TextChanged 事件,通过 For...Next... 枚举每个字符,将其中的尖括号( <> )、双引号( "" )中的文字换成不同的颜色。
这是我的代码:


 Public Class FrmEdit
    Private Sub CodeTextBox_TextChanged(sender As Object, e As EventArgs) Handles CodeTextBox.TextChanged
        If CodeTextBox.Text = "" Then Exit Sub
        CodeTextBox.ForeColor = Color.Black
        CodeTextBox.SelectAll() : CodeTextBox.SelectionFont = Me.Font
        TipProgressBar.Visible = True
        TipProgressBar.Maximum = CodeTextBox.TextLength - 1
        TipProgressBar.Minimum = 0
        TipProgressBar.Value = 0

        Dim AngleBracketsOn As Boolean = False
        Dim DoubleQuotesOn As Boolean = False

        For i As Integer = 0 To CodeTextBox.TextLength - 1
            CodeTextBox.SelectionStart = i
            CodeTextBox.SelectionLength = 1

            If CodeTextBox.SelectedText = "<" Then
                AngleBracketsOn = True
                CodeTextBox.SelectionLength = CodeTextBox.TextLength - i
                CodeTextBox.SelectionColor = Color.Purple
            End If
            If CodeTextBox.SelectedText = ">" Then
                If AngleBracketsOn = True Then
                    AngleBracketsOn = False
                    CodeTextBox.SelectionStart = i + 1
                    CodeTextBox.SelectionLength = CodeTextBox.TextLength - i - 1
                    CodeTextBox.SelectionColor = Color.Black
                End If
            End If

            If CodeTextBox.SelectedText = """" Then
                If DoubleQuotesOn = False Then
                    DoubleQuotesOn = True
                    CodeTextBox.SelectionLength = CodeTextBox.TextLength - i
                    CodeTextBox.SelectionColor = Color.Blue
                Else
                    DoubleQuotesOn = False
                    CodeTextBox.SelectionStart = i + 1
                    CodeTextBox.SelectionLength = CodeTextBox.TextLength - i - 1
                    CodeTextBox.SelectionColor = Color.Black
                End If
            End If

            TipProgressBar.Value = i
        Next

        CodeTextBox.SelectionLength = 0
        CodeTextBox.SelectionStart = CodeTextBox.TextLength
        TipProgressBar.Visible = False
    End Sub
End Class

我复制了一段百度翻译网页( http://fanyi.baidu.com/#en/zh/ )的源代码,卡了9分钟才完成。不知道有没有更好的办法,可以加快程序的速度?求大神帮忙!

visual-basic .net visual-studio

Astrot 9 years, 8 months ago

 For i As Integer = 0 To CodeTextBox.Text.Length - 1
    Dim char1 As Char = CodeTextBox.Text(i)
    CodeTextBox.Select(i, 1)
    Select Case char1
        Case "<"c
            CodeTextBox.SelectionColor = Color.Red
            Exit Select
        ...
        Case Else
            CodeTextBox.SelectionColor = Color.Black
            Exit Select
    End Select
Next

CodeTextBox.SelectionLength = 0
CodeTextBox.SelectionStart = CodeTextBox.TextLength

dzisy answered 9 years, 8 months ago

Your Answer