2012-09-20 50 views
0

將文本文件導入我的Windows窗體應用程序富文本框後,現在我想要添加搜索功能。是否有可能有多個SelectionStart值? SelectionLength將會看到相同的單詞。設置多個textbox.SelectionStart值,突出顯示搜索詞

 string textfield = TextField.Text; 
     string searchword = searchbox.Text; 
     int found=0; 
     TextField.SelectionLength = searchword.Length; 
     TextField.SelectionBackColor = Color.LightBlue; 

     for (int y = 0; y < textfield.Length; y++)//Goes through whole string 
     { 
      if (searchword[0] == textfield[y])//Looks for first character 
      { 
       for (int x = 0; x < searchword.Length; x++)//Checks if rest of characters match 
       { 
        if (searchword[x] == textfield[y + x]) 
        { 
         found++; 
        } 
        else 
         break; 
       } 
      } 

      if (found == searchword.Length) 
      { 
       TextField.SelectionStart = y;//////Want to have multiple of these 
      } 
      found=0; 
     } 
     TextField.Focus(); 

回答

1

不,你不能。但是,例如,您可以更改所選文字的背景顏色。首先選擇一個詞。然後做這個

foreach (Match match in matches) { 
    richTextBox.SelectionStart = match.Index; 
    richTextBox.SelectionLength = match.Length; 
    richTextBox.SelectionBackColor = Colors.Yellow; 
} 

要清除所有標記,只需選擇整個文本並設置背景色爲白色(假設你沒有使用背顏色以其他方式)。

在示例中,我假設您使用的是Regex。你會發現的話:

string pattern = String.Format(@"\b{0}\b", Regex.Escape(wordToFind)); 
MatchCollection matches = Regex.Matches(richTextBox.Text, pattern);