Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
(ebook) Visual Studio .NET Mastering Visual Basic.pdf
Скачиваний:
120
Добавлен:
17.08.2013
Размер:
15.38 Mб
Скачать

294 Chapter 7 MORE WINDOWS CONTROLS

This statement returns an integer value that represents the color Navy. This value, however, is negative. The reason for that is that the first byte in the color value represents the transparency of the color. To get the value of the color, you must take the absolute value of the integer value returned by the previous expression. To create an array of integers that represent color values, use a statement like the following:

Dim colors() As Integer = {Math.Abs(Color.Gray.ToARGB), _

Math.Abs(Color.Navy.ToARGB), _

Math.Abs(Color.Teal.ToARGB)}

Now you can assign the colors array to the CustomColors property of the control, and they will appear in the Custom Colors section of the Color dialog box. The three colors of the same code are the custom colors shown in Figure 7.2.

SolidColorOnly

Indicates whether the dialog box will restrict users to selecting solid colors only. This setting should be used with systems that can display only 256 colors.

The Font Dialog Box

The Font dialog box, shown in Figure 7.3, lets the user review and select a font and its size and style. Optionally, the user can also select the font’s color and even apply the current dialog-box settings to the selected text on a control of the form without closing the dialog box, by clicking the Apply button on the Font dialog box.

Figure 7.3

The Font common dialog box

After the user selects a font, its size and style, and possibly some special effects (the text color or the underline attribute), and clicks the OK button, the dialog returns the attributes of the selected font through its properties. In addition to the OK button, there’s an Apply button, which reports the current setting to your application. You can intercept the Click event of the Apply button and adjust the appearance of the text on your form while the common dialog is still visible.

The main property of this control is the Font property, which sets the initially selected font on the control and retrieves the font selected by the user. The following statements display the Font

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE COMMON DIALOG CONTROLS 295

dialog box after selecting the current font of the TextBox1 control. When the user closes the dialog box, they retrieve the selected font and assign it to the TextBox control:

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

ByVal e As System.EventArgs) Handles Button2.Click

FontDialog1.Font = TextBox1.Font

If FontDialog1.ShowDialog = DialogResult.OK Then

TextBox1.Font = FontDialog1.Font

End If

End Sub

AllowScriptChange

This property is a Boolean value that indicates whether the Script combo box will be displayed on the Font common dialog. This combo box allows the user to change the current character set and select a non-western language (like Greek, Hebrew, Cyrillic, and so on). The text on which the new font is applied will change to a different language only if the corresponding language has been installed on the system.

AllowSimulations

This property is a Boolean value that indicates whether the dialog box allows the display and selection of simulated fonts.

AllowVectorFonts

This property is a Boolean value that indicates whether the dialog box allows the display and selection of vector fonts.

AllowVerticalFonts

This property is a Boolean value that indicates whether the dialog box allows the display and selection of both vertical and horizontal fonts. Its default value is False, which displays only horizontal fonts.

Color

This property sets or returns the selected font color. The user will see the option to select a color for the selected font only if you set the ShowColor property to True.

FixedPitchOnly

This property is a Boolean value that indicates whether the dialog box allows only the selection of fixed-pitch fonts. Its default value is False, which means that all fonts (fixedand variable-pitch fonts) are displayed on the common dialog.

Font

This property is a Font object. You can set it to the preselected font before displaying the dialog box and assign it to a Font property upon return. The following statements show how to preselect

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

296 Chapter 7 MORE WINDOWS CONTROLS

the font of the TextBox1 control on the Font dialog box and how to change the same control’s font to the one selected by the user on the dialog box:

FontDialog1.Font = TextBox1.Font

If FontDialog1.ShowDialog = DialogResult.OK Then

TextBox1.Font = FontDialog1.Font

End If

You can create a new Font object and assign it to the control’s Font property. The following statements do that:

Dim newFont As Font

newFont = New Font(“Verdana”, 12, FontStyle.Underline) FontDialog1.Font = newFont

FontDialog1.ShowDialog()

The Font object’s constructor is heavily overloaded. The form shown here is among the simpler overloaded forms of the constructor. To apply multiple attributes, combine their names with the Or operator.

The Color property is not part of the Font property. If you allow users to change the font’s color, you must handle this property separately from within your code. To continue the previous example, the following statement sets the color of the new font:

TextBox1.ForeColor = FontDialog1.Color

