2012-11-13 23 views
2

對,我已經創建了允許用戶對所有文本執行查找和替換的代碼富文本框。不過,我現在允許用戶選擇文本的一部分要執行的查找和替換如何將查找和替換僅應用於所選文本而不是VB.net中的整個文檔

什麼這是我目前使用我的代碼:

Private Sub btnFFindNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFFindNext.Click 
Dim length as String 

length = textToFind.Text.Length 

lastposition = frm1.RichTextBox.Find(textToFind.Text, lastposition, RichTextBoxFinds.None) 

frm1.RichTextBox.SelectionStart = lastposition 
frm1.RichTextBox.SelectionLength = length 
lastposition = lastposition + 1 

我還添加代碼在RTB中的form1選擇已更改的事件處理程序中,以便當它發生更改時,它將當前光標位置設置爲上一個位置

希望上面的代碼和我的描述將幫助您瞭解我的情況。因此,爲了澄清,我將如何調整我的代碼,以便如果用戶選擇了一些文本,那麼它僅對該文本執行Find and Replace。一旦到達選擇結束,它結束。

謝謝。

+0

任何一個至少有任何建議嗎? – user1821387

+2

請不要**添加答案作爲後續回覆您的問題,編輯您的問題或留下意見。我試圖將它們移到你的問題中,但不能,每個人都專門提出了一個答案。 –

+0

@ user1821387,有沒有更新? – NeverHopeless

回答

0

我會建議使用MouseUpMouseDown事件來捕獲選擇,然後找出選擇範圍內的搜索字符串。

你也可以看看this MSDN例如,或者類似的東西,這將幫助你:

Private selectionStart As Integer 
Private selectionEnd As Integer 
Private searchString As String 

Private Sub btnFindAll_Click(sender As Object, e As EventArgs) 
    searchString = textToFind.Text ' Set string to find here 

    ' Swap position due to reverse selection 
    If selectionStart > selectionEnd Then 
     Dim x As Integer = selectionStart 
     selectionStart = selectionEnd 
     selectionEnd = x 
    End If 

    'Every time find index and focus the result 
    Dim index As Integer = richTextBox1.Find(searchString, selectionStart, selectionEnd, RichTextBoxFinds.None) 
    If index > 0 Then 
     richTextBox1.Focus() 
     richTextBox1.Select(index, searchString.Length) 
     selectionStart = index + searchString.Length 
    Else 
       ' not found 
    End If 
End Sub 

Private Sub richTextBox1_MouseUp(sender As Object, e As MouseEventArgs) 
    selectionEnd = richTextBox1.GetCharIndexFromPosition(New System.Drawing.Point(e.X, e.Y)) 
End Sub 

Private Sub richTextBox1_MouseDown(sender As Object, e As MouseEventArgs) 
    selectionStart = richTextBox1.GetCharIndexFromPosition(New System.Drawing.Point(e.X, e.Y)) 
End Sub 
+0

使用你的按鈕事件處理程序,並從鏈接只使用事件處理程序內的代碼 – NeverHopeless

+0

對於我的findnext事件處理程序會是這樣嗎? 私人小組btnFFindNext_Click(BYVAL發件人爲System.Object的,BYVALË作爲System.EventArgs)把手btnFFindNext.Click 呼叫FindMyText(RichTextBox.SelectedText,RichTextBox.SelectionStart,RichTextBox.Text.Length) 結束子 所以我m將selectedText作爲「searchText」傳遞。我將selectionStart作爲「searchStart」傳遞。現在,我作爲「searchEnd」通過了什麼?因爲'searchEnd'肯定不是RTB.Text.Length – user1821387

+0

,你應該看到我的代碼的'MoueseDown'事件。在這裏我已經捕獲了選擇的最終邊界。或者你可以使用'RTB.SelectedText.Length'或'RTB.SelectionLength' – NeverHopeless

相關問題