Sabtu, 20 Juni 2009

Belajar vb.net volume 4#

Learn Visual Basic .NET


4. More Exploration of the Visual Basic .NET Toolbox


Review and Preview

• In this class, we continue looking at tools in the Visual Basic .NET toolbox. We will look at some input tools, scroll bars, picture boxes and controls that allow direct interaction with drives, directories, and files. In the examples, you should start trying to do as much of the building and programming of the applications you can with minimal reference to the notes. This will help you build your programming skills.



Control Z Order

• As you build Windows applications using Visual Basic .NET, you will notice that whenever controls occupy the same space on a form, one control is on top of the other. The relative location of controls on a form is established by what is called the Z Order.

• As each control is placed on the form, it is assigned a Z Order value. Controls placed last will lie over controls placed earlier. While designing an application, the Z Order can be changed by right-clicking the control of interest. A menu will appear. Selecting BringToFront will bring that control ‘in front’ of all other controls. Conversely, selecting SendToBack will send that control ‘behind’ all other controls.

• A control’s Z Order can also be changed in code. Why would you want to do this? Perhaps, you have two controls on the form in exactly the same location, one that should be accessible for one particular operation and the other accessible for another operation. To place one control in front of the other, you need to change the Z Order. The BringToFront and SendToBack methods accomplish this task. For a control named ControlExample, the code to accomplish this is:

ControlName.BringToFront()

Or

ControlName.SendToBack()

• Now, let’s continue our look at the Visual Basic .NET toolbox, looking first at more controls that allow ‘point and click’ selections.

NumericUpDown Control

In Toolbox:



On Form (Default Properties):



• The NumericUpDown Control is used to obtain a numeric input. It looks like a text box control with two small arrows. Clicking the arrows changes the displayed value, which ranges from a specified minimum to a specified maximum. The user can even type in a value, if desired. Such controls are useful for supplying a date in a month or are used as volume controls in some Windows multimedia applications.

• NumericUpDown Properties:

Name Gets or sets the name of the numeric updown (three letter prefix for numeric updown name is nud).
BackColor Get or sets the numeric updown background color.
BorderStyle Gets or sets the border style for the updown control.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text or graphics.
Increment Gets or sets the value to increment or decrement the updown control when the up or down buttons are clicked.
Maximum Gets or sets the maximum value for the updown control.
Minimum Gets or sets the minimum value for the updown control.
ReadOnly Gets or sets a value indicating whether the text may be changed by the use of the up or down buttons only.
TextAlign Gets or sets the alignment of text in the numeric updown.
Value Gets or sets the value assigned to the updown control.

• NumericUpDown Methods:

DownButton Decrements the value of the updown control.
UpButton Increments the value of the updown control.


• NumericUpDown Events:

LostFocus Occurs when the updown control loses focus.
ValueChanged Occurs when the Value property has been changed in some way.

• The Value property can be changed by clicking either of the arrows or, optionally by typing a value. If using the arrows, the value will always lie between Minimum and Maximum. If the user can type in a value, you have no control over what value is typed. However, once the control loses focus, the typed value will be compared to Minimum and Maximum and any adjustments made. Hence, if you allow typed values, only check the Value property in the LostFocus event.

• Typical use of NumericUpDown control:

 Set the Name, Minimum and Maximum properties. Initialize Value property. Decide on value for ReadOnly.
 Monitor ValueChanged (or LostFocus) event for changes in Value.
 You may also want to change the Font, Backcolor and Forecolor properties.


DomainUpDown Control

In Toolbox:



On Form (Default Properties):



• The DomainUpDown control is similar in appearance to the NumericUpDown control. The difference is that the DomainUpDown control displays a list of string items (rather than numbers) as potential choices. It is much like a single line ComboBox control with no dropdown list. You will see it shares many of the properties of the ComboBox. The DomainUpDown control is usually reserved for relatively small lists. Examples of use are selecting a state in the United States for an address book, selecting a month for a calendar input or selecting a name from a short list.

• DomainUpDown Properties:

Name Gets or sets the name of the domain updown (three letter prefix for domain updown name is dud).
BackColor Get or sets the domain updown background color.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text.
Items Gets the Items object of the domain updown.
ReadOnly Gets or sets a value indicating whether the text may be changed by the use of the up or down buttons only.
SelectedIndex Gets or sets the zero-based index of the currently selected item.
SelectedItem Gets or sets the selected item based on the index value of the selected item.
Sorted Gets or sets a value indicating whether items are sorted alphabetically.
Text Gets or sets the text displayed in the updown control.
TextAlign Gets or sets the alignment of the text in the updown control.
Wrap Gets or sets a value indicating whether the list of items continues to the first or last item if the user continues past the end of the list.


