Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning Visual Basic 2005 (2006)

.pdf
Скачиваний:
219
Добавлен:
17.08.2013
Размер:
14.97 Mб
Скачать

Chapter 7

‘Set the DocumentName property objPrintDocument.DocumentName = “Text File Print Demo”

‘Set the PrintDialog properties PrintDialog1.AllowPrintToFile = False PrintDialog1.AllowSelection = False PrintDialog1.AllowSomePages = False

‘Set the Document property to the objPrintDocument object PrintDialog1.Document = objPrintDocument

‘Show the Print dialog

If PrintDialog1.ShowDialog() = DialogResult.OK Then

‘If the user clicked on the OK button then set the StreamReader ‘object to the file name in the strFileName variable objStreamToPrint = New StreamReader(strFileName)

‘Set the print font

objPrintFont = New Font(“Arial”, 10)

‘Add an event handler for the PrintPage event of the ‘objPrintDocument object

AddHandler objPrintDocument.PrintPage, _ AddressOf objPrintDocument_PrintPage

‘Set the PrinterSettings property of the objPrintDocument ‘object to the PrinterSettings property returned from the ‘PrintDialog control

objPrintDocument.PrinterSettings = PrintDialog1.PrinterSettings

‘Print the text file objPrintDocument.Print()

‘Clean up objStreamToPrint.Close() objStreamToPrint = Nothing

End If End Sub

7.Now add the following procedure to perform the actually printing:

Private Sub objPrintDocument_PrintPage(ByVal sender As Object, _ ByVal e As System.Drawing.Printing.PrintPageEventArgs)

‘Declare variables

Dim sngLinesPerpage As Single = 0 Dim sngVerticalPosition As Single = 0

Dim intLineCount As Integer = 0

Dim sngLeftMargin As Single = e.MarginBounds.Left

Dim sngTopMargin As Single = e.MarginBounds.Top

Dim strLine As String

‘Work out the number of lines per page.

236

Displaying Dialog Boxes

‘Use the MarginBounds on the event to do this sngLinesPerpage = _

e.MarginBounds.Height / objPrintFont.GetHeight(e.Graphics)

‘Now iterate through the file printing out each line. ‘This assumes that a single line is not wider than the page

‘width. Check intLineCount first so that we don’t read a line ‘that we won’t print

strLine = objStreamToPrint.ReadLine()

While (intLineCount < sngLinesPerpage And Not (strLine Is Nothing))

‘Calculate the vertical position on the page sngVerticalPosition = sngTopMargin + _

(intLineCount * objPrintFont.GetHeight(e.Graphics))

‘Pass a StringFormat to DrawString for the ‘Print Preview control

e.Graphics.DrawString(strLine, objPrintFont, Brushes.Black, _ sngLeftMargin, sngVerticalPosition, New StringFormat())

‘Increment the line count intLineCount = intLineCount + 1

‘If the line count is less than the lines per page then ‘read another line of text

If (intLineCount < sngLinesPerpage) Then strLine = objStreamToPrint.ReadLine()

End If

End While

‘If we have more lines then print another page If (strLine <> Nothing) Then

e.HasMorePages = True

Else

e.HasMorePages = False End If

End Sub

8.You are now ready to test your code, so run the project.

9.Click the Open button to open a file, and then click the Print button to display the Print dialog box shown in Figure 7-15.

Notice that the Print to file check box as well as the Selection and Pages radio buttons are disabled. This is because you set the AllowPrintToFile, AllowSelection, and

AllowSomePages properties in the PrintDialogno control to False.

If you have more than one printer installed, as shown in Figure 7-15, you can choose the name of the printer that you want to use in the list.

10.Click the Print button in the Print dialog box to have your text printed.

237

Chapter 7

Figure 7-15

How It Works

You begin the btnPrint button’s Click event procedure by declaring an object as a PrintDocument. You use this object to perform the actual printing:

Dim objPrintDocument As PrintDocument = New PrintDocument()

