In this task we will add a new form for a find dialog.
text box : name = txtFind
text = ""
label : name = lblFind
caption = "Find Text"
command button : name = cmdFind
caption = "Find"
command button : name = cmdCancel
caption = "Cancel"
You can see full details of the controls from the printout.
In this task we will add code to our dialog to give it searching capabilities.
Option Explicit
' Need a variable that keeps track of where to
' start the next search
Public startPos As Integer
Public currentSearch As String
Private Sub cmdCancel_Click()
Unload Me
Me.Hide
End Sub
Private Sub cmdFind_Click()
' When the find button is clicked, we wish to jump to the
' next instance of the current string in the text
' get a local variable that is the search string
Dim lookingFor As String
lookingFor = txtFind.Text
' Variable to keep track of where this string is
Dim pos As Integer
pos = 0
pos = InStr(startPos, frmMain!txtDocument.Text, lookingFor)
If pos = 0 Then
MsgBox "String not found"
Else
With frmMain!txtDocument
.SelStart = pos - 1
.SelLength = Len(lookingFor)
End With
End If
' set up for find next in case it is used
startPos = pos + Len(lookingFor)
currentSearch = lookingFor
' close down the form
cmdCancel_Click
End Sub
Private Sub Form_Load()
' got to set this initially
startPos = 1
End Sub
Public Sub findNext()
' This is a function that will find the next incident of
' the last string searched for
Dim pos As Integer
pos = InStr(startPos, frmMain!txtDocument.Text, currentSearch)
If pos = 0 Then
MsgBox "String not found"
startPos = 1
Else
With frmMain!txtDocument
.SelStart = pos - 1
.SelLength = Len(currentSearch)
End With
End If
' set up for find next in case it is used
startPos = pos + 1
End Sub
frmMain!txtDocument.Text = "some text" frmMain!txtDocument.SelStart = 5 frmMain!txtDocument.Length = 12 frmMain!txtDocument.Name = "some text"
With frmMain!txtDocument .Text = "some text" .SelStart = 5 .Length = 12 .Name = "some text" End With
We have to connect the two forms now. We must connect in both directions, from the main form to the dialog and from the dialog to the main form. Half of our connection has been made already, the dialog directly effects the main form by accessing it with the "!" notation. The connection from the main form to the dialog is simple. All we must do is add code to invoke the dialog. This will be in the form of two menu options (find and find next) which invoke functionality we have already built into the find dialog.
frmFind.ShowThe Show method will make a form visible.
frmFind.findNextNotice that we don't use the "!" notation to access the findNext procedure that we added (it is not connected to any event) to the find dialog. This notation is reserved for controls on the form. For accessing procedure, we can just use the simple . notation.
We have now finished the text editor. If you can think of any functionality that you would like to add to your text editor, go ahead and give it a go.