如何仅对所选文本应用“查找和替换”而不是VB.net中的整个文档

时间:2012-11-13 16:33:07

标签: .net vb.net richtextbox replace

是的,我已经创建了允许用户对Rich Text Box中的所有文本执行查找和替换的代码。但是,我现在允许用户选择要执行查找和替换

的部分文本

这是我目前使用的代码:

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

我还在form1选择更改事件处理程序的RTB中添加了代码,这样当它更改时,它会将当前光标位置设置为 lastposition

希望上面的代码和我的描述能帮助您了解我的情况。因此,为了澄清,我将如何调整我的代码,以便在用户选择某些文本时,它只对该文本执行Find and Replace。一旦它到达选择的结尾,它就会结束。

谢谢。

1 个答案:

答案 0 :(得分: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