Next, you set the DocumentName property for the PrintDocument object. This will be the name that you see when the document is printing and also the name that is shown in the printer queue:

objPrintDocument.DocumentName = “Text File Print Demo”

You then set some properties of the PrintDialog control. This will control the options on the Print dialog box. Since you are only doing basic printing in this example, you want the Print to File check box to be disabled along with the Pages and Selection radio buttons. The next three lines of code do this by setting these properties to False:

PrintDialog1.AllowPrintToFile = False

PrintDialog1.AllowSelection = False

PrintDialog1.AllowSomePages = False

With the PrintDialog control’s properties set, you set its Document property equal to the

PrintDocument object:

PrintDialog1.Document = objPrintDocument

238

Displaying Dialog Boxes

Then you show the Print dialog box, so you execute the ShowDialog method of the PrintDialog control in an If statement, as shown in the code next. Notice that you also are checking the DialogResult returned from the PrintDialog control:

If PrintDialog1.ShowDialog() = DialogResult.OK Then

If the user clicks the OK button in the Print dialog box, you actually want to execute the code for printing. The first thing that you do is to set the objStreamToPrint object to a new StreamReader class and pass it the strFileName variable:

objStreamToPrint = New StreamReader(strFileName)

Remember that this variable is set to the path and filename every time that you open or save a file. This will be the file that you print.

Next, you want to set the objPrintFont object to a valid font and font size. You have chosen an Arial font here and a font size of 10 points, but you could have put in any font and size that you wanted:

objPrintFont = New Font(“Arial”, 10)

You now want to add an event handler for the PrintPage event. Since the objPrintDocument object raises this event, you specify this object and the event. You then specify the address of the objPrintDocument_PrintPage procedure:

AddHandler objPrintDocument.PrintPage, _

AddressOf objPrintDocument_PrintPage

Next, you set the PrinterSettings property of the objPrintDocument object equal to the Printer Settings property of the PrintDialog control. This specifies the printer used, page orientation, and print quality chosen by the user:

objPrintDocument.PrinterSettings = PrintDialog1.PrinterSettings

You then call the Print method of the objPrintDocument object. Calling this method will raise the PrintPage event and the code inside the objPrintDocument_PrintPage procedure will be executed:

objPrintDocument.Print()

In the objPrintDocument_PrintPage procedure, you need to add two parameters: the first of which is the sender. Like every other procedure defined in this project, this argument is an object that lets you know what object called this procedure. The second parameter that you need to add is the Print PageEventArgs object. The PrintPage event receives this argument and it contains data related to the PrintPage event, such as margin boundaries and page boundaries.

Private Sub objPrintDocument_PrintPage(ByVal sender As Object, _

ByVal e As System.Drawing.Printing.PrintPageEventArgs)

239

Chapter 7

The first thing that you want to do in this procedure is to declare some variables and set their default values. Notice that you are setting the values for the sngLeftMargin and sngTopMargin variables using the PrintPageEventArgs that were passed to this procedure:

Dim sngLinesPerpage As Single = 0

Dim sngVerticalPosition As Single = 0

Dim intLineCount As Integer = 0

Dim sngLeftMargin As Single = e.MarginBounds.Left

Dim sngTopMargin As Single = e.MarginBounds.Top

Dim strLine As String

Next, you want to determine the number of lines that will fit on one page. You do this using the MarginBounds.Height property of PrintPageEventArgs. This property was set when you set the

PrinterSettings property of the objPrintDocument to the PrinterSettings property of the

PrintDialog control. WYoue divide the MarginBounds.Height by the height of the font that was set in the objPrintFont:

sngLinesPerpage = _

e.MarginBounds.Height / objPrintFont.GetHeight(e.Graphics)

Next, you read the first line from the text file and place the contents of that line in your strLine variable. Then you enter a loop to read and process all lines from the text file. You only want to process this loop while the intLineCount variable is less than the sngLinesPerPage variable and the strLine variable contains data to be printed:

strLine = objStreamToPrint.ReadLine()

While (intLineCount < sngLinesPerpage And Not (strLine Is Nothing))