FontMustExist

This property is a Boolean value that indicates whether the dialog box forces the selection of an existing font. If the user enters a font name that doesn’t correspond to a name in the list of available fonts, a warning is displayed. Its default value is True.

MaxSize, MinSize

These two properties are integers that determine the minimum and maximum point size the user can select. Use these two properties to prevent the selection of extremely large or extremely small font sizes.

ScriptsOnly

This property indicates whether the dialog box allows selection of fonts for Symbol character sets, in addition to the American National Standards Institute (ANSI) character set. Its default value is True.

ShowApply

This property is a Boolean value that indicates whether the dialog box provides an Apply button. Its default value is False, so the Apply button isn’t normally displayed. If you set this property to True, you must also program the control’s Apply button—the changes aren’t applied automatically to any of the controls on the current form.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE COMMON DIALOG CONTROLS 297

The following statements display the Font dialog box with the Apply button:

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

ByVal e As System.EventArgs) Handles Button2.Click

FontDialog1.Font = TextBox1.Font

FontDialog1.ShowApply = True

If FontDialog1.ShowDialog = DialogResult.OK Then

TextBox1.Font = FontDialog1.Font

End If

End Sub

If you display the Apply button, you must also capture its Click event and process it from within your code. The FontDialog control raises the Apply event every time the user clicks the Apply button. In this event’s handler, you must read the currently selected font and assign it to the TextBox control on the form:

Private Sub FontDialog1_Apply(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles FontDialog1.Apply TextBox1.Font = FontDialog1.Font

End Sub

ShowColor

This property is a Boolean value that indicates whether the dialog box allows the user to select a color for the font.

ShowEffects

This property is a Boolean value that indicates whether the dialog box contains controls to allow the user to specify special text effects, such as strikethrough and underline. The effects are returned to the application as attributes of the selected Font object, and you don’t have to anything special in your application.

The Open and Save As Dialog Boxes

Open and Save As are the two most widely used common dialog boxes, and they’re implemented by the OpenFileDialog and SaveFileDialog controls. Nearly every application prompts the user for a filename, and VB provides two controls for this purpose. The two dialog boxes are nearly identical and most of their properties are common, so we’ll start with the properties that are common to both controls.

When one of the two controls is displayed, it rarely displays all the files in any given folder. Usually the files displayed are limited to the ones that the application recognizes so that users can easily spot the file they want. The Filter property determines which files appear in the Open or Save dialog box (Figure 7.4).

It’s also standard for the Windows interface not to display the extensions of files (although Windows distinguishes files using their extensions). The Save As Type combo box contains the various file types recognized by the application. The various file types can be described in plain English with long descriptive names and without their extensions.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

298 Chapter 7 MORE WINDOWS CONTROLS

Figure 7.4

The Save As dialog box

The extension of the default file type for the application is described by the DefaultExtension property, and the list of the file types displayed in the Save As Type box is described by the Filter property. Both the DefaultExtension and the Filter properties are available in the control’s Properties window at design time. At runtime, you must set them manually from within your code.

To prompt the user for the file to be opened, use the following statements. This dialog box displays the files with the extension .BIN only.

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

ByVal e As System.EventArgs) Handles bttnSave.Click

OpenFileDialog1.DefaultExt = “.BIN”

OpenFileDialog1.AddExtension = True

OpenFileDialog1.Filter = “Binary Files|*.bin”

If OpenFileDialog1.ShowDialog() = DialogResult.OK Then

Console.WriteLine(OpenFileDialog1.FileName)

End If

End Sub

The following sections describe the properties of the OpenFileDialog and SaveFileDialog controls.

AddExtension

This property is a Boolean value that determines whether the dialog box automatically adds an extension to a filename, if the user omits it. The extension added automatically is the one specified by the DefaultExtension property, which must be set before you call the ShowDialog method.

CheckFileExists

This property is a Boolean value that indicates whether the dialog box displays a warning if the user enters the name of a file that does not exist.

CheckPathExists

This property is a Boolean value that indicates whether the dialog box displays a warning if the user specifies a path that does not exist, as part of the user-supplied filename.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE COMMON DIALOG CONTROLS 299

DefaultExtension

This property sets the default extension of the dialog box. Use this property to specify a default filename extension, such as TXT or DOC, so that when a file with no extension is saved, the extension specified by this property is automatically appended to the filename, as long as the AddExtension property is also set to True. The default extension property starts with the period, and it’s a string like “.BIN”.

