Tutorials > VSPrinter Examples > Find Text |
This example shows how you can find text in a VSPrinterdocument using the FindText property.
To create the Find example, start by adding the following controls to a new VB form:
VSPrinter control (name it vp)
TextBox control (name it txtText)
Two CommandButton controls (name them btnFind(0) and btnFind(1)).
Set the Caption property of the command buttons to Find and Find Next.
Next, you will need an RTF file that will be loaded into the VSPrinter control. Copyany RTF file to the sample's directory and name it "TEXT.RTF".
Then add the following code to load the RTF file into the control and manage the state of the Find and Find Next buttons:
Example Title |
Copy Code
|
---|---|
Private Sub Form_Load() vp.Footer = "TEXT.RTF||Page %d" vp.PrintFile App.Path & "\TEXT.RTF" vp.PenWidth = 50 vp.PenColor = 200 vp.PenStyle = psSolid vp.BrushStyle = bsTransparent End Sub Private Sub txtFind_Change() btnFind(0).Enabled = (Len(txtFind) > 0) btnFind(1).Enabled = (Len(txtFind) > 0) End Sub |
Finally, here is the main part of the code. It handles the Find and Find Next button clicks:
Example Title |
Copy Code
|
---|---|
Private Sub btnFind_Click(Index As Integer) Static iStartPage% Static fStartY! ' reset to find first If Index = 0 Then iStartPage = 0 fStartY = 0 End If ' look for text iStartPage = vp.FindText(txtFind, , iStartPage, , fStartY) ' not found? reset and bail If iStartPage <= 0 Then MsgBox "Cannot find the string '" & txtFind & "' in the document.", _ vbInformation, "Not Found" fStartY = 0 Exit Sub End If ' save top Y for next match fStartY = vp.Y2 ' show what we found vp.StartOverlay iStartPage vp.DrawRectangle vp.X1, vp.Y1, vp.X2, vp.Y2 vp.EndOverlay vp.PreviewPage = iStartPage vp.ScrollIntoView vp.X1, vp.Y1, vp.X2, vp.Y2 End Sub |
The code uses static variables (iStartPage and fStartY) to keep the page number and vertical position for the last match. These variables are reset when the user clicks the Find First button.
To find the text, the routine calls the FindText property using the iStartPage and fStartY variables. If the text is not found, the routine shows a dialog box and returns. If the text is found, the fStartY variable is updated, a red frame is drawn around the text on a page overlay, and the text is scrolled into view.
Note: The text returned by the FindText property includes the entire string that was added to the document when it was created, not just the argument passed to FindText. |