2010-12-06 5 views
2

ファインダの次のファンクションを作成するにはどうすればよいですか?C#次のファンクションの作成

私の現在のコードから、textBoxSearchからの単語がrichTextBoxBrowsingで見つかった場合、その単語はrichTextBoxBrowsing内で強調表示されます。

同じ単語が複数見つかった場合は、最初の単語のみが表示されます。したがって、次の単語を見つけるためにボタンF3を押したいと思います。それは、richTextBoxBrowsingが終了するまで順番に強調表示されます。

ありがとうございます!

 String s1 = textBoxSearch.Text.ToLower(); 
     int startPos = richTextBoxBrowsing.Find(s1); 
     int length = s1.Length; 

     if (startPos > -1) 
     { 
      MessageBox.Show("Word found!"); 
      richTextBoxBrowsing.Focus(); 
      richTextBoxBrowsing.Select(startPos, length); 
     } 

     else 
     { 
      MessageBox.Show("Word not found!"); 
     } 

答えて

3

トリックは最後の既知のインデックス(あなたがstartPosためだつまり最後の値)のホールドを維持することです - おそらく、フォームレベルのフィールドでは、あなたが使用することができます。

int startPos = Find(s1, lastIndex + 1, RichTextBoxFinds.None); 

lastIndex -1を指定すると最初から開始されます)

+0

私は 'lastIndex + s1.Length'を使用します。 –

+0

しかし、いくつかの正規表現のように、2番目の検索結果が1番目の検索結果に含まれる場合はどうなりますか?確かに、これはまだプログラムRegexsを使用していないが、それは常に有用です... – Miguel

2

以前に見つかったアイテムのインデックスを覚えておくなど、以前の検索の状態を保存する必要があります。検索文字列が変更されるたびに、開始インデックスを-1にリセットします。

1

ここでは、「次を検索」機能を使用しています。私は現在TAFEプロジェクトに取り組んでいますが、VB.netにはありますが、簡単にC#に変換できます。それは私にとって不思議なことです。

テキストがあるところに「RichTextBox1」と呼ばれるメインのリッチテキストボックスがあり、検索するものを入力する「ToolStripSearchTextBox」というテキストボックスと、メソッド 'FindNext_Click()を呼び出す' ToolStripButton2というボタンがあります。 'をクリックします。

この「Find Next」機能では、「RichTextBoxFinds.None」のために大文字小文字が区別されません。気軽に変更してください。

// Find next 
Dim searchIndex As Integer = 0 
Dim lastSearch As String 

Private Sub FindNext_Click(sender As Object, e As EventArgs) Handles ToolStripButton2.Click 
    // If the search textbox is empty, focus on it 
    If (ToolStripSearchTextBox.Text = String.Empty) Then 
     ToolStripSearchTextBox.Focus() 
     Return 
    End If 
    // If user changed their search term, reset the index 
    If (ToolStripSearchTextBox.Text <> lastSearch) Then 
     searchIndex = 0 
    End If 
    lastSearch = ToolStripSearchTextBox.Text 

    // If the character(s) exist, update the index. Otherwise, set the index to -1 
    Try 
     searchIndex = RichTextBox1.Find(ToolStripSearchTextBox.Text, searchIndex, RichTextBoxFinds.None) 
    Catch ex As ArgumentOutOfRangeException 
     searchIndex = -1 
    End Try 

    // Character(s) exists, focus on the main textbox and then select the character(s) 
    If (searchIndex <> -1) Then 
     RichTextBox1.Focus() 
     RichTextBox1.SelectionStart = searchIndex 
     RichTextBox1.SelectionLength = ToolStripSearchTextBox.Text.Length 

     searchIndex = searchIndex + 1 
    Else // No occurances of text or user has highlghted last remaining word. Let the user know they have reached the end of the document and reset the index 
     searchIndex = 0 
     //RichTextBox1.SelectionStart = 0 
     //RichTextBox1.SelectionLength = 0 
     MessageBox.Show("End of document", String.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information) 
    End If 
End Sub