前些天做了一个文本编辑器,其中正好有“搜索”、“查找下一个”的功能,先把代码给你,如不明白请回复.
Private Sub serch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles serch.Click
yesornonext = False
findtext(1)
End Sub
'查找下一个
Private Sub serchnext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles serchnext.Click
yesornonext = True
findtext(targetposition + 1)
End Sub
Private Sub findtext(ByVal startposition As Integer)
If yesornonext = False Then
findtextstr = Trim(InputBox("请输入要查找的文本:", "查找"))
End If
Dim activechild As Form = Me.ActiveMdiChild
If Not activechild Is Nothing Then
If Not activechild.ActiveControl Is Nothing Then
Dim therichtextbox As RichTextBox
therichtextbox = CType(activechild.ActiveControl, RichTextBox)
Dim pos As Integer
pos = InStr(startposition, therichtextbox.Text, findtextstr)
If pos > 0 Then
textnum = textnum + 1
targetposition = pos
therichtextbox.SelectionStart = targetposition - 1
therichtextbox.SelectionLength = Len(findtextstr)
Else
If yesornonext = False Then
MessageBox.Show("你要查找的文本不存在!", "提示", MessageBoxButtons.OK)
Else
MessageBox.Show("文本查找完毕!" & " " & "共" & CStr(textnum) & "处", "提示", MessageBoxButtons.OK)
End If
End If
End If
End If
End Sub
以上功能代码是查找richtextbox 中的文本。
'先声明API函数
Public Declare Function SetWindowPos Lib "user32" (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal x As Long, ByVal Y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long
Public Const HWND_TOPMOST = -1
Public Const SWP_NOMOVE = &H2
Public Const SWP_NOSIZE = &H1
'在窗体加载时调用
Private Sub Form_Load()
SetWindowPos Me.hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE Or SWP_NOSIZE
End Sub