【问题标题】:RichTextBox Select multiple appearances of the same wordRichTextBox 选择同一单词的多次出现
【发布时间】:2018-04-15 17:31:39
【问题描述】:

我使用 C#(Windows 窗体)创建了类似记事本的应用程序,并且我想添加查找功能,该功能将突出显示搜索词的每个外观。但是我不知道如何添加到现有选择中,所以我最终只突出显示搜索词的最后一次出现。这是我的代码:

Regex regex = new Regex(args.searchTerm);
MatchCollection matches = regex.Matches(richTextArea.Text);
foreach (Match match in matches)
{
    richTextArea.Select(match.Index, match.Length);
}

那么,我该怎么办?

【问题讨论】:

    标签: c# winforms richtextbox


    【解决方案1】:

    决定你想要什么

    • 您只能选择一个字符范围。

    • 但是,您可以突出显示多个范围(通过设置例如它们的 BackColor,即通过在循环中添加例如 richTextArea.SelectionBackColor = Color.Yellow)..

    例子:

    private void searchTextBox_TextChanged(object sender, EventArgs e)
    {
        Regex regex = new Regex(searchTextBox.Text);
        MatchCollection matches = regex.Matches(richTextArea.Text);
        richTextArea.SelectAll();
        richTextArea.SelectionBackColor = richTextArea.BackColor;
        foreach (Match match in matches)
        {
            richTextArea.Select(match.Index, match.Length);
            richTextArea.SelectionBackColor = Color.Yellow;
        }
    }
    

    【讨论】:

      【解决方案2】:

      多次搜索并选择要搜索的内容,此代码对我有用,没有任何错误。

       int Timer;
       private void button5_Click(object sender, EventArgs e)
          {
              string r = textR.Text;
              richTextBox1.SelectAll();
              richTextBox1.SelectionBackColor = richTextBox1.BackColor;
              string txt = textF.Text;
              int ff = 0;
      
              for (int af = 0; ff != -1; af++)
              {
                  ff = richTextBox1.Find(textF.Text, Timer + 1, RichTextBoxFinds.None);
                  if (ff != -1)
                  {
                      Timer = ff;
                      richTextBox1.Select(ff, txt.Length);
                      richTextBox1.SelectionBackColor = Color.Yellow;
                      richTextBox1.SelectedText = r;
                  }
              }
              Timer = 0;
          }
      

      其他解决方案

      string s1 = textBox2.Text;
      
               if (s1.Length > 0)
               {
                   int startpos = richTextBox1.Find(textBox2.Text, a + 1, RichTextBoxFinds.NoHighlight);
                   int leanth = s1.Length;
                   a = startpos;
                   MessageBox.Show(startpos.ToString());
                   richTextBox1.Focus();
                   richTextBox1.Select(startpos, textBox2.Text.Length);
               }
      
               else
                   MessageBox.Show("This Text Or Characters is Not Find");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-04
        • 1970-01-01
        • 2014-02-03
        • 1970-01-01
        相关资源
        最近更新 更多