DereferenceLinks

This property indicates whether the dialog box returns the location of the file referenced by the shortcut or the location of the shortcut itself. If you attempt to select a shortcut on your desktop with the DereferenceLinks property set to False, the dialog box will return to your application a value like C:\WINDOWS\SYSTEM32\lnkstub.exe, which is the name of the shortcut, and not the name of the file represented by the shortcut. If you set the DereferenceLinks property to True, the dialog box will return the actual filename represented by the shortcut, which you can use in your code.

FileName

This property is the path of the file selected by the user on the control. If you set this property to a filename before opening the dialog box, this value will be the proposed filename. The user can click OK to select this file, or select another one on the control. Read this property from within your code only if the control was closed with OK button. If the user closed it with the Cancel button, you should ignore the setting of this value. The two controls provide another related property, the FileNames property, which returns an array of filenames. To find out how to allow the user to select multiple files, see the discussion of the MultipleFiles and FileNames properties under “VB.NET at Work: Multiple File Selection” at the end of this section.

Filter

This property is used to specify the type(s) of files displayed on the dialog box. To display text files only, set the Filter property to “Text files|*.txt”. The pipe symbol separates the description of the files (what the user sees) from the actual extension (how the operating system distinguishes the various file types).

If you want to display multiple extensions, such as BMP, GIF, and JPG, use a semicolon to separate extensions with the Filter property. The string “Images|*.BMP;*.GIF;*.JPG” displays all the files of these three types when the user selects Images in the Save As Type box.

Don’t include spaces before or after the pipe symbol because these spaces will be displayed with the description and Filter values. In the Open common dialog of an image-processing application, you’ll probably provide options for each image file type, as well as an option for all images:

OpenFileDialog1.Filter = “Bitmaps|*.BMP|GIF Images|*.GIF|JPEG” & _

“Images|*.JPG|All Images|*.BMP;*.GIF;*.JPG”

The Open dialog box has four options, which determine what appears in the Save As Type box (see Figure 7.5).

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

300 Chapter 7 MORE WINDOWS CONTROLS

Figure 7.5

Displaying multiple file types in the Open dialog box

FilterIndex

When you specify more than one filter for the Open dialog box, the filter specified first in the Filter property becomes the default. If you want to use a Filter value other than the first one, use the FilterIndex property to determine which filter will be displayed as the default when the common dialog is opened. The index of the first filter is 1, and there’s no reason to ever set this property to 1. If you want to use the Filter property value of the example in the preceding section and set the FilterIndex property to 2, the Open dialog box will display GIF files by default.

InitialDirectory

This property sets the initial directory (folder) in which files are displayed the first time the Open and Save dialog boxes are opened. Use this property to display the files of the application’s folder or to specify a folder in which the application will store its files by default. If you don’t specify an initial folder, it will default to the last folder where the dialog box opened or saved a file. It’s also customary to set the initial folder to the application’s path, with the following statement:

OpenFileDialog1.InitialDirectory = Application.ExecutablePath

The expression Application.ExecutablePath returns the path in which the application’s executable file resides. You can also create a default data folder for the application during installation and use this folder’s name as the initial directory.

RestoreDirectory

Every time the Open and Save dialog boxes are displayed, the current folder is the one selected by the user the last time the control was displayed. The RestoreDirectory property is a Boolean value that indicates whether the dialog box restores the current directory before closing. Its default value is False, which means that the initial directory is not restored automatically. The InitialDirectory property overrides the RestoreDirectory property.

ValidateNames

This property is a Boolean value that indicates whether the dialog box accepts only valid Win32 filenames. Its default value is True, and you shouldn’t change it.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE COMMON DIALOG CONTROLS 301

Tip The following four properties—FileNames, MultiSelect, ReadOnlyChecked, and ShowReadOnly—are properties of the OpenFileDialog control only.

FileNames

If the Open dialog box allows the selection of multiple files (see the later section “VB.NET at Work: Multiple File Selection”), the FileNames property contains the pathnames of all selected files. FileNames is a collection, and you can iterate through the filenames with an enumerator. See the MultipleFiles application for an example of iterating through the collection of the selected files. This property is unique to the OpenFileDialog control.

MultiSelect

