我知道這個問題已被問及加載次數,但我有一個特定的請求。這可能有點難以理解,對此我表示歉意。我會盡我所能地評論代碼。如果你需要澄清,請告訴我。RichTextBox中的「查找下一個」功能:包含「匹配大小寫」
我的問題是我有非常複雜,不必要的代碼,因爲我自己寫了這個,這對我來說是一個新概念。該代碼旨在在主窗口的RichTextBox中找到一個字符串(該字符串顯然是由用戶提供的)。代碼工作正常,但由於其複雜的性質,我不知道如何實現「匹配大小寫」功能。
形式有這些控件(至少你搜索文本時使用的):
- 文本框:
txtFind
- 用戶在這裏輸入一個搜索詞 - 複選框:
chkMatchCase
- 允許用戶選擇是否要搜索詞的情況下匹配 - 按鈕:
btnFind
- 查找下一個按鈕
這是我的鱈魚e:
Dim index As Integer = 0
Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFind.Click
Dim strSearchTerm As String
Dim lastIndex As Integer
Dim strLastSearch As Integer
'Set the end of the find location to the last known instance of the search term
lastIndex = frmMain.rtxtNotepad.Text.LastIndexOf(Me.txtFind.Text)
'If the last known location is 0 (meaning the string is located at the beginning of the document), set strSearchTerm to 0.
If lastIndex = 0 Then
strSearchTerm = 0
ElseIf lastIndex = -1 Then
'If the search term appears not to exist, double-check (due to an error when searching using Text.LastIndexOf and the case of the search term does not match the instance):
If frmMain.rtxtNotepad.Text = "" Then
' 1a) If the main window's RTB is empty, warn the user
MsgBox("Cannot find '" & txtFind.Text & "'.")
Else
' 1b) If the RTB is not empty, search again.
If frmMain.rtxtNotepad.Find(Me.txtFind.Text, 0, frmMain.rtxtNotepad.Text.Length, RichTextBoxFinds.None) = -1 Then
' 2a) If the search string is not found again, warn the user.
MsgBox("Cannot find '" & txtFind.Text & "'.")
Else
' 2b) If it is found, set strSearchTerm to the beginning index of the occurrence.
strSearchTerm = frmMain.rtxtNotepad.Find(Me.txtFind.Text, 0, frmMain.rtxtNotepad.Text.Length, RichTextBoxFinds.None)
End If
End If
Else
'If none of the above apply, set strSearchTerm to the index of the occurence
strSearchTerm = frmMain.rtxtNotepad.Find(Me.txtFind.Text, index, lastIndex, RichTextBoxFinds.None)
End If
If strSearchTerm = -1 Then
'If the search term is found, but this is the last instance, loop back
strLastSearch = frmMain.rtxtNotepad.Text.LastIndexOf(Me.txtFind.Text)
frmMain.Focus()
frmMain.rtxtNotepad.SelectionStart = strLastSearch
frmMain.rtxtNotepad.SelectionLength = Me.txtFind.Text.Length
index = 0
Else
'If the search term is found, and this is not the last instance, set the starting integer of the Find statement to bypass the previous occurrence of the search term
frmMain.Focus()
frmMain.rtxtNotepad.SelectionStart = strSearchTerm
frmMain.rtxtNotepad.SelectionLength = Me.txtFind.Text.Length
index = strSearchTerm + 1
End If
End Sub
無論如何,如果有更好的方法來實現這一點,請讓我知道。我做了大量的搜索,但沒有找到好的解決方案。我結束了將其他教程的一些小部分組合到這裏。如果沒有更好的解決方案,我只想知道如何實現「匹配案例」功能。
對不起,感謝您的幫助!
該代碼是美好的,謝謝,但我恐怕我使用VB.NET。哦,你說C#。我的錯!我已經將它轉換爲VB.NET,我會看看它是否可行! – Abluescarab 2011-05-20 14:50:58
它奇妙地工作,謝謝!我現在唯一遇到的問題是我希望它回到搜索項的第一個實例。我正試圖弄清楚現在。 編輯:它現在工作完美!謝謝! – Abluescarab 2011-05-20 21:09:17