2

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

这是我目前正在使用的代码:

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 selection changed 事件处理程序的代码,因此当它更改时,它将当前光标位置设置为lastposition

希望上面的代码和我的描述能帮助你理解我的情况。所以只是为了澄清,我将如何调整我的代码,以便如果用户选择一些文本,那么它只Find and Replace对那个文本执行。一旦到达选择的末尾,它就结束了。

谢谢你。

4

1 回答 1

0

我建议使用MouseUpMouseDown事件来捕获选择,然后在选择范围内找出搜索字符串。

您还可以查看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
于 2012-11-14T11:41:46.210 回答