This property is a Boolean value that indicates whether the user can select multiple files on the dialog box. Its default value is False, and users can select a single file. When the MultiSelect property is True, the user can select multiple files, but they must all come from the same folder. You can’t allow the selection of multiple files from different folders. This property is unique to the OpenFileDialog control.

ReadOnlyChecked

This property is a Boolean value that indicates whether the Read-Only check box is initially selected when the dialog box first pops up (the user can clear this box to open a file in read/write mode). You can set this property to True only if the ShowReadOnly property is also set to True. This property is unique to the OpenFileDialog control.

ShowReadOnly

This property is a Boolean value that indicates whether the Read-Only check box is available. If this check box appears on the form, the user can check it so that the file will be opened as read-only. Files opened as read-only shouldn’t be saved onto the same file—you can prompt the user for a new filename, but you shouldn’t save them with the same filename. This property is unique to the OpenFileDialog control.

VB.NET at Work: The OpenFile and SaveFile Methods

The OpenFileDialog control exposes the OpenFile method, which allows you to quickly open the selected file. Normally, after retrieving the name of the file selected by the user, you must open this file for reading (in the case of the Open dialog box) or writing (in the case of the Save dialog box).

The topic of reading from, or writing to, files is discussed in detail in Chapter 13. In this section, I’ll show you how to quickly read the selected file through the OpenFileDialog control’s OpenFile method.

When the OpenFile method is applied to the Open dialog box, the file is opened with read-only permission. The same method can be applied to the Save dialog box, in which case the file is opened with read-write permission. The OpenFile method is demonstrated by the OpenMethod project, whose main form is shown in Figure 7.6.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

302 Chapter 7 MORE WINDOWS CONTROLS

Figure 7.6

The main form of the OpenMethod project

The following code segment demonstrates how to open a text file with the OpenFile method, read its contents, and display it on a TextBox control. The code displays the Open dialog box and then calls the control’s OpenFile method to open the file and read it. Listing 7.1 is code behind the Open And Read Text File button on the form.

Listing 7.1: The OpenFile Method of the OpenFileDialog Control

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

ByVal e As System.EventArgs) Handles readTextFile.Click OpenFileDialog1.ShowDialog()

Dim str As System.IO.Stream str = OpenFileDialog1.OpenFile

Dim txt As New System.Text.StringBuilder() Dim buffer(1000) As Byte

Dim numBytesToRead As Integer = CInt(str.Length) Dim numBytesRead As Integer = 0

Dim n As Integer

While (numBytesToRead > 0)

n = str.Read(buffer, 0, 1000) Console.WriteLine(n.ToString & “read”) If n = 0 Then

Exit While End If

Dim i As Integer

For i = 0 To n txt.Append(Chr(buffer(i)))

Next numBytesRead += n

numBytesToRead -= n End While

str.Close()

TextBox1.Text = txt.ToString End Sub

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE COMMON DIALOG CONTROLS 303

The code reads the file 1,000 characters at a time and appends the characters to a StringBuilder variable (this type of variable is especially efficient for manipulating strings, and you’ll learn more about it in Chapter 12). The Read method of the Stream object reads 1,000 characters and stores them to the buffer array. Then the characters of the array are appended to a StringBuilder variable, the txt variable, which is finally displayed on the TextBox control.

VB.NET at Work: Multiple File Selection

The Open dialog box allows the selection of multiple files. This option isn’t very common, but it can come in handy in situations when you want to process files en masse. You can let the user select many files and then process them one at a time. Or you may wish to prompt the user to select multiple files to be moved or copied.

To allow the user to select multiple files on the Open dialog box, set the MultiSelect property to True. The user can then select multiple files with the mouse by holding down the Shift or Ctrl key. The names of the selected files are reported by the property FileNames, which is an array of strings. The FileNames array contains the pathnames of all selected files, and you can iterate through them as you would iterate through the elements of any array.

In this chapter’s folder on the CD, you’ll find the MultipleFiles project, which demonstrates the use of the FileNames property. The application’s form is shown in Figure 7.7. The button at the top of the form opens a File dialog box, where you can select multiple files. After closing the dialog box by clicking the Open button, the application displays the pathnames of the selected files in the ListBox control.

Figure 7.7

The MultipleFiles project lets the user select multiple files on an Open dialog box.

The code behind the Open Files button is shown in Listing 7.2. In this example, I’ve used the array’s enumerator to iterate through the elements of the FileNames array. You can use any of the methods discussed in Chapter 3 to iterate through the array.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com