Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

426 Part III Designing the User Interface



  1. Scroll to the top of the form, and then enter the following code:


Imports System.IO 'for FileStream class
Imports System.Drawing.Printing
These statements make it easier to reference the FileStream class and the classes for
printing.


  1. Move the cursor below the Public Class Form1 statement, and then enter the following
    variable declarations:
    Private PrintPageSettings As New PageSettings
    Private StringToPrint As String
    Private PrintFont As New Font("Arial", 10)
    These statements define important information about the pages that will be printed.

  2. Scroll to the btnOpenClick event procedure, and then type the following program
    code:
    Dim FilePath As String
    'Display Open dialog box and select text file
    OpenFileDialog1.Filter = "Text files (.txt)|.txt"
    OpenFileDialog1.ShowDialog()
    'If Cancel button not selected, load FilePath variable
    If OpenFileDialog1.FileName <> "" Then
    FilePath = OpenFileDialog1.FileName
    Try
    'Read text file and load into RichTextBox1
    Dim MyFileStream As New FileStream(FilePath, FileMode.Open)
    RichTextBox1.LoadFile(MyFileStream,

    RichTextBoxStreamType.PlainText)
    MyFileStream.Close()
    'Initialize string to print
    StringToPrint = RichTextBox1.Text
    'Enable Print button
    btnPrint.Enabled = True
    Catch ex As Exception
    'display error messages if they appear
    MessageBox.Show(ex.Message)
    End Try
    End If
    When the user clicks the Open button, this event procedure displays an Open dialog
    box using a filter that displays only text files. When the user selects a file, the file name
    is assigned to a public string variable named FilePath, which is declared at the top of
    the event procedure. The procedure then uses a Try... Catch error handler to load the
    text file into the RichTextBox1 object. To facilitate the loading process, I’ve used the
    FileStream class and the Open file mode, which places the complete contents of the
    text file into the MyFileStream variable. Finally, the event procedure enables the Print
    button (btnPrint) so that the user can print the file. In short, this routine opens the file
    and enables the print button on the form but doesn’t do any printing itself.
    Now you’ll add the necessary program code to display the Print dialog box and print the file
    by using logic that monitors the dimensions of the current text page.

Free download pdf