代码之家  ›  专栏  ›  技术社区  ›  Nguyễn Nam Khánh

对richtextbox使用颜色,但当添加字符时,con trámouse会出错

  •  0
  • Nguyễn Nam Khánh  · 技术社区  · 7 年前
    Private Sub Write_code_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Write_code.TextChanged
            Dim strWord As String
            Dim lPos As Long
    
            strWord = "read"
    
            lPos = InStr(1, Write_code.Text, strWord, vbTextCompare)
    
            If lPos > 0 Then
                With Write_code
                    .SelectionStart = lPos - 1
                    .SelectionLength = Len(strWord)
                    .SelectionColor = Color.Green
                    .SelectionStart = Len(Write_code.Text)
                    .SelectionLength = 0
                    .SelectionColor = Color.Blue
                End With
            End If
    End Sub
    

    这是我的代码,我有一个问题,当我再次打开文本时,它无法添加字符(只能添加到文本末尾的文本末尾)。有没有其他代码可以帮助我。

    1 回复  |  直到 7 年前
        1
  •  0
  •   the_lotus    7 年前

    您正在使用此“.SelectionStart=Len(Write\u code.text)”在文本末尾设置选择。您可以跟踪最后一个选择并将其设置回原处。

    Private Sub Write_code_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Write_code.TextChanged
            Dim strWord As String
            Dim lPos As Long
    
            strWord = "read"
    
            lPos = InStr(1, Write_code.Text, strWord, vbTextCompare)
    
            If lPos > 0 Then
                Dim originalPosition As Long = Write_code.SelectionStart
    
                With Write_code
                    .SelectionStart = lPos - 1
                    .SelectionLength = Len(strWord)
                    .SelectionColor = Color.Green
                    .SelectionStart = Len(Write_code.Text) ' Or maybe put it here
                    .SelectionLength = 0
                    .SelectionColor = Color.Blue
                End With
    
                Write_code.SelectionStart = originalPosition
            End If
    End Sub