• DomainUpDown Methods:

DownButton Displays the next item in the control.
UpButton Displays the previous item in the control.

• DomainUpDown Events:

KeyPress Occurs when a key is pressed while the domain updown has focus.
SelectedItemChanged Occurs when the SelectedItem property has changed.
TextChanged Occurs when the Text property has changed.

• Like the ListBox and ComboBox controls, the Items object provides details on what is in the control and how to add/delete information from the control. The first item in a updown control named dudExample is:

dudExample.Items.Item(0)

The last item in the list is:

dudExample.Items.Item(dudExample.Items.Count - 1)

• To add an item to the control, use the Add method, to delete an item, use the Remove method and to clear it use the Clear method. For our example:

Add Item: dudExample.Items.Add(StringToAdd)
Delete Item: dudExample.Items.Remove(IndexOfItem)
Clear list box: dudExample.Items.Clear

• Typical use of DomainUpDown control:

 Set Name property, decide whether ReadOnly should be True and populate Items object (usually in Form Load procedure).
 Monitor SelectedItemChanged (or TextChanged) event for individual selections.
 Read Text property to identify choice.
 As usual, you may also want to change the Font, Backcolor and Forecolor properties.


Example 4-1

Date Input Device

1. Start a new project. In this project, we’ll use a NumericUpDown control, in conjunction with a DomainUpDown control, to select a month and day of the year.

2. Place a NumericUpDown control, a DomainUpDown control and a Label control on the form. The form should resemble this:



3. Set these properties:

Form1:
Name frmDate
FormBorderStyle FixedSingle
StartPosition CenterScreen
Text Date Input

DomainUpDown1:
Name dudMonth
BackColor White
Font Size 14
ReadOnly True
Wrap True

NumericUpDown1:
Name nudDay
BackColor White
Font Size 14
Maximum 31
Minimum 1
ReadOnly True
TextAlign Center
Value 1

Label1:
Name lblDate
Font Size 12
Text [Blank]
TextAlign MiddleCenter

When done, the form should look like this:



4. Use this code in the Form Load procedure to populate the control with the month names:

Private Sub frmDate_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dudMonth.Items.Add("January")
dudMonth.Items.Add("February")
dudMonth.Items.Add("March")
dudMonth.Items.Add("April")
dudMonth.Items.Add("May")
dudMonth.Items.Add("June")
dudMonth.Items.Add("July")
dudMonth.Items.Add("August")
dudMonth.Items.Add("September")
dudMonth.Items.Add("October")
dudMonth.Items.Add("November")
dudMonth.Items.Add("December")
dudMonth.SelectedIndex = 0
lblDate.Text = dudMonth.Text + Str(nudDay.Value)
End Sub


5. Use this code in the dudMonth SelectedItemChanged event to update date if month changes:

Private Sub dudMonth_SelectedItemChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dudMonth.SelectedItemChanged
lblDate.Text = dudMonth.Text + Str(nudDay.Value)
End Sub

6. Use this code in the nudDay ValueChanged event to update date if day changes:

Private Sub nudDay_ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles nudDay.ValueChanged
lblDate.Text = dudMonth.Text + Str(nudDay.Value)
End Sub

7. Run the program. Scroll through the month names. Notice how the Wrap property allows the list to return to January after December. Scroll through the day values, noticing how the displayed date changes. Save the project (saved in Example 4-1 folder in the LearnVBN\VBN Code\Class 4 folder).

Do you notice that you could enter April 31 as a date, even though it’s not a legal value? Can you think of how to modify this example to make sure you don’t exceed the number of days in any particular month? And, how would you handle February – you need to know if it’s a leap year.

Horizontal and Vertical ScrollBar Controls

Horizontal ScrollBar In Toolbox:



Horizontal ScrollBar On Form (Default Properties):



Vertical ScrollBar In Toolbox:



Vertical ScrollBar On Form (Default Properties):



• The NumericUpDown control is useful for relatively small ranges of numeric input. It wouldn’t work well for large number ranges – you’d spend a lot of time clicking those little arrows. For large ranges of numbers, we use horizontal (HScrollBar) and vertical (VScrollBar) scroll bar controls. Scroll bars are widely used in Windows applications. Scroll bars provide an intuitive way to move through a list of information and make great input devices. Here, we use a scroll bar to obtain a whole number (Integer data type).

• Both type of scroll bars are comprised of three areas that can be clicked, or dragged, to change the scroll bar value. Those areas are:




Clicking an end arrow increments the scroll box a small amount, clicking the bar area increments the scroll box a large amount, and dragging the scroll box (thumb) provides continuous motion. Using the properties of scroll bars, we can completely specify how one works. The scroll box position is the only output information from a scroll bar.


• ScrollBar Properties (apply to both horizontal and vertical controls):

Name Gets or sets the name of the scroll bar (three letter prefix for horizontal scroll bar is hsb, for vertical scroll bar vsb).
LargeChange Increment added to or subtracted from the scroll bar Value property when the bar area is clicked.
Maximum The maximum value of the horizontal scroll bar at the far right and the maximum value of the vertical scroll bar at the bottom.
Minimum The minimum value of the horizontal scroll bar at the left and the vertical scroll bar at the top
SmallChange The increment added to or subtracted from the scroll bar Value property when either of the scroll arrows is clicked.
Value The current position of the scroll box (thumb) within the scroll bar. If you set this in code, Visual Basic .NET moves the scroll box to the proper position.

Location of properties for horizontal scroll bar:







Location of properties for vertical scroll bar:






• A couple of important notes about scroll bar properties:

1. Notice the vertical scroll bar has its Minimum at the top and its Maximum at the bottom. This may be counter-intuitive in some applications. That is, users may expect things to ‘go up’ as they increase. You can give this appearance of going up by defining another variable that varies ‘negatively’ with the scroll bar Value property.

2. If you ever change the Value, Minimum, or Maximum properties in code, make sure Value is at all times between Minimum and Maximum or the program will stop with an error message.

• ScrollBar Events:

Scroll Occurs when the scroll box has been moved by either a mouse or keyboard action.

• Typical use of HScrollBar and VScrollBar controsl:

 Decide whether horizontal or vertical scroll bar fits your needs best.
 Set the Name, Minimum, Maximum, SmallChange, LargeChange properties. Initialize Value property.
 Monitor Scroll event for changes in Value.


Example 4-2

Temperature Conversion

1. Start a new project. In this project, we convert temperatures in degrees Fahrenheit (set using a horizontal scroll bar) to degrees Celsius. The formula for converting Fahrenheit (F) to Celsius (C) is:

C = (F - 32) * 5 / 9

Temperatures will be adjusted and displayed in tenths of degrees.

2. Place a horizontal scroll bar, four labels, and a button on the form. Place two more labels (right behind each other) behind the scroll bar (we’ll use these for special effects). It should resemble this:




3. Set the properties of the form and each control:

Form1:
Name frmTemp
FormBorderStyle FixedSingle
StartPosition CenterScreen
Text Temperature Conversion

Label1:
Font Microsoft Sans Serif, Bold, Size 10
Text Fahrenheit
TextAlign MiddleCenter

Label2:
Name lblTempF
BackColor White
BorderStyle Fixed3D
Font Microsoft Sans Serif, Bold, Size 10
Text 32.0
TextAlign MiddleCenter

Label3:
Font Microsoft Sans Serif, Bold, Size 10
Text Celsius
TextAlign MiddleCenter

Label4:
Name lblTempC
BackColor White
BorderStyle Fixed3D
Font Microsoft Sans Serif, Bold, Size 10
Text 0.0
TextAlign MiddleCenter

Label5:
Name lblBlue
BackColor Blue

Label6:
Name lblRed
BackColor Red


HScrollBar1:
Name hsbTemp
LargeChange 10
Maximum 1200
Minimum -600
SmallChange 1
Value 320

Note the scroll bar properties (Value, Minimum, Maximum, SmallChange, LargeChange) are in tenths of degrees. The initial temperatures are initialized at 32.0 F (Value = 320 tenths of degrees) and 0.0 C, known values.

When done, the form should look like this:



3. Form level scope declarations:

Dim IsHot As Boolean


4. Use this code in the hsbTemp Scroll event.