Inside your While loop, you set the vertical position of the text to be printed. You calculate this position using the sngTopMargin variable and the intLineCount multiplied by the height of the printer font:

sngVerticalPosition = sngTopMargin + _

(intLineCount * objPrintFont.GetHeight(e.Graphics))

Using the DrawString method of the Graphics class, you actually send a line of text to the printer. Here you pass the strLine variable (which contains a line of text to be printed), the font to be used when printing, the brush color to be used, the left margin, vertical position, and the format to be used:

e.Graphics.DrawString(strLine, objPrintFont, Brushes.Black, _ sngLeftMargin, sngVerticalPosition, New StringFormat())

Next, you increment the line count on this page in the intLineCount variable:

intLineCount = intLineCount + 1

If the actual line count is less than the number of lines per page, you want to read another line from the text file to print. Then you go back to the beginning of your loop and process the next line of text:

If (intLineCount < sngLinesPerpage) Then strLine = objStreamToPrint.ReadLine()

240

Displaying Dialog Boxes

End If

End While

Having completed your While loop, enter an If statement to test the value of strLine:

If (strLine <> Nothing) Then e.HasMorePages = True

Else

e.HasMorePages = False End If

If the strLine variable is not Nothing, then you have more printing to do so you set HasMorePages property to True, causing the PrintPage event to be fired again, and you will continue to read the text file and print another page.

If strLine is Nothing, you have no more printing to do so you set the HasMorePages property to False, causing the Print method of the objPrintDocument object to end processing and move to the next line of code within the btnPrint_Click event procedure.

Since the printing has completed, you clean up by closing the text file that was used for printing and freeing up the resources used by the objStreamToPrint object:

objStreamToPrint.Close() objStreamToPrint = Nothing

The FolderBrowserDialog Control

Occasionally, you’ll have a need to allow your users to select a folder instead of a file. Perhaps your application performs backups, or perhaps you need a folder to save temporary files. The FolderBrowserDialog control displays the Browse For Folder dialog box, which allows your users to select a folder. This dialog box does not display files — only folders, which provides an obvious way to allow your users to select a folder needed by your application.

Like the other dialog boxes that you have examined thus far, the FolderBrowserDialog control can also be used as a class declared in code. The Browse For Folder dialog box, shown in Figure 7-16 without any customization, allows the user to browse for and select a folder. Notice that there is also a Make New Folder button that allows a user to create and select a new folder.

241

Chapter 7

Figure 7-16

The Properties of FolderBrowserDialog

Before you dive into some code, take a look at some of the available properties for the FolderBrowserDialog control, shown in the following table.

Property

Description

 

 

Description

Provides a descriptive message in the dialog box.

RootFolder

Indicates the root folder where the dialog box should start

 

browsing from.

SelectedPath

Indicates the folder selected by the user.

ShowNewFolderButton

Indicates whether the Make New Folder button is shown in the

 

dialog box.

This is one dialog control where you’ll want to use all of the most common properties, as shown in Table 7-12, to customize the dialog box displayed.

As with the other dialog controls, the FolderBrowserDialog contains a ShowDialog method. You have already seen this method in the previous examples, and since it is the same, it does not need to be discussed again.

Using the FolderBrowserDialog Control

Before showing the Browse For Folder dialog box, you’ll want to set some basic properties. The three main properties that you are most likely to set are shown in the following code snippet. The first of these properties is the Description property. This property allows you to provide a description or instructions for your users.

242

Displaying Dialog Boxes

The next property is the RootFolder property and specifies the starting folder for the Browse For Folder dialog box. This property uses one of the constants from the Environment.SpecialFolder enumeration. Typically you would use the MyComputer constant to specify that browsing should start at the My Computer level or sometimes you may want to use to the Personal constant to start browsing at the My Documents level.

The final property shown in the code snippet is the ShowNewFolderButton property. This property has a default value of True, which indicates that the Make New Folder button should be displayed. However, if you do not want this button displayed, you need to specify this property and set it to a value of False:

