C # RichTextBox Выбрать указанный текст - PullRequest
5 голосов
/ 29 августа 2011

У меня есть RichTextBox с -по примеру- этот текст:

"This is my Text"

Теперь я хочу «найти» в RichTextBox текст (строку), например:

"Text"

Теперь «Текст» должен быть выделен / выделен (для каждого) в RichTextBox ..

Есть что-то вроде:

myRichTextBox.Select();

но здесь я должен установить StartPosition и так далее, но я хочу найти строку!

Как я мог это сделать? (Поиск переполнения стека, не нашел что-то похожее ..)

Ответы [ 4 ]

2 голосов
/ 29 августа 2011
     int start = 0;
int indexOfSearchText = 0;
private void btnFind_Click(object sender, EventArgs e)
        {
            int startindex = 0;

            if(txtSearch.Text.Length > 0)
                startindex = FindMyText(txtSearch.Text.Trim(), start, rtb.Text.Length);

            // If string was found in the RichTextBox, highlight it
            if (startindex >= 0)
            {
                // Set the highlight color as red
                rtb.SelectionColor = Color.Red;
                // Find the end index. End Index = number of characters in textbox
                int endindex = txtSearch.Text.Length;
                // Highlight the search string
                rtb.Select(startindex, endindex);
                // mark the start position after the position of
                // last search string
                start = startindex + endindex;
            }
        }




public int FindMyText(string txtToSearch, int searchStart, int searchEnd)
        {
            // Unselect the previously searched string
            if (searchStart > 0 && searchEnd > 0 && indexOfSearchText >= 0)
            {
                rtb.Undo();
            }

            // Set the return value to -1 by default.
            int retVal = -1;

            // A valid starting index should be specified.
            // if indexOfSearchText = -1, the end of search
            if (searchStart >= 0 && indexOfSearchText >=0)
            {
                // A valid ending index
                if (searchEnd > searchStart || searchEnd == -1)
                {
                    // Find the position of search string in RichTextBox
                    indexOfSearchText = rtb.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None);
                    // Determine whether the text was found in richTextBox1.
                    if (indexOfSearchText != -1)
                    {
                        // Return the index to the specified search text.
                        retVal = indexOfSearchText;
                    }
                }
            }
            return retVal;
        }



private void textBox1_TextChanged(object sender, EventArgs e)
        {
            start = 0;
            indexOfSearchText = 0;
        }

Отметьте эту статью, если вы не понимаете этот код ... http://www.dotnetcurry.com/ShowArticle.aspx?ID=146

2 голосов
/ 29 августа 2011

Вы можете использовать метод Find, чтобы найти начальный индекс искомого текста:

int indexToText = myRichTextBox.Find(searchText);

Затем вы можете использовать этот индекс и метод Select для выделения текста:

int endIndex = searchText.Length;
myRichTextBox.Select(indexToText , endIndex);
1 голос
/ 29 августа 2011

Вы можете иметь только один выбор в текстовом поле. Вы хотите выделить найденный текст.
Вы можете достичь этого следующим образом:

  1. Найдите позиции текста, которые вы хотите выделить, используя повторные вызовы myRichTextBox.Text.IndexOf с последним найденным индексом + 1 в качестве начальной позиции.
  2. Выделите найденные тексты, используя возможности RichTextBox по умолчанию.
0 голосов
/ 13 марта 2016
    private void Txt_Search_Box_TT_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
        FOFO:
            int start =
                RtfAll_Messages.Find(Txt_Search_Box_TT.Text, RtfAll_Messages.SelectionStart + 1,
                RichTextBoxFinds.None);
            if (start >= 0)
                RtfAll_Messages.Select(start, Txt_Search_Box_TT.Text.Length);
            else
            {
                start = 0;
                RtfAll_Messages.SelectionStart = 0;
                RtfAll_Messages.SelectionLength = 0;
            }
        }
    }
...