查找RichTextBox中所有出现的字符串并为其着色

时间:2013-09-09 10:08:52

标签: vb.net

我使用的是RichTextBox控件,

我想创建一个接收String,Color和RichTextBox(obj)的函数,然后该函数将Color函数接收的String的所有实例。

我试图制作这个功能,但结果不好。

我的职能是:

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

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:-2)

cell.messagePreviewLabel.text = a_potentially_really_long_string_here