5

私は今、あまりにも長い時間を使って、問題を理解しようとしましたが、それはそれほど難しいことではないと思いました。

取引は次のとおりです。

私はC#とWPFを使用して小さなアプリケーションを書いています。

FlowDocumentを含むRichTextBoxがあります。

リッチテキストボックスの下に小さなテキストボックスとボタンを追加しました。

次に、ユーザーは検索したい単語を入力してボタンを押します。

次に、richtextboxはその単語の最初の出現にジャンプします。

正しい行にジャンプするだけで十分です。単語でカーソルを選択、強調表示、または配置することもできます。richTextBoxが単語までスクロールされている限り、何でもかまいません。

ボタンを押し続けると、ドキュメントの最後まで、単語の次の出現箇所にジャンプし、以下同様に続きます。

私が言ったように-私はそれが簡単な仕事だと思った-しかし私はこれを理解するのに深刻な問題を抱えている。

4

3 に答える 3

14

これでうまくいくはずです:

public bool DoSearch(RichTextBox richTextBox, string searchText, bool searchNext)
{
  TextRange searchRange;

  // Get the range to search
  if(searchNext)
    searchRange = new TextRange(
        richTextBox.Selection.Start.GetPositionAtOffset(1),
        richTextBox.Document.ContentEnd);
  else
    searchRange = new TextRange(
        richTextBox.Document.ContentStart,
        richTextBox.Document.ContentEnd);

  // Do the search
  TextRange foundRange = FindTextInRange(searchRange, searchText);
  if(foundRange==null)
    return false;

  // Select the found range
  richTextBox.Selection.Select(foundRange.Start, foundRange.End);
  return true; 
}

public TextRange FindTextInRange(TextRange searchRange, string searchText)
{
  // Search the text with IndexOf
  int offset = searchRange.Text.IndexOf(searchText);
  if(offset<0)
    return null;  // Not found

  // Try to select the text as a contiguous range
  for(TextPointer start = searchRange.Start.GetPositionAtOffset(offset); start != searchRange.End; start = start.GetPositionAtOffset(1))
  {
    TextRange result = new TextRange(start, start.GetPositionAtOffset(searchText.Length);
    if(result.Text == searchText)
      return result;
  }
  return null;
}

FindTextInRangeのfor()ループの理由残念ながら、range.Textは非テキスト文字を削除するため、場合によっては、IndexOfによって計算されるオフセットがわずかに低くなりすぎます。

于 2009-11-18T17:05:16.907 に答える
2

私は別のアプローチを使用しました。TextBoxを使用してキーワードを設定します。これは、ボタンクリックでキーワードを検索します。キーワードを検索します。それをハイライトし、そのキーワードに焦点を当てます。

    // Index of Current Result Found (Counts Characters not Lines or Results)
    private int IndexOfSearchResultFound;
    // Start Position Index of RichTextBox (Initiated as 0 : Beggining of Text / 1st Char)
    private int StartOfSelectedKeyword;
    private int EndOfSelectedKeyword;

    private void btnSearch_Click(object sender, EventArgs e)
    {
        // Reset Keyword Selection Index. (0 is the Staring Point of the Keyword Selection)
        IndexOfSearchResultFound = 0;

        // Specify the End of the Selected Keyword; using txt_Search.Text.Lenght (Char Ammount).
        EndOfSelectedKeyword = txt_Search.Text.Length;

        // If txt_Search.Text is not Empty
        if (txt_Search.Text.Length > 0)
        {
            // Find Keyword in RichTextBox.Text
            IndexOfSearchResultFound = FindKeyword(txt_Search.Text.Trim(), StartOfSelectedKeyword, rtb_Hosts.Text.Length);

            // If string was found in RichTextBox; Highlight it and Focus on Keyword Found Location
            if (IndexOfSearchResultFound >= 0)
            {
                // Focus on Currently Found Result
                rtb_Hosts.Focus();

                // Highlight the search string
                rtb_Hosts.Select(IndexOfSearchResultFound, EndOfSelectedKeyword);

                // Sets a new Starting Position (after the Position of the Last Result Found)
                // To be Ready to Focus on the Next Result
                StartOfSelectedKeyword = IndexOfSearchResultFound + EndOfSelectedKeyword;
            }
        }
    }


    private int FindKeyword(string _SearchKeyword, int _KeywordSelectionStart, int _KeywordSelectionEnd)
    {
        // De-Select Previous Searched String (Keyword)
        if (_KeywordSelectionStart > 0 && _KeywordSelectionEnd > 0 && IndexOfSearchResultFound >= 0)
        { rtb_Hosts.Undo(); }

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

        // A valid Starting index should be specified.
        // if indexOfSearchText = -1, Means that Search has reached the end of Document
        if (_KeywordSelectionStart >= 0 && IndexOfSearchResultFound >= 0)
        {
            // Find Keyword
            IndexOfSearchResultFound = rtb_Hosts.Find(_SearchKeyword, _KeywordSelectionStart, _KeywordSelectionEnd, RichTextBoxFinds.None);

            // Determine whether the text was found in richTextBox
            retVal = IndexOfSearchResultFound;
        }
        // Return the index to the specified Keyword text.
        return retVal;
    }

私がまだ達成できなかった唯一のことは、最初の検索結果に戻ることです

于 2014-02-05T16:24:49.443 に答える
0

これは、Caretの位置に最も近い一致を見つけるバリアントです。

  private TextRange FindText(string findText)
    {
      var fullText = DoGetAllText();
      if (string.IsNullOrEmpty(findText) || string.IsNullOrEmpty(fullText) || findText.Length > fullText.Length)
        return null;

      var textbox = GetTextbox();
      var leftPos = textbox.CaretPosition;
      var rightPos = textbox.CaretPosition;

      while (true)
      {
        var previous = leftPos.GetNextInsertionPosition(LogicalDirection.Backward);
        var next = rightPos.GetNextInsertionPosition(LogicalDirection.Forward);
        if (previous == null && next == null)
          return null; //can no longer move outward in either direction and text wasn't found

        if (previous != null)
          leftPos = previous;
        if (next != null)
          rightPos = next;

        var range = new TextRange(leftPos, rightPos);
        var offset = range.Text.IndexOf(findText, StringComparison.InvariantCultureIgnoreCase);
        if (offset < 0)
          continue; //text not found, continue to move outward

        //rtf has broken text indexes that often come up too low due to not considering hidden chars.  Increment up until we find the real position
        var findTextLower = findText.ToLower();
        var endOfDoc = textbox.Document.ContentEnd.GetNextInsertionPosition(LogicalDirection.Backward);
        for (var start = range.Start.GetPositionAtOffset(offset); start != endOfDoc; start = start.GetPositionAtOffset(1))
        {
          var result = new TextRange(start, start.GetPositionAtOffset(findText.Length));
          if (result.Text?.ToLower() == findTextLower)
          {
            return result;
          }
        }
      }
    }

一致を強調表示する場合は、このメソッドをvoidに変更し、一致が見つかったときにこれを行うのと同じくらい簡単です。

textbox.Selection.Select(result.Start, result.End);
于 2017-10-28T06:16:24.470 に答える