FolderBrowserDialog1.Description = “Select a folder for your backups:” FolderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer FolderBrowserDialog1.ShowNewFolderButton = False

After you have set the necessary properties, you execute the ShowDialog method to display the dialog box:

FolderBrowserDialog1.ShowDialog()

The FolderBrowserDialog control will return a DialogResult of OK or Cancel. Hence, you can use the previous statement in an If . . . End If statement and test for a DialogResult of OK, as you have done in the previous examples that you have coded.

To retrieve the folder that the user has chosen, you simply retrieve the value set in the SelectedPath property and assign it to a variable. The folder that is returned is a fully qualified path name. For example, if you chose a folder named Temp at the root of your C drive, the path returned would be C:\Temp:

strFolder = FolderBrowserDialog1.SelectedPath

In the next Try It Out, you continue using the same Dialogs project and have the FolderBrowserDialog control display the Browse For Folder dialog box. Then, if the dialog box returns a DialogResult of OK, you’ll display the selected folder in the text box on your form.

Try It Out

Working with the ColorDialog Control

1.Switch to the Forms Designer in the Dialogs project.

2.On the form, add another Button control from the Toolbox and set its properties according to the values shown:

Set Name to btnBrowse.

Set Anchor to Top, Right.

Set Location to 367, 158.

Set Text to Browse.

3.Next, add a FolderBrowserDialog control to your project from the Toolbox. It will be added to the workspace below the form. Accept all default properties for this control, because you’ll set the necessary properties in your code.

243

Chapter 7

4.Double-click the Browse button to bring up its Click event procedure, and add the following code:

Private Sub btnBrowse_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnBrowse.Click

‘Set the FolderBrowserDialog control properties FolderBrowserDialog1.Description = “Select a folder for your backups:” FolderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer FolderBrowserDialog1.ShowNewFolderButton = False

‘Show the Browse For Folder dialog

If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then ‘Display the selected folder

txtFile.Text = FolderBrowserDialog1.SelectedPath End If

End Sub

5.That’s all the code you need to add. To test your changes to this project, click the Start button.

6.When your form displays, click the Browse button, and you’ll see a Browse For Folder dialog similar to the one shown in Figure 7-17.

Figure 7-17

7.Now browse your computer and select a folder. When you click the OK button, the selected folder will be displayed in the text box on your form as shown in Figure 7-18. Notice that the folder returned contains a fully qualified path name.

How It Works

Before displaying the Browse For Folder dialog box, you needed to set some basic properties of the FolderBrowserDialog control to customize the look for this dialog box. You started by setting the Description property to provide some basic instructions for your user. Then you selected the root folder at which the Browse For Folder dialog box should start browsing. In this instance, you used the

244

Displaying Dialog Boxes

MyComputer constant, which displayed all drives on your computer, as shown in Figure 7-17. Finally, you set the ShowNewFolderButton property to False so as not to display the Make New Folder button:

‘Set the FolderBrowserDialog control properties FolderBrowserDialog1.Description = “Select a folder for your backups:” FolderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer FolderBrowserDialog1.ShowNewFolderButton = False

Figure 7-18

Then you displayed the dialog box in an If . . . End If statement to check the DialogResult returned by the ShowDialog method of the FolderBrowserDialog control:

‘Show the Browse For Folder dialog

If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then

Within the If . . . End If statement, you added the code necessary to display the folder selected in the text box on your form, using the SelectedPath property:

‘Display the selected folder

txtFile.Text = FolderBrowserDialog1.SelectedPath End If

Summar y

This chapter has taken a look at some of the dialog boxes that are provided in Visual Basic 2005. You examined the MessageBox dialog box, and the OpenFileDialog, SaveFileDialog, FontDialog, ColorDialog, PrintDialog, and FolderBrowserDialog controls. Each of these dialog boxes will help you provide a common interface in your applications for their respective functions. They also hide a lot of the complexities required to perform their tasks, allowing you to concentrate on the logic needed to make your application functional and feature-rich.

245