Private Sub hsbTemp_Scroll(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles hsbTemp.Scroll
Dim TempF As Single, TempC As Single
'Read F and convert to C - divide by 10 needed since Value is tenths of degrees
TempF = CSng(Val(hsbTemp.Value) / 10)
'check to see if changed from hot to cold or vice versa
If IsHot And TempF < 70 Then
'changed to cold
IsHot = False
lblBlue.BringToFront()
hsbTemp.BringToFront()
ElseIf Not (IsHot) And TempF >= 70 Then
'changed to hot
IsHot = True
lblRed.BringToFront()
hsbTemp.BringToFront()
End If
lblTempF.Text = Format(TempF, "0.0")
TempC = (TempF - 32) * 5 / 9
lblTempC.Text = Format(TempC, "0.0")
End Sub

This code determines the scroll bar Value as it changes, takes that value as Fahrenheit temperature, computes Celsius temperature, and displays both values. A blue label is used for cold temperatures, a red label for warm temperatures.

5. Give the program a try. Make sure it provides correct information at obvious points. For example, 32.0 F better always be the same as 0.0 C! What happens around 70 F? Save the project (saved in Example 4-2 folder in the LearnVBN\VBN Code\Class 4 folder).

Can you find a point where Fahrenheit temperature equals Celsius temperature? If you don't know this off the top of your head, it's obvious you've never lived in extremely cold climates. I've actually witnessed one of those bank temperature signs flashing degrees F and degrees C and seeing the same number! Ever wonder why body temperature is that odd figure of 98.6 degrees F? Can your new application give you some insight to an answer to this question?


PictureBox Control

In Toolbox:



On Form (Default Properties):



• Visual Basic .NET has powerful features for graphics. The PictureBox control is the primary tool for exploiting these features. The picture box control can display graphics files (in a variety of formats), can host many graphics functions and can be used for detailed animations. We look at using picture boxes for graphics and animations in later chapters. Here, we concentrate on using the control to display a graphics file.

• PictureBox Properties:

Name Gets or sets the name of the picture box (three letter prefix for picture box name is pic).
BackColor Get or sets the picture box background color.
BorderStyle Indicates the border style for the picture box.
Height Height of picture box in pixels.
Image Establishes the graphics file to display in the picture box.
Left Distance from left edge of form to left edge of picture box, in pixels.
SizeMode Indicates how the image is displayed.
Top Distance bottom of form title bar area to top edge of picture box, in pixels.
Width Width of picture box in pixels.

• PictureBox Events:

Click Triggered when a picture box is clicked.


• The Image property specifies the graphics file to display. It can be established in design mode or at run-time. To set the Image property at design time, simply display the Properties window for the picture box control and select the Image property. An ellipsis (…) will appear. Click the ellipsis and an Open File dialog box will appear. Use that box to locate the graphics file to display.

• Five types of graphics files can be viewed in a picture box:

File Type Description
Bitmap An image represented by pixels and stored as a collection of bits in which each bit corresponds to one pixel. This is the format commonly used by scanners and paintbrush programs. Bitmap filenames have a .bmp extension.
Icon A special type of bitmap file of maximum 32 x 32 size. Icon filenames have an .ico extension. We’ll create icon files in Class 5
Metafile A file that stores an image as a collection of graphical objects (lines, circles, polygons) rather than pixels. Metafiles preserve an image more accurately than bitmaps when resized. Many graphics files available for download from the internet are metafiles. Metafile filenames have a .wmf extension.
JPEG JPEG (Joint Photographic Experts Group) is a compressed bitmap format which supports 8 and 24 bit color. It is popular on the Internet and is a common format for digital cameras. JPEG filenames have a .jpg extension.
GIF GIF (Graphic Interchange Format) is a compressed bitmap format originally developed by CompuServe. It supports up to 256 colors and is also popular on the Internet. GIF filenames have a .gif extension.

• To set the Image property at run-time, you use the FromFile method associated with the Image object. As an example, to load the file c:\\sample\myfile.bmp into a picture box name picExample, the proper code is:

picExample.Image = Image.FromFile(“c:\\sample\myfile.bmp”)

The argument in the Image.From method must be a legal, complete path and file name, or your program will stop with an error message.


• To clear an image from a picture box control at run-time, simply set the corresponding Image property to Nothing (a Basic keyword). This disassociates the Image property from the last loaded image. For our example, the code is:

picExample.Image = Nothing

• The SizeMode property dictates how a particular image will be displayed. There are four possible values for this property: Normal, StretchImage, AutoSize, CenterImage. The effect of each value is:

SizeMode Effect
Normal Image appears in original size. If picture box is larger than image, there will be blank space. If picture box is smaller than image, the image will be cropped.
CenterImage Image appears in original size, centered in picture box. If picture box is larger than image, there will be blank space. If picture box is smaller than image, image is cropped.
StretchImage Image will ‘fill’ picture box. If image is smaller than picture box, it will expand. If image is larger than picture box, it will scale down. Bitmap and icon files do not scale nicely, Metafiles, JPEG and GIF files do scale nicely.
AutoSize Reverse of StretchImage - picture box will change its dimensions to match the original size of the image. Be forewarned – metafiles are usually very large!

Notice picture box dimensions remain fixed for Normal, CenterImage, and StretchImage SizeMode values. With AutoSize, the picture box will grow in size. This may cause problems at run-time if your form is not large enough to ‘contain’ the picture box.

• Typical use of PictureBox control for displaying images:

 Set the Name and SizeMode property (most often, StretchImage).
 Set Image property, either in design mode or at run-time.


OpenFileDialog Control

In Toolbox:



Below Form (Default Properties):



• Note that to set the Image property of the picture box control, you need the path and filename for the image file. How can you get this from a user? One possibility would be to use a text box control, asking the user to type in the desired information? This is just asking for trouble. Even the simplest of paths is difficult to type, remembering drive names, proper folder names, file names and extensions, and where all the slashes go. And then you, the programmer, must verify that the information typed contains a valid path and valid file name.

• I think you see that asking a user to type a path and file name is a bad idea. We want a ‘point and click’ type interface to get a file name. Every Windows application provides such an interface for opening files. [Click on the Open File toolbar button in Visual Basic .NET and an ‘Open File’ dialog box will appear.] Visual Basic .NET lets us use this same interface in our applications via the OpenFileDialog control. This control is one of a suite of dialog controls we can add to our applications. There are also dialog controls to save files, change fonts, change colors, and perform printing operations. We’ll look at other dialog controls as we work through the course.

• What we learn here is not just limited to opening image files for the picture box control. There are many times in application development where we will need a file name from a user. Applications often require data files, initialization files, configuration files, sound files and other graphic files. The OpenFileDialog control will also be useful in these cases.


• OpenFileDialog Properties:

Name Gets or sets the name of the open file dialog (I usually name this control dlgOpen).
AddExtension Gets or sets a value indicating whether the dialog box automatically adds an extension to a file name if the user omits the extension.
CheckFileExists Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist.
CheckPathExists Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a path that does not exist.
DefaultExt Gets or sets the default file extension.
FileName Gets or sets a string containing the file name selected in the file dialog box.
Filter Gets or sets the current file name filter string, which determines the choices that appear in "Files of type" box.
FilterIndex Gets or sets the index of the filter currently selected in the file dialog box.
InitialDirectory Gets or sets the initial directory displayed by the file dialog box.
Title Gets or sets the file dialog box title.

• OpenFileDialog Methods:

ShowDialog Displays the dialog box. Returned value indicates which button was clicked by user (OK or Cancel).

• To use the OpenFileDialog control, we add it to our application the same as any control. Since the OpenFileDialog control has no immediate user interface (you control when it appears), the control does not appear on the form at design time. Such Visual Basic .NET controls (the Timer control seen briefly back in Chapter 1 was a similar control) appear in a ‘tray’ below the form in the IDE Design window. Once added, we set a few properties. Then, we write code to make the dialog box appear when desired. The user then makes selections and closes the dialog box. At this point, we use the provided information for our tasks.


• The ShowDialog method is used to display the OpenFileDialog control. For a control named dlgOpen, the appropriate code is:

dlgOpen.ShowDialog()

And the displayed dialog box is:



• The user selects a file using the dialog control (or types a name in the File name box). The file type is selected form the Files of type box (values here set with the Filter property). Once selected, the Open button is clicked. Cancel can be clicked to cancel the open operation. The ShowDialog method returns the clicked button. It returns DialogResult.OK if Open is clicked and returns DialogResult.Cancel if Cancel is clicked. The nice thing about this control is that it can validate the file name before it is returned to the application. The FileName property contains the complete path to the selected file.

• Typical use of OpenFileDialog control:

 Set the Name, Filter, and Title properties.
 Use ShowDialog method to display dialog box.
 Read FileName property to determine selected file


Example 4-3

Picture Box Playground

1. Start a new project. In this project, we will use a OpenFileDialog control to select image files. The selected file will be displayed in four different picture box controls (one for each setting of the SizeMode property).

2. Place 4 labels at the top of a form. Place a picture box control under each of the 4 labels. Place two more labels and a button control under these controls. Finally, place the OpenFileDialog control in the ‘tray’ under the form. The form (which will be rather wide) should look like this:




3. Set the properties of the form and each control:

Form1:
Name frmPlayground
Text Picture Box Playground

Label1:
Text Normal:

Label2:
Text CenterImage:


Label3:
Text StretchImage:

Label4:
Text AutoSize:

PictureBox1:
Name picNormal
BackColor White
BorderStyle FixedSingle
SizeMode Normal

PictureBox2:
Name picCenter
BackColor White
BorderStyle FixedSingle
SizeMode CenterImage

PictureBox3:
Name picStretch
BackColor White
BorderStyle FixedSingle
SizeMode StretchImage

PictureBox4:
Name picAuto
BackColor White
BorderStyle FixedSingle
SizeMode AutoSize

Label5:
Text Size:
TextAlign LeftCenter

Label6:
Name lblSize
BackColor White
BorderStyle Fixed3D
Text [Blank]
TextAlign LeftCenter


Button1:
Name btnImage
Text &Select Image

OpenFileDialog1:
Name dlgOpen
Filter Bitmaps (*.bmp)|*.bmp|Icons (*.ico)|*.ico|Metafiles (*.wmf)|*.wmf|JPEG (*.jpg)|*.jpg|GIF (*.gif)|*.gif
[Type this line carefully! – consult on-line help as reference]
Title Open Image File

When done, the form should look like this:




4. Form level scope declarations:

Dim WSave As Integer, HSave As Integer

5. Use this code in the Form Load event to initialize positions and save size:

Private Sub frmPlayground_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
'start form in upper left corner
Me.Left = 0
Me.Top = 0
'save form width/height for initialization
WSave = Me.Width
HSave = Me.Height
End Sub

6. Use this code in the btnImage Click event:

Private Sub btnImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImage.Click
'reset autosize picture box and form to initial size
picAuto.Width = picNormal.Width
picAuto.Height = picNormal.Height
Me.Width = WSave
Me.Height = HSave
'display open dialog box
If dlgOpen.ShowDialog = DialogResult.OK Then
picNormal.Image = Image.FromFile(dlgOpen.FileName)
picCenter.Image = Image.FromFile(dlgOpen.FileName)
picStretch.Image = Image.FromFile(dlgOpen.FileName)
picAuto.Image = Image.FromFile(dlgOpen.FileName)
lblSize.Text = Str(picAuto.Width) + " pixels x" + Str(picAuto.Height) + " pixels"
End If
End Sub

This code reads the selected file and displays it in each of the picture box controls.

7. Save the application (saved in Example 4-3 folder in the LearnVBN\VBN Code\Class 4 folder). Run the application and open different types of image files (we’ve included one of each type in the project folder). Notice how the different SizeMode properties affect the display. Images in the AutoSize mode may be very large requiring resizing of the form.

Legacy Controls

• Visual Basic .NET provides a wealth of useful controls in its toolbox. Compared to previous incarnations of Visual Basic, there are many new, improved tools. Visual Basic .NET has also eliminated some controls that existed in Visual Basic. For the most part, elimination of these legacy controls is a good thing. But there are three controls we wish they had not eliminated.

• In the Picture Box Playground example just developed, every time we want to change the image, it is necessary to bring up the open file dialog box. What would be nice is to have the capability of the dialog box built into the form providing a clickable list of image files. As each file name was clicked, the corresponding image would be displayed in each of the picture boxes. Visual Basic offered three controls that allowed this capability.

• The DriveListBox Control was a dropdown box that allowed selection of drives. The DirListBox Control was a list box allowing folder selection. And, the FileLIstBox control was a list box allowing file selection. Using these three controls on a form allowed a ‘built-in’ replication of the open file dialog box. And, the nice thing about these controls is you could choose as many as you like. For example, if you just wanted to present your user a selection of files in a single directory they could not change, you could just use the FileListBox control. The OpenFileDialog control does not allow such a limitation.

• So, are we just left with our ‘wishing and hoping’ these controls were back? Unfortunately, no. Visual Basic .NET still has some of these legacy controls (as part of the Microsoft.Visual Basic.Compatibility.VB6 namespace), but they must be added to the toolbox. To do this, choose the Tools menu option and select Customize Toolbox. When the dialog box appears, select .NET Framework Components. Place check marks next to: DriveListBox, DirListBox and FileListBox. Click OK and the controls will appear in the toolbox and become available for use (on-line help is available for documentation).

• You may see other legacy controls in the Customize Toolbox dialog box. You can decide if you need any other such controls. Be aware, however, that using legacy controls could be dangerous. Microsoft may decide to drop support for such controls at any time. Our hope is that controls similar to the drive, directory and file list tools are added with the next version of Visual Basic .NET – their utility calls out for their inclusion.


DriveListBox Controls

In Toolbox:



On Form (Default Properties):



• The DriveListBox control allows a user to select a valid disk drive at run-time. It displays the available drives in a drop-down combo box. No code is needed to load a drive list box with valid drives; Visual Basic .NET does this for us. We use the box to get the current drive identification.

• DriveListBox Properties:

Name Gets or sets the name of the drive list box (three letter prefix for drive list box name is drv).
BackColor Get or sets the drive list box background color.
Drive Contains the name of the currently selected drive.
DropDownStyle Gets or sets a value specifying the style of the drive list box.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text.

• DriveListBox Events:

SelectedValueChanged Triggered whenever the user or program changes the drive selection.

• This control is always used in conjunction with the DirListBox and FileListBox controls – we rarely look at the Drive property.

• Typical use of DriveListBox control:

 Set the Name property.
 Use SelectedValueChanged event to update displayed directories.



DirListBox Control

In Toolbox:



On Form (Default Properties):



• The DirListBox control displays an ordered, hierarchical list of the user's disk directories and subdirectories. The directory structure is displayed in a list box. Like, the drive list box, little coding is needed to use the directory list box - Visual Basic .NET does most of the work for us.

• DirListBox Properties:

Name Gets or sets the name of the directory list box (three letter prefix for directory list box name is dir).
BackColor Get or sets the directory list box background color.
BorderStyle Establishes the border for directory list box.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text.
Path Gets or sets the current directory path.

• DirListBox Events:

Change Triggered when the directory selection is changed.

• Typical use of DirListBox control:

 Set the Name property.
 Use Change event to update displayed files.
 Read Path property for current path.


FileListBox Control

In Toolbox:



On Form (Default Properties):



• The FileListBox control locates and lists files in the directory specified by its Path property at run-time. You may select the types of files you want to display in the file list box. You will notice most of its properties are very similar to those of the list box control.

• FileListBox Properties:

Name Gets or sets the name of the file list box (three letter prefix for file list box name is fil).
BackColor Get or sets the file list box background color.
FileName Contains the currently selected file name.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text.
Items Gets the Items object of the file list box.
Path Contains the current path directory.
Pattern Contains a string that determines which files will be displayed. It supports the use of * and ? wildcard characters. For example, using *.dat only displays files with the .dat extension.
SelectedIndex Gets or sets the zero-based index of the currently selected item in a list box.
SelectionMode Gets or sets the method in which items are selected in file list box (allows single or multiple selections).


• FileListBox Events:

SelectedIndexChanged Occurs when the SelectedIndex property has changed.

• If needed, the number of items in the list is provided by the Items.Count property. The individual items in the list are found by examining elements of the Items.Item zero-based array.

• Typical use of FileListBox control:

 Set Name and Pattern properties.
 Monitor SelectedIndexChanged event for individual selections.
 Use Path and FileName properties to form complete path to selected file.



Synchronizing the Drive, Directory, and File List Box Controls

• The drive, directory and file list boxes are controls that can be used independently of each other. As such, there are no common properties or linking mechanisms. When used with each other to obtain a file name, their operation must be synchronized to insure the displayed information is always consistent.

• When the drive selection is changed (drive list box SelectedValueChanged event), you need to update the directory list box path. For example, if the drive list box is named drvExample and the directory list box is dirExample, use the code:

dirExample.Path = drvExample.Drive

• When the directory selection is changed (directory list box Change event), you must update the names displayed in the file list box. With a file list box named filExample, this code is:

filExample.Path = dirExample.Path

• Once all of the selections have been made and you want the file name, you need to form a text string that specifies the complete path to the file. This string concatenates the Path and FileName information from the file list box. This should be an easy task, except for one problem. The problem involves the backslash (\) character. If you are at the root directory of your drive, the path name ends with a backslash. If you are not at the root directory, there is no backslash at the end of the path name and you have to add one before tacking on the file name.


• Example code for concatenating the available information into a proper file name (YourFile):

Dim YourFile As String

If Mid(filExample.Path, Len(filExample.Path), 1) = "\" Then
YourFile = filExample.Path + filExample.FileName
Else
YourFile = filExample.Path + "\" + filExample.FileName
End If

The Mid() statement checks the last character in the Path property to see if it is a backslash. Note we only have to use properties of the file list box. The drive and directory box properties are only used to create changes in the file list box via code.


Example 4-4

Image Viewer

1. Start a new project. In this application, we search our computer's file structure for graphics files and display the results of our search in an picture box control.

2. First, place a group box control on the form. In this group box, place a drive list box, directory list box, file list box, and four label boxes. Make sure you have added the three legacy list box controls to your toolbox using instructions provided earlier. Add a second group box. In that group box, place a picture box control and three radio buttons. The form should look like this:




3. Set properties of the form and each control.

Form1:
Name frmImage
FormBorderStyle FixedSingle
StartPosition CenterScreen
Text Image Viewer

GroupBox1:
Name grpFile
BackColor Red
Text [Blank]

Label1:
Name lblImage
BackColor Yellow
BorderStyle Fixed3D
Text [Blank]
TextAlign MiddleLeft

Label2:
ForeColor Yellow
Text Files:

DriveListBox1:
Name drvImage

Label3:
ForeColor Yellow
Text Directories:

DirLIstBox1:
Name dirImage

Label4:
ForeColor Yellow
Text Drives:

FileListBox1:
Name filImage
Pattern *.bmp;*.ico;*.wmf;*.gif;*jpg
[type this line with no spaces]


GroupBox1:
Name grpImage
BackColor Blue
Text [Blank]

PictureBox1:
Name picImage
BackColor White
BorderStyle FixedSingle

RadioButton1:
Name rdoNormal
ForeColor Yellow
Text Normal

RadioButton2:
Name rdoCenter
ForeColor Yellow
Text Center

RadioButton3:
Name rdoStretch
ForeColor Yellow
Text Stretch


My finished form is this:




4. Use this code in the Form Load procedure (initializes Stretch size mode):

Private Sub frmImage_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'initialize stretch mode
rdoStretch.PerformClick()
End Sub

5. Use this code in the drvImage SelectedValueChanged procedure.

Private Sub drvImage_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drvImage.SelectedValueChanged
'If drive changes, update directory
dirImage.Path = drvImage.Drive
End Sub

When a new drive is selected, this code forces the directory list box to display directories on that drive.


6. Use this code in the dirImage Change procedure.

Private Sub dirImage_Change(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dirImage.Change
'If directory changes, update file path
filImage.Path = dirImage.Path
End Sub

Likewise, when a new directory is chosen, we want to see the files on that directory.

7. Use this code for the filImage SelectedIndexChanged event.

Private Sub filImage_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filImage.SelectedIndexChanged
'Get complete path to file name and open graphics
Dim ImageName As String
If Mid(filImage.Path, Len(filImage.Path), 1) = "\" Then
ImageName = filImage.Path + filImage.FileName
Else
ImageName = filImage.Path + "\" + filImage.FileName
End If
lblImage.Text = ImageName
picImage.Image = Image.FromFile(ImageName)
End Sub

This code forms the file name (ImageName) by concatenating the directory path with the file name. It then displays the complete name and loads the image into the picture box.

8. Lastly, code the three radio button CheckChanged events to change the display size mode:

Private Sub rdoNormal_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdoNormal.CheckedChanged
picImage.SizeMode = PictureBoxSizeMode.Normal
End Sub


Private Sub rdoCenter_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdoCenter.CheckedChanged
picImage.SizeMode = PictureBoxSizeMode.CenterImage
End Sub

Private Sub rdoStretch_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdoStretch.CheckedChanged
picImage.SizeMode = PictureBoxSizeMode.StretchImage
End Sub

9. Save your project (saved in Example 4-4 folder in LearnVBN\VBN Code\Class 4 folder). Run and try the application. Find bitmaps, icons, metafiles, gif files, and JPEGs (an example of each is included in the project folder). Here’s how the form should look when displaying the example JPEG file (a photo from my Mexican vacation):





Class Review

• After completing this class, you should understand:

 The concept of Z Order for a control
 Useful properties, events, methods and typical uses for the numeric updown and domain updown controls
 Properties, events, methods, and uses for the horizontal and vertical scroll bar controls
 The five types of graphics files that can be displayed by the picture box control
 How the picture box SizeMode property affects Image display
 How to load image files at both design time and run time
 How to use the file open common dialog box to obtain file names for opening files
 How the legacy drive, directory, and file list controls work and when they could be used




Practice Problems 4

Problem 4-1. Tic-Tac-Toe Problem. Build a simple Tic-Tac-Toe game. Use ‘skinny’ label controls for the grid and picture box controls for markers (use different pictures to distinguish players). Click the image controls to add the markers. Can you write logic to detect a win?

Problem 4-2. Number Guess Problem. Build a game where the user guesses a number between 1 and 100. Use a scroll bar for entering the guess and change the extreme limits (Minimum and Maximum properties) with each guess to help the user adjust their guess.

Problem 4-3. File Times Problem. Using the drive, directory and file list controls, write an application that lists all files in a directory. For every file, find what time the file was created (use the FileDateTime() function to get time details). Determine the most popular hours of the day for creating files.





Exercise 4

Student Database Input Screen

You did so well with last chapter’s assignment that, now, a school wants you to develop the beginning structure of an input screen for its students. The required input information is:

1. Student Name
2. Student Grade (1 through 6)
3. Student Sex (Male or Female)
4. Student Date of Birth (Month, Day, Year)
5. Student Picture (Assume they can be loaded as jpeg files)

Set up the screen so that only the Name needs to be typed; all other inputs should be set with option buttons, scroll bars, and common dialog boxes. When a screen of information is complete, display the summarized profile in a message box. This profile message box should resemble this:



Note the student’s age must be computed from the input birth date - watch out for pitfalls in doing the computation. The student’s picture does not appear in the profile, only on the input screen.

Tidak ada komentar:

Posting Komentar