1

我正在使用 RichTextBox 控件,

我想创建一个接收字符串、颜色和 RichTextBox (obj) 的函数,然后该函数将为函数接收的字符串的所有实例着色。

我试图实现这个功能,但结果很糟糕。

我的功能负责人是:

Public Sub ColorWord(ByVal T As RichTextBox, ByVal Word As String, ByVal color1 As Color)

例如 :

            RichTextBox1.text = xxxxxtextxxxxxtextxxx

            After Runing the function like this :
            ColorWord(RichTextBox1,"text",Color.red)

结果应该是:

xxxxx文本xxxxx文本xxx

4

2 回答 2

4
static void Highlight(RichTextBox box, string word , Color color) {
  int pos =0;
  string s = box.Text;
  for (int i = 0; ; ) {
    int j = s.IndexOf(word , i, StringComparison.CurrentCultureIgnoreCase);
    if (j < 0) break;
    box.SelectionStart = j;
    box.SelectionLength = word .Length;
    box.SelectionColor = color;
    i = j + 1;
  }
  box.SelectionStart = pos;
  box.SelectionLength = 0;
}

将代码转换为 VB.net :

Public Sub hl(ByVal T As RichTextBox, ByVal Word As String, ByVal color1 As Color)
       Dim pos As Integer = 0
       Dim s As String = T.Text
       Dim i As Integer = 0
       Dim StopWhile As Boolean = False
       While Not StopWhile
           Dim j As Integer = s.IndexOf(Word, i)
           If j < 0 Then
               StopWhile = True
           Else
               T.Select(j, Word.Length)
               T.SelectionColor = color1
               i = j + 1
           End If
       End While
       T.Select(pos, 0)
   End Sub
于 2013-09-09T10:15:13.813 回答
-2
Public Enum Highlight_Type
    Forecolor
    Backcolor
End Enum
Public Sub Reset_Highlight(ByVal T As RichTextBox, ByVal HighlightColorReset As Color, ByVal Type As Highlight_Type)
    On Error Resume Next
    T.SelectAll()
    Select Case Type
        Case Highlight_Type.Backcolor
            T.SelectionBackColor = HighlightColorReset
        Case Highlight_Type.Forecolor
            T.SelectionColor = HighlightColorReset
    End Select
    T.HideSelection = True
End Sub
Public Sub HighLight(ByVal T As RichTextBox, ByVal Word As String, ByVal HighlightColor As Color, ByVal HighlightColorReset As Color, ByVal Type As Highlight_Type)
    On Error Resume Next
    Reset_Highlight(T, HighlightColorReset, Type)
    If Word = Nothing Then Exit Sub
    Dim pos As Integer = 0
    Dim s As String = T.Text
    Dim i As Integer = 0
    Dim StopWhile As Boolean = False
    While Not StopWhile
        Dim j As Integer = s.IndexOf(Word, i)
        If j < 0 Then
            StopWhile = True
        Else
            T.Select(j, Word.Length)
            Select Case Type
                Case Highlight_Type.Backcolor
                    T.SelectionBackColor = HighlightColor
                Case Highlight_Type.Forecolor
                    T.SelectionColor = HighlightColor
            End Select
            i = j + 1
        End If
    End While
    T.Select(pos, 0)
End Sub
于 2015-04-26T05:15:40.907 回答