Appendix G. Windows Forms Controls and Components

This appendix describes the standard controls and components provided by Visual Basic.NET. Some of these are quite complicated, providing dozens or even hundreds of properties, methods, and events, so it would be impractical to describe them all completely here. However, it's still worthwhile having a concise guide to the most important properties, methods, and events provided by the Windows Forms controls.

The sections in this appendix describe the components' general purposes and give examples of what I believe to be their simplest, most common, and most helpful usages. The idea is to help you decide which components to use for which purposes, and to give you some idea about the components' most commonly used properties, methods, and events. To learn more about a particular component, see the online help.

You can also learn more by studying this appendix's example programs, which are available for download on the book's web site.

Note that all of these components inherit from the Component class, and the controls inherit from the Control class. Except where overridden, the components and controls inherit the properties, methods, and events defined by the Component and Control classes. Chapter 9, "Using Windows Forms Controls," discusses some of the more useful properties, methods, and events provided by the Control class, and many of those apply to these controls as well. Appendix A, "Useful Control Properties, Methods, and Events," summarizes the Control class's most useful properties.

Figure G-1 shows the Visual Basic Toolbox displaying the standard Windows Forms controls.

The following table lists the components shown in Figure G-1 in the same order in which they appear in the figure. Read the table by rows. For example, the first several entries (Pointer, BackgroundWorker, BindingNavigator, BindingSource, Button, and so on) correspond to the first controls in the first row in Figure G-1.

Visual Basic provides a large number of standard components and controls for Windows Forms.

Figure G.1. Visual Basic provides a large number of standard components and controls for Windows Forms.

Pointer

BackgroundWorker

BindingNavigator

BindingSource

Button

CheckBox

CheckedListBox

ColorDialog

ComboBox

ContextMenuStrip

DataGridView

DataSet

DateTimePicker

DirectoryEntry

DirectorySearcher

DomainUpDown

ErrorProvider

EventLog

FileSystemWatcher

FlowLayoutPanel

FolderBrowserDialog

FontDialog

GroupBox

HelpProvider

HScrollBar

ImageList

Label

LinkLabel

ListBox

ListView

MaskedTextBox

MenuStrip

MessageQueue

MonthCalendar

NotifyIcon

NumericUpDown

OpenFileDialog

PageSetupDialog

Panel

PerformanceCounter

PictureBox

PrintDialog

PrintDocument

PrintPreviewControl

PrintPreviewDialog

Process

ProgressBar

PropertyGrid

RadioButton

 

RichTextBox

SaveFileDialog

SerialPort

ServiceController

SplitContainer

Splitter

StatusStrip

TabControl

TableLayoutPanel

TextBox

Timer

ToolStrip

ToolStripContainer

ToolTip

TrackBar

TreeView

VScrollBar

WebBrowser

COMPONENTS' PURPOSES

By default, the Toolbox provides several tabs that group related components together. With such a large number of components at your fingertips, having categorized tabs sometimes makes finding a particular tool easier. Each tab also contains a Pointer tool.

The following table lists the tools in various Toolbox tabs. You can use this table to help decide which tool to use for a particular purpose.

COMMON CONTROLS

   

Button

CheckBox

CheckedListBox

ComboBox

DateTimePicker

Label

LinkLabel

ListBox

ListView

MaskedTextBox

MonthCalendar

NotifyIcon

NumericUpDown

PictureBox

ProgressBar

RadioButton

RichTextBox

TextBox

ToolTip

TreeView

WebBrowser

   

Containers

   

FlowLayoutPanel

GroupBox

Panel

SplitContainer

TabControl

TableLayoutPanel

  

Menus and Toolbars

   

ContextMenuStrip

MenuStrip

StatusStrip

ToolStrip

ToolStripContainer

   

Data

   

DataSet

DataGridView

BindingSource

BindingNavigator

Components

   

BackgroundWorker

DirectoryEntry

DirectorySearcher

ErrorProvider

EventLog

FileSystemWatcher

HelpProvider

ImageList

MessageQueue

PerformanceCounter

Process

SerialPort

ServiceController

Timer

  

Printing

   

PageSetupDialog

PrintDialog

PrintDocument

PrintPreviewControl

PrintPreviewDialog

   

Dialogs

   

ColorDialog

FolderBrowserDialog

FontDialog

OpenFileDialog

SaveFileDialog

   

WPF Interoperability

   

ElementHost

   

Reporting

   

MicrosoftReportViewer

CrystalReportViewer

CrystalReportDocument

 

Visual Basic Power Packs

   

PrintForm

   

One other section, General, is initially empty.

The following sections describe the tools shown in Figure G-1. Except for the generic pointer tool, all tools are presented in alphabetical order.

POINTER

Each of the Toolbox's sections begins with an arrow in its upper-left corner. This is the only tool shown in Figure G-1 that does not represent a type of control or component. Selecting the pointer deselects any other currently selected tool. You can then click the controls on the form to select them without creating a new control.

BACKGROUNDWORKER

The BackgroundWorker component simplifies multi-threading. When a program invokes its RunWorkerAsync method, the component starts running on a new thread. It raises its DoWork method on the new thread, and the corresponding event handler should perform the necessary work. While it runs, the worker can call the component's ReportProgress method to raise a ProgressChanged event on the main thread to let the program know how it is progressing.

When the worker thread finishes, the component receives a RunWorkerCompleted event on the main thread.

The UseBackgroundWorker example program, which is available for download on the book's web site, demonstrates the BackgroundWorker component. It allows the user to start a BackgroundWorker that simulates a long task. The program displays the worker's progress and lets the user cancel the task, stopping the worker before it finishes.

BINDINGNAVIGATOR

A BindingNavigator provides a user interface so the user can control a data source. It initially appears as a toolbar docked to the top of the form, although you can move it if you like. It contains navigation buttons that move to the beginning, previous record, next record, and end of the data source. It also contains a text box where you can enter a record number to jump to, a label showing the current record number, and buttons to add and delete records.

See Chapter 20, "Database Controls and Objects," for more information on BindingNavigator and other database controls.

BINDINGSOURCE

A BindingSource provides control of bound data on a form. It provides programmatic methods for navigating through the data, adding items, deleting items, and otherwise managing the data at the code level.

Typically you attach the BindingSource to a data source. You then bind controls to the BindingSource. When the BindingSource changes its position in the data source, it automatically updates the bound controls. If you attach a BindingNavigator to the BindingSource, the user can use the BindingNavigator to control the BindingSource.

See Chapter 20 for more information on BindingNavigator and other database controls.

BUTTON

The Button control is a simple push button. You can use it to let the user tell the program to do something.

A Button can display a textual caption, a picture, or both. Use the ImageAlign and TextAlign properties to determine where the caption and picture appear on the Button.

When the user clicks the Button, it raises its Click event. The program can take the appropriate action in the Button control's Click event handler, as shown in the following code:

Private Sub btnValidatePhoneNumber_Click(ByVal sender As System.Object,
 ByVal e As System.EventArgs) Handles btnValidatePhoneNumber.Click
    ValidatePhoneNumber(txtPhoneNumber.Text)
End Sub

Note that most button Click event handlers are assigned to a single button so they don't need to use their sender and e parameters. In that case, you can use relaxed delegates to omit the parameters completely, significantly simplifying the event handler as shown in the following code:

Private Sub btnValidatePhoneNumber_Click() Handles btnValidatePhoneNumber.Click
    ValidatePhoneNumber(txtPhoneNumber.Text)
End Sub

For more information on relaxed delegates, see the section "Relaxed Delegates" in Chapter 17, "Subroutines and Functions."

You can use the control's ImageList and ImageIndex properties to assign an image to the Button.

If you set a form's AcceptButton property to a Button, the Button control's Click event handler runs when the user presses the Enter key while the form has focus. Similarly, if you set a form's CancelButton property to a Button, the Button control's Click event handler runs when the user presses the Escape key while the form has focus.

CHECKBOX

A CheckBox displays a box that enables the user to select or clear an option.

A CheckBox can display a textual caption, a picture, or both. Use the ImageAlign and TextAlign properties to determine where the caption and picture appear in the CheckBox.

You can also use the control's ImageList and ImageIndex properties to assign an image to the CheckBox.

Use the control's CheckAlign property to determine where the check box appears. Normally the box appears on the left, but you can make it appear on the right, center, upper-left corner, and so forth.

Usually a program uses the CheckBox control's Checked property to tell if it is checked. This property returns True if the CheckBox is checked and False if it is not. Your program can also set this property to True or False to check or uncheck the control.

Although a CheckBox usually is either checked or not, this control also has a third indeterminate state. This state is represented as a grayed-out check in the box. Some applications use this state to represent a partial or unknown selection.

If you want to allow the user to cycle through the three values (checked, indeterminate, and unchecked), set the control's ThreeState property to True.

Most programs use CheckBoxes to gather information and only process the information when the user clicks a button or selects a menu item, so they don't need to process any CheckBox events. The control does provide a CheckedChanged event, however, that fires whenever the control's value changes, either because the user clicked it or because your program's code changed the value. For example, the program could hide and display extra information that only applies when the box is checked, as shown in the following code:

Private Sub chkExtraInfo_CheckedChanged() Handles chkExtraInfo.CheckedChanged
    grpExtraInfo.Visible = chkExtraInfo.Checked
End Sub

CHECKEDLISTBOX

A CheckedListBox control displays a series of items with check boxes in a list format. This enables the user to pick and choose similar items from a list of choices. You can also use a ListBox to allow the user to select items in a list, but there are some important differences between the two controls' behaviors.

First, in a CheckedListBox, previously checked items remain checked when the user clicks another item. If the user clicks an item in a ListBox, the control deselects any previously selected items. Though you can use the Shift and Ctrl keys to modify this behavior, making complex selections can be tricky.

Second, the user must click each CheckedListBox item individually to select it. You can make a ListBox allow simple or extended selections. That means, for example, the user could Shift+click to select all of the items in a range. If the user is likely to want that type of selection, consider using a ListBox instead of a CheckedListBox.

If a CheckedListBox isn't big enough to display all of its items at once, it displays a vertical scroll bar to let the user see all the items. If some of the items are too wide to fit, set the control's HorizontalScrollBar property to True to display a horizontal scroll bar.

If you set the MultiColumn property to True, the control displays items in multiple columns.

By default, the user must click an item and then click its box to check the item. To allow the user to select an item with a single click, set the control's CheckOnClick property to True. This usually makes selection easier.

If the control's IntegralHeight property is True, the control will not display a partial item. For example, if the control is tall enough to display 10.7 items, it will make itself slightly shorter so that it can only display 10 items.

Set the control's Sorted property to True to make the control display its items in sorted order.

Use the control's Items.Add method to add an item to the list. This method has three overloaded versions. All three take a generic Object as the first parameter. The control uses this object's ToString method to generate the text that it displays to the user. The first overloaded version takes no extra parameters. The second version takes a Boolean parameter indicating whether the new item should be checked. The last version takes a parameter that indicates whether the new item should be checked, unchecked, or indeterminate.

For example, suppose that a program defines the following Employee class. The important part here is the ToString method, which tells the CheckedListBox how to display an Employee object, as shown in the following code:

Public Class Employee
    Public FirstName As String
    Public LastName As String

    Public Sub New(ByVal first_name As String, ByVal last_name As String)
        FirstName = first_name
        LastName = last_name
    End Sub

    Public Overrides Function ToString() As String
        Return FirstName & " " & LastName
    End Function
End Class
                                                  
CHECKEDLISTBOX

The CheckedListBox item's CheckedItems property returns a collection containing the objects that are checked, including those that are in the indeterminate state. The control's CheckedIndices property returns a collection of integers representing the items that are selected or indeterminate (numbered starting with zero).

COLORDIALOG

The ColorDialog component displays a dialog that enables the user to select a color from a standard palette or from a custom color palette. A program calls its ShowDialog method to display a color selection dialog. ShowDialog returns DialogResult.OK if the user selects a color and clicks OK. It returns DialogResult.Cancel if the user cancels.

The following code sets the dialog box's Color property to the btnPickColor control's current background color. It displays the dialog box and, if the user clicks OK, it sets the btnPickColor control's background color to the user's selection.

Private Sub btnPickColor_Click() Handles btnPickColor.Click
    dlgColor.Color = btnPickColor.BackColor
    If dlgColor.ShowDialog() = DialogResult.OK Then
        btnPickColor.BackColor = dlgColor.Color
    End If
End Sub
                                                  
COLORDIALOG

The dialog box provides an area on the right where the user can define custom colors. Set the component's AllowFullOpen property to True to allow the user to access this area. Set the FullOpen property to True to make the dialog appear with this area already open (otherwise the user must click the Define Custom Colors button to show this area).

If you set the SolidColorOnly property to True, the dialog box only allows the user to select solid colors. This applies only to systems using 256 or fewer colors, where some colors are dithered combinations of other colors. All colors are solid on systems using more than 256 colors.

The component's CustomColors property is an array of integers that determine the colors that the dialog displays in its custom colors area. These color values are a combination of red, green, and blue values between 0 and 255. In hexadecimal, the form of a value is BBGGRR, where BB is the blue component, GG is the green component, and RR is the red component.

For example, the color &HFF8000 has a blue component of &HFF = 255, a green component of &H80 = 128, and a red component of 0. This color is light blue. Unfortunately, the Color object's ToArgb method returns the color in the reversed format RRGGBB, so you cannot use that method to calculate these values. Instead, you need to calculate them yourself.

Example program UseColorDialog demonstrates a simple color dialog. Example program CustomColorDialog displays a dialog initialized with a custom color palette. Both of these programs are available for download on the book's web site.

COMBOBOX

The ComboBox control contains a text box where the user can enter a value. It also provides a list box or drop-down list where the user can select a value. How the text box, list box, and drop-down list work depends on the control's DropDownStyle property. Figure G-2 shows the three styles.

When DropDownStyle is Simple, the ComboBox displays a text box and a list, as shown on the left in Figure G-2. The user can type a value in the text box, or select one from the list. The user can enter any text in the text box, even if it does not appear in the list.

The ComboBox provides three diff erent styles: Simple, DropDown, and DropDownList.

Figure G.2. The ComboBox provides three diff erent styles: Simple, DropDown, and DropDownList.

When DropDownStyle is DropDown, the ComboBox displays a text box and a drop-down list, as shown in the middle in Figure G-2. The user can type a value in the text box. If the user clicks the drop-down arrow to the right of the text box, the control displays the list where the user can select an item. The user can enter any text in the text box, even if it does not appear in the list. In Figure G-2, the middle ComboBox control's text box contains the value Persimmon, which does not appear in the list.

When DropDownStyle is DropDownList, the ComboBox displays a non-editable text box and a drop-down list. If the user clicks the control, the ComboBox displays a drop-down list exactly as it does when DropDownStyle is DropDown. The difference is that the user must select an item from the list. If the user sets focus to the control and types a letter, the control selects the next item in the list that begins with that letter. If the user presses the same letter again, the control moves to the next choice beginning with that letter.

Setting DropDownStyle to DropDownList restricts the user's choices the most and allows the least room for error. So, if you know all of the user's choices, you should use the DropDownList style. If you must allow the user to enter new values, you should use one of the other styles. The DropDown style takes less room on the form and is more familiar to most users, so that is often the better choice.

The control's DropDownWidth property determines how wide the drop-down list should be.

The ComboBox control's MaxDropDownItems property determines how many items the control displays in its drop-down list. For example, if you set this to 10 and the list contains more than 10 items, the drop-down list displays a scroll bar to let the user find the additional items.

The MaxLength property lets you specify the maximum number of characters the user can type into the control's text box. Note, however, that the control will display a longer value if the user selects it from the control's list box or drop-down list. Set MaxLength to 0 to allow entries of any length.

If you set the control's Sorted property to True, the ComboBox lists its choices in sorted order.

The ComboBox control's Text property gets or sets the value displayed by the control's text box. If the control's DropDownStyle is DropDownList, this property does nothing at design time and the program can only set it to values that are in the control's list of allowed values at runtime. Many programs use this property to see what value is selected in the control.

Like the CheckedListBox described earlier in this appendix, the items in a ComboBox can be any type of object and the control uses the objects' ToString methods to figure out what text to display to the user. As is the case with the CheckedListBox, you can use the ComboBox control's Items.Add method to add new objects to the control. See the "CheckedListBox" section earlier in this appendix for more information and an example Employee class that will also work with ComboBox controls.

If an item is selected, the ComboBox control's SelectedItem property returns the item's object. If no item is selected, this property returns Nothing.

If an item is selected, the ComboBox control's SelectedIndex property returns the item's index, numbered starting with zero. If no item is selected, this property returns āˆ’1.

Note that the SelectedItem and SelectedIndex properties return Nothing and āˆ’1, respectively, if the user types a new value into the text area, even if the user types a value that appears in the control's item list. If you want the user to select an item rather than typing some text, you should set the control's DropDownStyle property to DropDownList.

CONTEXTMENUSTRIP

The ContextMenuStrip component represents a context menu. When you select it on the form at design time, the development environment displays the menu at the top of the form. Enter the menu's items, use the Property window to set their names and other properties, and double-click the items to edit their event handlers. See the section "MenuStrip" later in this appendix for information on menu item properties and events.

To use a ContextMenuStrip, you need to attach it to a control. Use the Properties window to set the control's ContextMenuStrip property to your ContextMenuStrip component. The rest is automatic. When the user right-clicks this control at runtime, Visual Basic automatically displays the ContextMenuStrip. If the user selects one of the menu's items, Visual Basic triggers the menu item's event handler.

DATAGRIDVIEW

The DataGridView control displays a table-like grid display. The control's underlying data can come from a data source such as a DataSet or BindingSource, or the program can add rows and columns directly to the control. The DataGridView provides many properties for customizing the grid's appearance. For example, it lets you change column header styles and cell border styles, determine whether rows and columns are resizable, and determine whether the control displays tooltips and errors in data cells.

Visual Basic can automatically create a DataGridView bound to a BindingSource and associated with a BindingNavigator. To do this, create a data source and drag a table from the Data Sources window onto a form. For more information on this technique, or for information on using the control in general, see Chapter 20.

DATASET

The DataSet component holds data in a relational format. It provides all the features you need to build, load, store, manipulate, and save data similar to that stored in a relational database. It can hold multiple tables related with complex parent/child relationships and uniqueness constraints. It provides methods for merging DataSets, searching for records that satisfy criteria, and saving data in different ways (such as into a relational database or an XML file).

One of the most common ways to use a DataSet is to load it from a relational database when the program starts, use various controls to display the data and let the user manipulate it interactively, and then save the changes back into the database when the program ends.

For more information on the DataSet component, see the online help (msdn.microsoft.com/system.data.dataset.aspx) and Chapter 20.

DATETIMEPICKER

The DateTimePicker control allows the user to select a date and time. The control can display one of several styles, depending on its property values.

If the ShowUpDown property is True, the control displays small up and down arrows on its right, as shown at the top of Figure G-3. Click a date field (month, date, year) to select it, and use the up and down arrow buttons to adjust that field.

If ShowUpDown is False (the default), the control displays a drop-down arrow on its right, as shown in the second DateTimePicker in Figure G-3. If you click this arrow, the control displays the calendar shown under the control in Figure G-3. The right and left arrows at the top of the calendar let you move through months. If you click the calendar's month, the control displays a pop-up menu listing the months so that you can quickly select one. If you click the year, the control displays small up and down arrows that you can use to change the year. When you have found the month and year you want, click a date to select it and close the calendar.

The DateTimePicker control lets the user select a date and time.

Figure G.3. The DateTimePicker control lets the user select a date and time.

If you get lost while scrolling through the calendar's months, you can click the Today entry at the bottom of the calendar to jump back to the current date. You can also right-click the calendar and select the "Go to today" command.

Whether ShowUpDown is True or False, you can click a date field (month, date, year) and then use the up and down arrow keys to adjust the field's value. You can also type a new value into numeric fields (such as the date and year).

The control's Format property determines the way in which the control displays dates and times. This property can take the values Long, Short, Time, and Custom. The results depend on the regional settings on the computer. The following table shows typical results for the Long, Short, and Time settings in the United States.

FORMAT PROPERTY

EXAMPLE

Long

Saturday, February 20, 2010

Short

2/20/2010

Time

3:12:45 PM

When the Format property is set to Custom, the control uses the date and time format string stored in the control's CustomFormat property. For example, the DateTimePicker on the bottom in Figure G-3 has CustomFormat set to h:mm tt, MMM d, yyyy to display the time, abbreviated month, date, and year. See Appendix P, "Date and Time Format Specifiers," for more information.

If the control displays time (either because Format is set to Time or because a CustomFormat value includes time fields), the user can click a time field and use the arrow keys to adjust its value. You can also click a numeric field or AM/PM designator and type a new value.

The DateTimePicker control's MinDate and MaxDate properties determine the first and last dates that the control will let the user select.

The control has several properties that determine the appearance of the calendar, if it displays one. These include CalendarFont, CalendarForeColor, CalendarMonthBackground, CalendarTitleBackColor, CalendarTitleForeColor, and CalendarTrailingForeColor.

The program can use the control's Value property to get or set the control's date and time.

DIRECTORYENTRY

The DirectoryEntry component represents a node or object in an Active Directory hierarchy. Active Directory is a service that provides a common, hierarchical view of distributed resources and services on a network.

Active Directory is really a Windows operating system topic, not a Visual Basic topic, so it is not covered further here. For more information, see the DirectoryEntry class's web page at msdn.microsoft.com/system.directoryservices.directoryentry.aspx.

DIRECTORYSEARCHER

The DirectorySearcher component performs searches on an Active Directory hierarchy. See the online help for more information on Active Directory (msdn.microsoft.com/aa286486.aspx) and the DirectorySearcher component (msdn.microsoft.com/system.directoryservices.directorysearcher.aspx).

DOMAINUPDOWN

The DomainUpDown control displays a list of items that the user can select by clicking the up and down arrow buttons beside the control. For example, the control might let the user select one of the values High, Medium, and Low.

If the control's InterceptArrowKeys property is True, the user can also scroll through the items by using the up and down arrow keys. If InterceptArrowKeys is False, the user must click the arrow buttons to change the value.

Normally, the control's ReadOnly property is set to False so the user can type text into the control's text area much as you can enter text in a ComboBox. If ReadOnly is True, the user cannot type in this area and must use the arrow keys or buttons to pick one of the control's items. Unfortunately, setting ReadOnly to True gives the control a gray background, so it appears disabled unless you look closely and notice that the text is black rather than dark gray.

Like the CheckedListBox control, the DomainUpDown control can hold arbitrary objects as items. It displays the string returned by an object's ToString method. See the "CheckedListBox" section earlier in this appendix for more information about displaying objects in the control.

The control's SelectedItem property returns the object representing the item that is currently selected. Note that there may be no item selected if the user typed a value in the text area, rather than selecting a value from the list of items. The SelectedIndex property returns the index of the currently selected item or āˆ’1 if no choice is selected.

The control's Text property returns the text that the control is currently displaying. This property returns something meaningful whether the user typed a value or selected an item from the list.

When the control is first displayed, no item is selected. You can use the Properties window to give the control a Text value at design time, but you cannot make it select an item, even if the Text value matches an item's text. If you want the control to begin with an item selected, you can use code similar to the following in the form's Load event handler:

' Select the first Priority value.
dudPriority.SelectedIndex = 0

If you set the control's Sorted property to True, the control displays its items in sorted order.

If you set the Wrap property to True, the control wraps its list of items around if the user moves past the beginning or end of the list.

ERRORPROVIDER

The ErrorProvider component indicates to the user that another control has an error associated with it. ErrorProvider is an extender provider, so it adds a new Error property to the other controls on its form. For example, if the ErrorProvider is named ErrorProvider1, each control on the form gets a new property named "Error on ErrorProvider1." At design time, use the Properties window to set or clear this value.

To associate an error with a control at runtime, use the ErrorProvider's SetError method. The ErrorProvider automatically displays a red circle containing an exclamation mark next to the control. If the user hovers the mouse over the circle, the ErrorProvider displays a tooltip giving the error text.

To remove an error on a control at runtime, use the ErrorProvider's SetError method to set the control's error message to an empty string.

Many programs set or clear errors on a control in the control's Validating event. Example program UseErrorProvider, which is available for download on the book's web site, uses a Validating event to validate a ZIP code text box.

The component's BlinkRate property determines how quickly the error icon blinks. The BlinkStyle property determines how it blinks.

If BlinkStyle is BlinkIfDifferentError, the component makes the icon blink several times whenever the program sets a control's error message to a new nonblank value.

If BlinkStyle is AlwaysBlink, the component makes the icon blink as long as the control has an associated error. The icon continues blinking, even if another application has the focus, until the user fixes the error and moves to a new field to trigger the Validating event handler again.

If BlinkStyle is NeverBlink, the component displays the error icon without blinking.

The component's Icon property gives the icon that the component displays for an error. You can change this icon if you want to use a special error image.

EVENTLOG

The EventLog component enables an application to manipulate event logs. It provides methods to create logs, write and read log messages, and clear logs. Event logs are a more advanced topic. For detailed information, see the MSDN topic "Logging Application, Server, and Security Events" at msdn.microsoft.com/e6t4tk09.aspx.

FILESYSTEMWATCHER

The FileSystemWatcher component keeps an eye on part of the file system and raises events to let your program know if something changes. For example, it can notify your program if a file is created in a particular directory.

For more information on the FileSystemWatcher component, see Chapter 37, "File-System Objects," and Appendix U, "File-System Classes."

FLOWLAYOUTPANEL

The FlowLayoutPanel control displays the controls that it contains in rows or columns. For example, when laying out rows, it places controls next to each other horizontally in a row until it runs out of room, and then it starts a new row.

The FlowLayoutPanel is particularly useful for Toolboxes and in situations where the goal is to display as many of the contained controls as possible at one time, and the exact arrangement of the controls isn't too important.

The control's FlowDirection property determines the manner in which the control arranges its contained controls. This property can take the values LeftToRight, RightToLeft, TopDown, and BottomUp. Example program FlowDirections, which is available for download on the book's web site, demonstrates these different arrangements.

The control's AutoScroll property determines whether the control automatically provides scroll bars if its contents won't fit within the control all at once.

The Padding property determines how much space the control leaves between its edges and the controls that it contains. Use the Margin properties of the contained controls to specify the spacing between the controls.

The TableLayoutPanel control also arranges its contained controls, but in a grid. For information on that control, see the section "TableLayoutPanel" later in this appendix.

FOLDERBROWSERDIALOG

The FolderBrowserDialog component displays a dialog box that lets the user select a folder (directory) in the file system. The program displays the dialog box by calling the component's ShowDialog method.

The component's SelectedPath property not only returns the path selected by the user, but it also determines where the dialog begins browsing. If your code uses the dialog box, does not change this value, and then uses the dialog box again later, the dialog box starts the second time where it left off the first time.

The program can also explicitly set the SelectedPath value to start browsing at a particular folder. For example, the following code makes the dialog begin browsing in the C:Temp directory:

dlgFolder.SelectedPath = "C:Temp"

Alternatively, you can use the component's RootFolder property to make the component start in one of the system folders. Set this property to one of the Environment.SpecialFolder values. For example, to start browsing in the MyPictures directory, set RootFolder to Environment.SpecialFolder.MyPictures.

The dialog box will not allow the user to leave the root folder. For example, if you set the RootFolder property to Environment.SpecialFolder.ProgramFiles, the user will be able to browse through the Program Files hierarchy (normally, C:Program Files), but will not be able to move to other parts of the system.

If you want to start browsing at a particular directory but want to allow the user to move to other parts of the directory hierarchy, leave the RootFolder with its default value of Environment.SpecialFolder.Desktop and then set the SelectedPath property appropriately. For example, the following code uses the Environment object's SpecialFolder method to make the browser start browsing at the Program Files folder:

dlgFolder.RootFolder = Environment.SpecialFolder.Desktop
dlgFolder.SelectedPath =
    Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)

FONTDIALOG

The FontDialog component displays a font selection dialog. If the user selects a font and clicks OK, the ShowDialog method returns DialogResult.OK.

The component has several properties that determine the options that the dialog displays and the types of fonts it will allow the user to select. The following table describes some of the most important of the component's properties.

PROPERTY

PURPOSE

AllowScriptChange

Determines whether the component allows the user to change the character set shown in the Script combo box. If this is False, the dropdown is still visible, but it only contains one choice.

AllowSimulations

Determines whether the component allows graphics device font simulations. For example, many fonts do not include bold or italics, but the graphics device interface (GDI) can simulate them.

AllowVectorFonts

Determines whether the component allows vector fonts. (Characters in a raster font are drawn as bitmaps. Characters in a vector font are drawn as a series of lines and curves. Vector fonts may provide a nicer look because they scale more easily than raster fonts, but vector fonts may take longer to draw.)

AllowVerticalFonts

Determines whether the component allows vertical fonts (such as Chinese).

Color

Sets or gets the font's color. Note that this is not part of the Font property, so if you want to let the user set a control's font and color, you must handle them separately, as shown in the following code:

dlgFont.Font = Me.Font

dlgFont.Color = Me.ForeColor

dlgFont.ShowColor = True

If dlgFont.ShowDialog() = DialogResult.OK Then

     Me.Font = dlgFont.Font
     Me.ForeColor = dlgFont.Color

End If

FixedPitchOnly

Determines whether the dialog box only allows fixed-pitch (fixed-width) fonts. (In a fixed-width font, all characters have the same width. For example, this sentence is in the Courier font, which is fixed-width. In a variable-width font, some characters such as l and i are thinner than other characters such as W. This sentence is in the Times New Roman font, which has variable width.

Font

Sets or gets the font described by the dialog box.

FontMustExist

Determines whether the component raises an error if the user tries to select a font that doesn't exist.

MaxSize

Determines the maximum allowed point size.

MinSize

Determines the minimum allowed point size.

ShowApply

Determines whether the dialog box displays the Apply button. If you set this to True, you should catch the component's Apply event and apply the currently selected font.

ShowColor

Determines whether the component allows the user to select a color.

ShowEffects

Determines whether the component displays the Effects group box that includes the Strikeout and Underline boxes and the Color dropdown.

ShowHelp

Determines whether the dialog box displays the Help button. If you set this to True, you should catch the component's HelpRequest event. The event handler might explain to the user how the font will be used. For example, "Select the font to be used for item descriptions."

Example program UseFontDialog demonstrates a simple font selection dialog. Example program UseFontDialogWithShowEffects shows how to respond when the user clicks the font dialog's Apply button. Both of these examples are available for download on the book's web site.

GROUPBOX

The GroupBox control displays a caption and a border. This control is mostly for decoration and provides a visually appealing method for grouping related controls on the form.

The GroupBox is also a control container, so you can place other controls inside it. If a GroupBox contains RadioButton controls, those buttons form a group separate from any other RadioButton controls on the form. If you click one of those buttons, the other buttons in the GroupBox deselect, but any selected RadioButton controls outside of the GroupBox remain unchanged. This is important if you need to create more than one group of RadioButton controls.

If you want to create multiple RadioButton groups, but you don't want to display a caption and border, use a Panel control instead of a GroupBox.

The GroupBox control provides a typical assortment of properties that determine its appearance (such as BackColor, BackgroundImage, and Font). These properties are straightforward.

If you set the control's Enabled property to False, its caption is grayed out and any controls it contains are also disabled. This is a convenient way for a program to enable or disable a group of controls all at once.

The GroupBox control's Controls property returns a collection containing references to the controls inside the GroupBox.

One of the few confusing aspects to working with GroupBox controls in code is figuring out where to position controls within the GroupBox. The control's borders and caption take up room inside the control's client area, so deciding how to position controls without covering those decorations is not obvious. Fortunately, the control's DisplayRectangle property returns a Rectangle object that you can use to position items. This rectangle fills most of the control's area that isn't occupied by the caption and borders.

HELPPROVIDER

The HelpProvider component displays help for other controls. You can associate a HelpProvider with a control. Then, if the user sets focus to the control and presses the F1 key, the HelpProvider displays help for the control. The HelpProvider either displays a small tooltip-like pop-up displaying a help string, or it opens a help file.

To assign a help string to a control at design time, open the form in the form designer and select the control. In the Properties window, look for a property named "HelpString on HelpProvider1," where HelpProvider1 is the name of your HelpProvider component. If the form contains more than one HelpProvider, the control should have more than one "HelpString on" property.

Enter the text you want the HelpProvider to display in this property and you're finished. When the user sets focus to the control and presses F1, the HelpProvider displays the string automatically.

To set the help string programmatically, call the HelpProvider component's SetHelpString method passing it the control and the help string that it should display for the control.

To provide help using a help file, set the HelpProvider component's HelpNamespace property to the full name and path to the help file. Set the other control's "HelpNavigator on HelpProvider1" property to one of the values shown in the following table to tell the HelpProvider how to use the help file when the user asks for help on this control.

HELPNAVIGATOR VALUE

PURPOSE

AssociateIndex

Opens the help file's Index page and goes to the first entry that begins with the same letter as the control's "HelpKeyword on HelpProvider1" property.

Find

Opens the help file's Index tab.

Index

Opens the help file's Index tab and searches for the value entered in the control's "HelpKeyword on HelpProvider1" property.

KeywordIndex

Opens the help file's Index tab and searches for the value entered in the control's "HelpKeyword on HelpProvider1" property.

TableOfContents

Opens the help file's Table of Contents tab.

Topic

Displays the topic in the help file that has URL stored in the control's "HelpKeyword on HelpProvider1" property. For example, the URL street_name.htm might contain the help file's page for the Street field.

To set a control's HelpNavigator value in code, call the HelpProvider component's SetHelpNavigator method passing it the control and the navigator method that you want to use.

A control's "ShowHelp on HelpProvider1" property indicates whether the control should use the HelpProvider to display its help.

HSCROLLBAR

The HScrollBar control represents a horizontal scroll bar. The user can drag the scroll bar's "thumb" to select a number.

The control's Value property gets and sets its current numeric value. The Minimum and Maximum properties determine the range of values that the control can display. These are integer values, so the HScrollBar control is not ideal for letting the user select a nonintegral value such as 1.25. (You can multiply the values by 100 to get finer grained resolution but the user still can't select truly nonintegral values.)

The control's SmallChange property determines how much the control's Value property changes when the user clicks the arrows at the scroll bar's ends. The LargeChange property determines how much the Value changes when the user clicks the scroll bar between the thumb and the arrows.

Strangely, the control does not let the user actually select the value given by its Maximum property. The program can select that value using code, but the largest value the user can select is Maximum - LargeChange + 1. For example, if Maximum is 100 and LargeChange is 10 (the default values), the user can select values up to 100 āˆ’ 10 + 1 = 91.

If you set the control's TabStop property to True, the control can hold the input focus. While the control has the focus, you can use the arrow keys to change its value by the SmallChange amount.

The control's Scroll event fires when the user changes the control's value interactively. The ValueChanged event occurs when the control's value changes either because the user changed it interactively, or because the program changed it with code. The following code shows how a program can display the hbarDays control's Value property when the user or program changes it:

Private Sub hbarDays_ValueChanged() Handles hbarDays.ValueChanged
    lblDays.Text = hbarDays.Value.ToString
End Sub

Note that many controls that might otherwise require scroll bars can provide their own. For example, the ListBox, TextBox, and Panel controls can display their own scroll bars when necessary, so you don't need to add your own.

IMAGELIST

The ImageList component stores a series of images for use by other controls or by the program's code. For example, one way to display an image on a Button control is to create an ImageList component holding the image. Set the Button's ImageList property to the ImageList component and set its ImageIndex property to the index of the image in the ImageList.

To add images to the component at design time, open the form designer, select the component, click the Images property in the Properties window, and click the ellipsis (...) on the right. The Image Collection Editor that appears has buttons that let you add, remove, and rearrange the images.

The ImageList component's ImageSize property determines the size of the images. The component stretches any images of different sizes to fit the ImageSize. This means that a single ImageList component cannot provide images of different sizes. If you must store images of different sizes in the application, use another method such as multiple ImageList components, PictureBox controls (possibly with the Visible property set to False), or resources.

LABEL

The Label control displays some read-only text. Note that you cannot even select the text at runtime so, for example, you cannot copy it to the clipboard. If you want to allow the user to select and copy text, but not modify it, use a TextBox with the ReadOnly property set to True.

The Label control can display an image in addition to text. To display an image, either set the control's Image property to the image or set the control's ImageList and ImageIndex properties. Use the ImageAlign and TextAlign properties to determine where the image and text are positioned within the control.

If you set the Label control's AutoSize property to True (the default), the control resizes itself to fit its text. This can be particularly useful for controls that contain text that changes at runtime because it ensures that the control is always big enough to hold the text. Note that the control does not automatically make itself big enough to display any image it contains.

The Label control automatically breaks lines that contain embedded carriage returns. The following code makes a label display text on four lines:

lblInstructions.Text = "Print this message and either:" & vbCrLf &
    "    - Mail it to the recipient" & vbCrLf &
    "    - Fax it to the recipient" & vbCrLf &
    "    - Throw it away"

Text that contains carriage returns confuses the control's AutoSize capabilities, however, so you should not use AutoSize with multiline text.

The Label control also automatically wraps to a new line if the text it contains is too long to fit within the control's width.

LINKLABEL

The LinkLabel control displays a label that is associated with a hyperlink. By default, the label is blue and underlined, so it is easy to recognize as a link. It also displays a pointing hand cursor when the mouse moves over it, so it looks more or less like a link on a web page.

When the user clicks a LinkLabel, the control raises its LinkClicked event. The program can catch the event and take whatever action is appropriate. For example, it could display another form, open a document, or open a web page.

The LinkLabel control provides all the formatting properties that the Label control does. See the section "Label" earlier in this appendix for more information on formatting the control's label.

The control also provides several properties for determining the appearance of its link. The following table describes some of the most useful.

PROPERTY

PURPOSE

ActiveLinkColor

The color of an active link.

DisabledLinkColor

The color of a disabled link.

LinkArea

The piece of the control's text that is represented as a link. This includes a start position and a length in characters.

LinkBehavior

Determines when the link is underlined. This can take the values AlwaysUnderline, HoverUnderline, NeverUnderline, and SystemDefault.

LinkColor

The color of a normal link.

Links

A collection of objects representing the link(s) within the control's text.

LinkVisited

A Boolean that indicates whether the link should be displayed as visited.

VisitedLinkColor

The color of a visited link.

A LinkLabel can display more than one link within its text. For example, in the text "The quick brown fox jumps over the lazy dog," the control might display the words fox and dog as links and the rest as normal text. At design time, you can use the LinkArea property to specify only one link. To make fox the link, the program would set LinkArea to 16, 3 to start with the seventeenth character (remember indexing starts at 0) and include 3 letters.

At runtime, the program can add other links to the control. The following code clears the llblPangram control's Links collection and then adds two new link areas. The program sets each of the new Link objects' LinkData property to a URL that the program should display when the user clicks that link.

Dim new_link As System.Windows.Forms.LinkLabel.Link

llblPangram.Links.Clear()
new_link = llblPangram.Links.Add(16, 3)
new_link.LinkData = "http://www.somewhere.com/fox.htm"
new_link = llblPangram.Links.Add(40, 3)
new_link.LinkData = "http://www.somewhere.com/dog.htm"

The following code shows how the program displays the URL corresponding to the link the user clicked. The code gets the appropriate Link object from the event handler's event arguments, converts the Link object's LinkData property into a string, and uses System.Diagnostics.Process.Start to open it with the system's default browser.

' Display the URL associated with the clicked link.
Private Sub llblPangram_LinkClicked(ByVal sender As System.Object,
 ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) _
 Handles llblPangram.LinkClicked
    System.Diagnostics.Process.Start(e.Link.LinkData.ToString)
End Sub

LISTBOX

The ListBox control displays a list of items that the user can select. The following table describes some of the control's most useful properties.

PROPERTY

PURPOSE

SelectionMode

Determines how the user can select text. See the following text for details.

MultiColumn

If this is True, the control does not display a vertical scroll bar. Instead, if there are too many items to fit, the control displays them in multiple columns. If the columns will not all fit, the control displays a horizontal scroll bar to let you see them all. The control's ColumnWidth property determines the width of the columns.

IntegralHeight

If this is True, the control will not display a partial item. For example, if the control is tall enough to display 10.7 items, it will shrink slightly so it can only display 10 items.

ScrollAlwaysVisible

If this is True, the control displays its vertical scroll bar even if all of its items fit. This can be useful if the program will add and remove items to and from the list at runtime and you don't want the control to change size depending on whether the items all fit.

Sorted

Determines whether the control displays its items in sorted order.

SelectedItem

Returns a reference to the first selected item or Nothing if no item is selected. This is particularly useful if the control's SelectionMode is One.

SelectedIndex

Returns the zero-based index of the first selected item or āˆ’1 if no item is selected. This is particularly useful if the control's SelectionMode is One.

Text

Returns the text displayed for the first currently selected item, or an empty string if no item is selected. Your code can set this property to a string to make the control select the item that displays exactly that string.

SelectedItems

A collection containing references to all the items that are currently selected.

SelectedIndices

A collection containing the indices of all the items that are currently selected.

UseTabStops

Determines whether the control recognizes tabs embedded within its items' text. If UseTabStops is True, the control replaces tab characters with empty space. If UseTabStops is False, the control displays tab characters as thin black boxes.

The control's SelectionMode property determines how the user can select items. This property can take the value None, One, MultiSimple, or MultiExtended.

When SelectionMode is None, the user cannot select any items. This mode can be useful for displaying a read-only list. It can be particularly handy when the list is very long and the control's automatic scrolling is useful, allowing the user see all of the list's items.

When SelectionMode is One, the user can select a single item. When the user clicks an item, any previously selected item is deselected.

When SelectionMode is MultiSimple, the user can select multiple items by clicking them one at a time. When the user clicks an item, the other items keep their current selection status. This mode is useful when the user needs to select multiple items that are not necessarily near each other in the list. It is less useful if the user must select a large number of items. For example, clicking 100 items individually would be tedious.

When SelectionMode is MultiExtended, the user can select multiple items in several ways. The user can click and drag to manipulate several items at once. If the first item clicked is not selected, all of the items are selected. If the first item is already selected, all of the items are deselected. If the user holds down the Ctrl key and clicks an item, the other items' selection status remains unchanged. If the user doesn't hold down the Ctrl key, any other items are deselected when the user selects new items. If the user clicks an item and then clicks another item while holding down the Shift key, all of the items between those two are selected. If the user holds down the Ctrl key at the same time, those items are selected and the other items' selection status remains unchanged.

The MultiExtended mode is useful when the user needs to select many items, some of which may be next to each other. This mode is quite complicated, however, so MultiSimple may be a better choice if the user doesn't need to select ranges of items or too many items. The CheckedListBox control is often a good alternative when the user must make many complicated selections.

Use the control's Items.Add method to add an object to the list. If the object isn't a string, the control uses the object's ToString method to determine the value it displays to the user.

The ListBox control's FindString method returns the index of the first item that begins with a given string. For example, the following code selects the first item that begins with the string Code:

lstTask.SelectedIndex = lstTask.FindString("Code")

The FindStringExact method returns the index of the first item that matches a given string exactly.

LISTVIEW

The ListView control displays a list of items in one of five possible views, determined by the control's View property. The View property can take the following values:

  • Details ā€” For each item, displays a small icon, the item's text, and the sub-items' text on a row.

  • LargeIcon ā€” Displays large icons above the item's text. Entries are arranged from left to right until they wrap to the next row.

  • List ā€” Displays small icons to the left of the item's text. Each entry is placed on its own row.

  • SmallIcon ā€” Displays small icons to the left of the item's text. Entries are arranged from left to right until they wrap to the next row.

  • Tile ā€” Displays large icons to the left of the item's text. Entries are arranged from left to right until they wrap to the next row.

Figure G-4 shows each of these views for the same list of items. The second tiled view shown in the lower-right corner uses the control's CheckBoxes and StateImageList properties, and is described shortly.

The ListView control can display five views.

Figure G.4. The ListView control can display five views.

Set the control's LargeImageList and SmallImageList properties to ImageList controls containing the images that you want to use for the LargeIcon and SmallIcon views.

Each of the ListView control's items may contain one or more sub-items that are displayed in the Details view. To create the items and sub-items, open the form designer, select the ListView control, click the Items property in the Properties window, and click the ellipsis (...) button to the right to display the ListViewItem Collection Editor.

Click the Add button to make a new item. Set the item's Text property to the string you want the control to display. If you have attached ImageList controls to the ListView, set the new item's ImageIndex property to the index of the image you want to display for this item in the LargeIcon and SmallIcon views.

For example, the program in Figure G-4 contains two ImageList controls. The imlBig control contains 32 Ɨ 32 pixel images and the imlSmall control contains 16 Ɨ 16 pixel images. Each holds one image of a book. All of the items in the ListView items have ImageIndex set to 0, so they all display the first images in the imlBig and imlSmall controls.

To give an item sub-items at design time, select it in the ListViewItem Collection Editor, click its SubItems property, and then click the ellipsis (...) button to the right to display the ListViewSubItem Collection Editor. Use the Add button to make sub-items. Set the sub-items' Text properties to determine what the Details view displays.

If you set the ListView control's CheckBoxes property to True, the control displays check boxes next to its items. If you set the control's StateImageList property to an ImageList control, the control displays the images in that list. When the user double-clicks an item, the control toggles the image index between 0 and 1 and displays the first or second image in the ImageList control. In Figure G-4, the ListView on the lower-right uses check box images that look like circles with numbers inside. If you set CheckBoxes to True but do not set the ListView control's StateImageList property, the control displays simple boxes containing check marks.

If CheckBoxes is True, the program can use the CheckedIndices or CheckedItems collections to see which items the user has selected. If the StateImageList control holds more than two images, an item is considered checked if it is displaying any picture other than the first one. The following code lists the currently checked items in the lvwMeals ListView control:

For Each checked_item As ListViewItem In lvwMeals.CheckedItems
    Debug.WriteLine(checked_item.ToString)
Next checked_item

The control's SelectedIndices and SelectedItems collections let the program see which items the user has currently selected. The user can select items by clicking them. If the user holds down the Ctrl key while clicking, any items that are already selected remain selected. If the user clicks an item, holds down the Shift key, and then clicks another item, the control selects all of the items in between the two.

If you are using the ListView in Details mode, you must define the control's columns. Open the form designer, select the control, click the Columns property in the Properties window, and click the ellipsis (...) button to the right to display the ColumnHeader Collection Editor.

Use the Add button to create column headers and then set each header's text. If you don't define enough columns for all of the sub-items, some of the sub-items will not be visible to the user. This is one way you can include data for an item but hide it from the user.

The LabelEdit control has several other properties that determine its appearance and how the control interacts with the user. The following table describes some of the most important of these.

PROPERTY

PURPOSE

AllowColumnReorder

If True, the user can rearrange the columns by dragging their column headers while in Detail mode.

FullRowSelect

If True, clicking an item or any of its sub-items selects the item. If False, the user must click the item, not a sub-item, to select the item. If AllowColumnReorder is True, you may want to set FullRowSelect to True also so the user doesn't need to figure out which rearranged column contains the item itself.

GridLines

If True, the control displays gray lines between the rows and columns while in Detail mode.

HeaderStyle

When in Detail mode, this can be None to not display column headers, Clickable to allow the user to click column headers, or Nonclickable to not let the user click column headers. If this is Clickable, the program can catch the control's ColumnClick event to learn the index of the column clicked. For example, you may want to sort the ListView control's items using the clicked column.

LabelEdit

If True, the user can modify the items' labels. The user can never change the sub-items' labels.

MultiSelect

If True, the user can use the Ctrl and Shift keys to select multiple items.

Sorting

Indicates whether the control displays its items sorted ascending, sorted descending, or not sorted.

Example program UseListView, shown in Figure G-4 and available for download on the book's web site, uses these techniques to initialize its ListView controls at design time.

ListView Helper Code

In addition to using the ListView control's collection property editors at design time, you can manipulate the control's items and sub-items at runtime using code.

The control's Columns collection contains ColumnHeader objects representing the control's column headers. You can use the collection's Add, Count, Remove, RemoveAt, and other methods to manage the text displayed above the columns.

The ListViewMakeColumnHeaders subroutine shown in the following code uses the Columns collection to define a ListView control's column headers. The routine takes as parameters a ListView control and a ParamArray of values that contain title strings, alignment values, and widths. The code clears the control's Columns collection and then loops through the ParamArray. For each triple of array entries, the control creates a column header using the title string, alignment value, and width.

' Make the ListView's column headers.
' The ParamArray entries should be triples holding
' column title, HorizontalAlignment value, and width.
Private Sub ListViewMakeColumnHeaders(ByVal lvw As ListView,
 ByVal ParamArray header_info() As Object)
    ' Remove any existing headers.
    lvw.Columns.Clear()

    ' Make the column headers.
    For i As Integer = header_info.GetLowerBound(0) To _
                       header_info.GetUpperBound(0) Step 3
        Dim col_header As ColumnHeader = lvw.Columns.Add(
            DirectCast(header_info(i), String),
            āˆ’1,
            DirectCast(header_info(i + 1), HorizontalAlignment))
        col_header.Width = DirectCast(header_info(i + 2), Integer)
    Next i
End Sub

The following code shows how a program might use subroutine ListViewMakeColumnHeaders to define the lvwBooks control's column headers. Because the Pages and Year columns contain numeric values, the control aligns them on the right of their columns.

' Make the ListView column headers.
ListViewMakeColumnHeaders(lvwBooks,
    "Title", HorizontalAlignment.Left, 120,
    "URL", HorizontalAlignment.Left, 120,
    "ISBN", HorizontalAlignment.Left, 90,
    "Picture", HorizontalAlignment.Left, 120,
    "Pages", HorizontalAlignment.Right, 50,
    "Year", HorizontalAlignment.Right, 40)

The ListView control's Items collection contains ListViewItem objects that represent the control's items. Each ListViewItem has a SubItems collection that represents the item's sub-items. These collections provide the usual assortment of methods for managing collections: Count, Add, Remove, RemoveAt, and so forth.

The ListViewMakeRow subroutine shown in the following code uses these collections to add an item and its sub-items to a ListView. The routine takes as parameters the ListView control, the name of the item, and a ParamArray containing the names of any number of sub-items. The code uses the ListView control's Items.Add method to make the new item. It then loops through the sub-item names, using the new item's SubItems.Add method to make the sub-items.

' Make a ListView row.
Private Sub ListViewMakeRow(ByVal lvw As ListView, ByVal image_index As Integer,
 ByVal item_title As String, ByVal ParamArray subitem_titles() As String)
    ' Make the item.
    Dim new_item As ListViewItem = lvw.Items.Add(item_title)
    new_item.ImageIndex = image_index

    ' Make the subitems.
For i As Integer = subitem_titles.GetLowerBound(0) To _
                       subitem_titles.GetUpperBound(0)
        new_item.SubItems.Add(subitem_titles(i))
    Next i
End Sub

If you set a ListView column's width to āˆ’1, the control automatically resizes the column so it is wide enough to display all of its data. If you set a column's width to āˆ’2, the control makes the column wide enough to display all of its data and its header text.

The ListViewSizeColumns subroutine shown in the following code sizes all of a ListView control's columns so that they fit their data. If the allow_room_for_header parameter is True, it also allows room for the column headers.

' Set column widths to āˆ’1 to fit data, āˆ’2 to fit data and header.
Private Sub ListViewSizeColumns(ByVal lvw As ListView,
 ByVal allow_room_for_header As Boolean)
    Dim new_wid As Integer = āˆ’1
    If allow_room_for_header Then new_wid = āˆ’2

    ' Set the width for each column.
    For i As Integer = 0 To lvw.Columns.Countāˆ’1
        lvw.Columns(i).Width = new_wid
    Next i
End Sub

These helper routines make working with ListView controls a bit easier.

Custom ListView Sorting

The ListView control's Sorting property enables you to sort items in ascending or descending order, but it only considers the items, not the sub-items. It doesn't even use the sub-items to break ties when two items have the same value.

Fortunately, the ListView control's ListViewItemSorter property provides the flexibility to change the sort order in any way you like. To use this property, you must create a class that implements the IComparer interface. The ListView control will use an object of this type to decide which items to place before other items.

The key to the IComparer interface is its Compare function. This function takes two ListViewItem objects as parameters and returns āˆ’1, 0, or 1 to indicate whether the first should be considered less than, equal to, or greater than the second object in the sort order.

To implement a custom sort order, the program should set the ListView control's ListViewItemSorter property to an object that implements IComparer and then call the control's Sort method. The control then uses the IComparer object to put the items in the proper order.

Example program ListViewCustomSort, which is available for download on the book's web site, uses an IComparer class to allow the user to sort ascending or descending on any of the ListView control's item or sub-item columns in the control's Details view. The code is fairly involved so it is not shown here. Download the example from the book's web site to see the details.

MASKEDTEXTBOX

The MaskedTextBox control is a text box that provides a mask that helps guide the user in entering a value in a particular format. The mask determines which characters are allowed at different positions in the text. It displays placeholder characters to help prompt the user and underscores where the user can enter characters. For example, an empty United States phone number field would appear as (__)__-___in the MaskedTextBox.

The control's Mask property uses the characters shown in the following table.

CHARACTER

MEANING

0

A required digit between 0 and 9.

9

An optional digit or space.

#

An optional digit, space, +, or āˆ’. If the user leaves this blank, this character appears as a space in the control's Text, InputText, and OutputText properties.

L

A required letter a-z or A-Z.

?

An optional letter a-z or A-Z.

&

A required nonspace character.

C

An optional character.

A

A required alphanumeric character a-z, A-Z, or 0āˆ’9.

a

An optional alphanumeric character a-z, A-Z, or 0āˆ’9.

.

A decimal separator placeholder. The control automatically displays the appropriate decimal separator character for the current UI culture.

,

A thousands separator placeholder. The control automatically displays the appropriate thousands separator character for the current UI culture.

:

A time separator placeholder. The control automatically displays the appropriate time separator character for the current UI culture.

/

A date separator placeholder. The control automatically displays the appropriate date separator character for the current UI culture.

$

A currency symbol placeholder. The control automatically displays the appropriate currency symbol character for the current UI culture.

<

Automatically converts the characters that the user types after this point into lowercase.

>

Automatically converts the characters that the user types after this point into uppercase.

|

Disables the previous < or > character.

Escapes a character so it is displayed literally by the control even if the character would otherwise have special meaning. For example, 9 places a 9 in the output and \ displays a .

All other characters appear as literals within the mask. Dashes and parentheses are common literal characters. For example, the Social Security number mask 000-00-0000 displays dashes as in "__-__-___."

The following table shows the MaskTextBox control's most useful properties. Note that this control inherits from the TextBox control, so it inherits most of that control's properties, methods, and events. See the section "TextBox" later in this appendix for more information.

PROPERTY

PURPOSE

AllowPromptAsInput

Determines whether the user can enter the prompt character determined by the PromptChar property (normally an underscore).

AsciiOnly

Determines whether the control allows non-ASCII Unicode characters.

BeepOnError

Determines whether the control beeps whenever the user types an invalid keystroke.

EnableCutCopyLiterals

Determines whether literal characters such as the parentheses in the mask (999)000-0000 are included when the user copies and pastes the control's text.

HidePromptOnLeave

Determines whether the control hides its prompt characters when it loses the focus.

IncludeLiterals

Determines whether the control includes literal characters in the Text and OutputText properties.

IncludePrompt

Determines whether the control includes the PromptChar character in the OutputText property.

InputText

Gets or sets the characters input by the user. This doesn't include any literal mask characters.

Mask

Gets or sets the mask.

MaskCompleted

Returns True if the user's input satisfies the required mask characters.

MaskFull

Returns True if the user has entered characters for all of the mask's required and optional elements.

OutputText

Returns the user's text modified by the IncludeLiterals and IncludePrompt properties.

PromptChar

Determines the character that the control uses as a placeholder for user input.

Text

Gets or sets the text as it is currently displayed to the user, including prompt and literal characters.

The following table describes the control's most useful events.

EVENT

OCCURS WHEN

InputTextChanged

The control's text has been modified.

MaskChanged

The control's mask changed.

MaskInputRejected

The user's input does not satisfy the mask at the current position.

OutputTextChanged

The control's text has been modified.

TextChanged

The control's text has been modified.

Unfortunately, the MaskedTextBox control is relatively inflexible. It requires the user to enter exactly the right characters at the right positions, and there can be no variation in the format. For example, a single mask cannot let the user enter a telephone number in either of the formats 456-7890 or (123)456-7890. The mask (999)000-0000 makes the first three digits optional, but the user must enter spaces in those positions or skip over them. The mask also considers each character separately, so this mask accepts the value (3)456-7890.

This inflexibility means the MaskedTextBox control is most useful when you know exactly what the user will need to enter. If you want the user to type a four-digit telephone extension, a seven-digit phone number, or a five-digit ZIP code, then the control works well. If the user might enter either a seven- or ten-digit phone number, a five-digit ZIP code or a nine-digit ZIP+4 code, or an arbitrary e-mail address, the control is much less useful. In these cases, you might want to use regular expressions to validate the user's input more precisely. For more information on regular expressions, see the "Regular Expressions" section in Chapter 39, "Useful Namespaces."

MENUSTRIP

The MenuStrip control represents a form's menus, submenus, and menu items. To make the form display the menu, its Menu property must be set to the MenuStrip control. The first time you add a MenuStrip control to the form, Visual Basic automatically sets the form's Menu property to the new control, so you usually don't need to worry about this. If you later delete the control and create a new MenuStrip, you may need to set this property yourself.

At design time, the MenuStrip control is visible both at the top of the form and in the component tray. Click a menu entry and type to change the caption it displays. Place an ampersand in front of the character that you want to use as a keyboard accelerator. For example, to make the caption of the File menu display as File, set the menu's text to &File. If you type Alt+F at runtime, the program opens this menu.

To make a cascading submenu, click a menu item and enter its caption. A ghostly text box appears to the right containing the text "Type Here." Click this text and enter the submenu's name.

When you select a menu item, the Properties window displays the menu item's properties. The following table describes the most useful menu item properties.

PROPERTY

PURPOSE

Checked

Indicates whether the item is checked. You can use this property to let the user check and uncheck menu items.

CheckOnClick

Determines whether the item should automatically check and uncheck when the user clicks it.

CheckState

Determines whether the item is checked, unchecked, or displayed as in an indeterminate state.

DisplayStyle

Determines whether the item displays text, an image, both, or neither. The image appears on the left where a check box would otherwise go. If the item displays an image, it draws a box around the image when the item is checked.

Enabled

Determines whether the menu item is enabled. If an item is disabled, its shortcut is also disabled and the user cannot open its submenu if it contains one.

Font

Determines the font used to draw the item.

MergeAction

Determines how Visual Basic merges MDI child and parent form menus. See the online help for more information.

MergeIndex

Determines the order in which Visual Basic merges MDI child and parent form menus. See the online help for more information.

Name

Gives the menu item's name.

ShortcutKeys

Determines the item's keyboard shortcut. For instance, if you set an item's shortcut to F5, the user can instantly invoke the item at runtime by pressing the F5 key.

ShowShortcutKeys

Determines whether the menu displays its shortcut to the right at runtime. Usually this should be True, so users can learn about the items' shortcuts.

Text

Gives the caption displayed by the item. Place an ampersand in front of the character you want to use as a keyboard accelerator as already described.

Visible

Determines whether the item is visible. An item's shortcut will still work even if the item is not visible. You can use that feature to provide keyboard shortcuts for functions that are not available in any menu.

When the user selects a menu item, the item raises a Click event. You can write an event handler to take whatever action is appropriate. For example, the following code shows how the File menu's Exit item closes the form:

Private Sub mnuFileExit_Click() Handles mnuFileExit.Click
    Me.Close()
End Sub

To create a menu item event handler, open the item in the form editor and double-click it.

For online help about the MenuStrip control, go to msdn.microsoft.com/system.windows.forms.menustrip.aspx.

MESSAGEQUEUE

The MessageQueue component provides access to a queue on a message-queuing server. An application can use a message queue to communicate with other applications. This is a fairly advanced and specialized topic, so it is not covered in detail here. See the online help at msdn.microsoft.com/system.messaging.messagequeue.aspx for more information.

MONTHCALENDAR

The MonthCalendar control displays a calendar that allows the user to select a range of dates. This calendar is similar to the one that the DateTimePicker control displays when its ShowUpDown property is False and you click the control's drop-down arrow (on the bottom in Figure G-3). See the section "DateTimePicker" earlier in this appendix for more information on that control.

The DateTimePicker control is designed to let the user select a single date. The MonthCalendar control is a bit more powerful. For example, this control can allow the user to select a range of dates by clicking and dragging across the calendar. The program can use the control's SelectionRange, SelectionStart, and SelectionEnd properties to see what dates the user has selected.

The following table describes the control's most useful properties for controlling its more advanced features.

PROPERTY

PURPOSE

AnnuallyBoldedDates

An array that specifies dates that should be bolded every year. For example, you can bold April 1 for every year displayed.

BoldedDates

An array that specifies specific dates that should be displayed in bold.

CalendarDimensions

Sets the number of columns and rows of months the control displays. Figure G-5 shows a MonthCalendar control with Calendar Dimensions = 3, 2 (three columns and two rows).

FirstDayOfWeek

Sets the day of the week shown in the leftmost column of each month. Figure G-5 uses the default value Sunday.

MaxDate

The last date the user is allowed to select.

MaxSelectionCount

The maximum number of days the user can select.

MinDate

The first date the user is allowed to select.

MonthlyBoldedDates

An array that specifies dates that should be bolded every month. For example, you can bold the 13th of every month displayed.

SelectionEnd

A DateTime object representing the control's last selected date.

SelectionRange

A SelectionRange object representing the control's selected range of dates.

SelectionStart

A DateTime object representing the control's first selected date.

ShowToday

Determines whether the control displays today's date at the bottom.

ShowTodayCircle

Determines whether the control circles today's date (April 1, 2010 in Figure G-5). (Although on this system at least the date is "circled" with a rectangle.)

ShowWeekNumbers

Determines whether the control displays the number of each week in the year to the left of each week.

SingleMonthSize

Returns the minimum size needed to display a single month.

TodayDate

Determines the date displayed as today's date (April 1, 2010 in Figure G-5).

TodayDateSet

Boolean that indicates whether the control's TodayDate property has been explicitly set.

Program UseMonthCalendarInDialog displays several months at a time.

Figure G.5. Program UseMonthCalendarInDialog displays several months at a time.

The MonthCalendar control provides several handy methods. The following table describes the most useful.

METHOD

PURPOSE

AddAnnuallyBoldedDate

Adds a date to the control's array of annually bolded dates. You must call UpdateBoldedDates after using this method.

AddBoldedDate

Adds a date to the control's array of bolded dates. You must call UpdateBoldedDates after using this method.

AddMonthlyBoldedDate

Adds a date to the control's array of monthly bolded dates. You must call UpdateBoldedDates after using this method.

GetDisplayRange

Returns a SelectionRange object that indicates the range of dates currently displayed by the control. If this method's visible parameter is True, the SelectionRange includes only dates that are included in the months that are completely visible (1/1/2010 to 6/30/2010 in Figure G-5). If this parameter is False, the SelectionRange includes all of the displayed dates even if they are in the partially displayed months.

RemoveAllAnnuallyBoldedDates

Empties the control's array of annually bolded dates. You must call UpdateBoldedDates after using this method.

RemoveAllBoldedDates

Empties the control's array of bolded dates. You must call UpdateBoldedDates after using this method.

RemoveAllMonthlyBoldedDates

Empties the control's array of monthly bolded dates. You must call UpdateBoldedDates after using this method.

RemoveAnnuallyBoldedDate

Removes a specific annually bolded date. You must call UpdateBoldedDates after using this method.

RemoveBoldedDate

Removes a specific bolded date. You must call UpdateBoldedDates after using this method.

RemoveMonthlyBoldedDate

Removes a specific monthly bolded date. You must call UpdateBoldedDates after using this method.

SetCalendarDimensions

Sets the control's CalendarDimensions property.

SetDate

Selects the specified date.

SetSelectionRange

Selects the range defined by two dates.

UpdateBoldedDates

Makes the control update itself to show changes to its bolded dates.

The control's bolded dates, monthly bolded dates, and annually bolded dates are all tracked separately and the control displays any date that is listed in any of those groups as bold. That means, for instance, that the RemoveAllBoldedDates subroutine does not change the monthly bolded dates or annually bolded dates.

For example, the following code sets April 1 as an annually bolded date and January 13 as a monthly bolded date. It then removes all of the nonspecific bolded dates and calls UpdateBoldedDates. The result is that April 1 in every year is bold and that the 13th of every month is bold.

calStartDate.AddAnnuallyBoldedDate(#4/1/2010#)
calStartDate.AddMonthlyBoldedDate(#1/13/2010#)
calStartDate.RemoveAllBoldedDates()
calStartDate.UpdateBoldedDates()

Example program UseMonthCalendar uses a MonthCalendar control to display a single month at a time and lets the user select a date range. Example program UseMonthCalendarInDialog also lets the user select a range of dates, but it displays six months at a time. Both of these programs are available for download on the book's web site.

NOTIFYICON

The NotifyIcon component is invisible at runtime. A program can use the NotifyIcon to display an icon in the system tray. The system tray (also called the status area) is the little area holding small icons in the lower-right part of the taskbar. The program can use this icon to indicate the application's state.

Figure G-6 shows part of the desktop while the UseNotifyIcon example program is running. The program's NotifyIcon is displaying a happy face icon in the system tray on the lower right. When you click the program's Happy or Sad radio buttons, the NotifyIcon component displays the corresponding icon.

The NotifyIcon component displays an icon in the system tray.

Figure G.6. The NotifyIcon component displays an icon in the system tray.

Figure G-6 also shows the program and the program's icon in the taskbar. These (and the Task Manager, too, although it isn't shown in Figure G-6) also display happy and sad icons. The pictures used for these come from the form's Icon property, not from the NotifyIcon component, so you can display different images for these and the one in the system tray, if you like. Download the UseNotifyIcon example program from the book's web site to see how it sets the icons.

Notification icons are particularly useful for programs that have no user interface or that run in the background. For example, a program that monitors the system's load could use its system tray icon to give the user an idea of the current load.

These sorts of programs, particularly those without normal user interfaces, often add a context menu to their tray icons so that the user can interact with them. This menu might include commands to minimize or restore the application if it has a user interface, or to close the application.

The NotifyIcon component only has a few interesting properties. Its Icon property determines the icon that the component displays. Its Text property sets the tooltip text that the component displays when the user hovers the mouse over the icon. The Visible property determines whether the icon is visible. Finally, the component's ContextMenuStrip property sets the ContextMenuStrip control that displays when the user right-clicks the icon.

NUMERICUPDOWN

The NumericUpDown control displays a number with up and down arrows that you can use to change the number. If you click an arrow and hold it down, the number changes repeatedly. After a small delay, the changes start happening faster, so you can make some fairly large changes in a reasonable amount of time. You can also change the number by clicking it and typing in a new value.

The following table lists the control's most interesting properties.

PROPERTY

PURPOSE

DecimalPlaces

Determines the number of decimal places that the control displays. This has no effect when Hexadecimal is True.

Hexadecimal

Determines whether the control displays the number using a hexadecimal format as in A1C when the control's value is 2588 (decimal).

Increment

Determines the amount by which the values are modified when the user clicks an arrow.

InterceptArrowKeys

If this is True, the user can also adjust the number's value using the up and down arrow keys.

Maximum

Determines the largest value that the control allows.

Minimum

Determines the smallest value that the control allows.

ReadOnly

Determines whether the user can type in a new value. Note that the arrow keys and arrow buttons still work when ReadOnly is True. You can disable them by setting InterceptArrowKeys to False and Increment to 0.

TextAlign

Determines whether the number is aligned on the left, right, or center of the control.

ThousandsSeparator

If this is True, the control displays thousands separators when the value is greater than 999. This has no effect when Hexadecimal is True.

UpDownAlign

Determines whether the up and down arrows are positioned on the left or right.

Value

The control's numeric value.

The control's more important event, ValueChanged, fires whenever the control's numeric value changes, whether because the user changed it or because the program's code changed it.

The Click event handler is not as useful for deciding when the control's value has changed. It executes when the user changes the value by clicking an arrow button, but it does not execute if the user types a new value into the field or uses the arrow keys. It also fires if the user clicks the control's number but doesn't make any changes.

OPENFILEDIALOG

The OpenFileDialog component displays a standard dialog box that lets the user select a file to open. A program calls the component's ShowDialog method to display a file selection dialog. ShowDialog returns DialogResult.OK if the user selects a file and clicks OK, and it returns DialogResult.Cancel if the user cancels.

This component provides many properties for determining the kinds of files the user can select. The following table describes the most useful of these.

PROPERTY

PURPOSE

AddExtension

If True, the component adds the default extension specified in the DefaultExt property to the file name if the user does not include an extension.

CheckFileExists

If True, the component verifies that the file exists. If the user types in the name of a nonexistent file, the component warns the user and refuses to close.

CheckPathExists

If True, the component verifies that the file's directory path exists. If the user types in a file and path and the path doesn't exist, the component warns the user and refuses to close.

DefaultExt

The default extension that the component adds to the file's name if the user omits the extension. This property should have a value such as txt.

DereferenceLinks

If this is True and the user selects a shortcut file (.lnk), the component returns the name of the file referenced by the shortcut rather than the link file.

FileName

Sets the first file selected when the dialog is initially displayed. When the user closes the dialog box, this property returns the name of the file selected. The dialog box retains this value so the next time it is displayed it begins with this file selected.

FileNames

Gets an array of all of the files selected (if the dialog box allows multiple selections).

Filter

A string giving the filter that the dialog box should use. This string holds pairs of display names (such as Bitmaps) and their corresponding filter expressions (such as *.bmp) separated by vertical bar characters (|). Separate multiple expressions within a filter entry with semicolons. For example, the following value lets the user search for GIF files, JPG files, both GIFs and JPGs, or all files: GIFs|*.gif|JPGs|*.jpg;*.jpeg|Both|*.gif;*.jpg;*.jpeg|All Files|*.*

FilterIndex

Gives the index of the filter entry that the dialog box initially displays. The indexes start with 1.

InitialDirectory

Determines the path where the dialog box starts when it is displayed. If you later redisplay the same dialog box, it will start at the path determined by its FileName property, so it continues where it last left off. If you want to change InitialDirectory to start in some other directory, you also need to set FileName = "".

MultiSelect

Determines whether the user can select multiple files.

ReadOnlyChecked

Determines whether the dialog box's Open as read-only check box is initially selected. This has no effect unless ShowReadOnly is True. The dialog box retains this value so that the next time it is displayed it has the value that the user selected. If you want the box checked every time the dialog box appears, you must set ReadOnlyChecked to True before you display the dialog each time.

RestoreDirectory

If this value is True, the dialog box restores its initial directory after the user closes it, if the user has navigated to some other directory. However, if you later redisplay the same dialog box, it will start at the path determined by its FileName property, so it continues where it last left off. That means if you want to restore the initial directory, you must also set FileName = "" before redisplaying the dialog.

ShowHelp

Determines whether the dialog box displays a Help button. If you set this to True, the application should catch the dialog box's HelpRequest event and give the user some help.

ShowReadOnly

Determines whether the dialog box displays an Open as read-only check box.

Title

Determines the dialog's title text.

The OpenFileDialog component raises its FileOk event when the user tries to accept a file. You can use an event handler to catch the event and perform extra validation. Set the event's e.Cancel value to True to stop the dialog box from accepting the selection.

The following code allows the dlgBitmapFile dialog box to accept only bitmap files. The code loops through the dialog box's selected files. If it finds one with a name that doesn't end in .bmp, the program displays an error message, sets e.Cancel to True, and exits the function.

' Ensure that the user only selects bitmap files.
Private Sub dlgBitmapFile_FileOk() Handles dlgBitmapFile.FileOk
    For Each file_name As String In dlgBitmapFile.FileNames
        ' See if this file name ends with .bmp.
        If Not file_name.EndsWith(".bmp") Then
            MessageBox.Show("File "" & file_name & "" is not a bitmap file",
                "Invalid File Type",
                MessageBoxButtons.OK,
                MessageBoxIcon.Exclamation)
            e.Cancel = True
            Exit Sub
        End If
    Next file_name
End Sub

PAGESETUPDIALOG

The PageSetupDialog component displays a dialog box that lets the user specify properties for printed pages. For example, the user can specify the printer's paper tray, page size, margins, and orientation (portrait or landscape).

Before you can display the dialog box, you must assign it a PageSetting object to modify. You can do this in two ways. First, you can set the component's Document property to a PrintDocument object. If the user clicks OK, the dialog box modifies the PrintDocument's settings. This method is preferred because a PrintDocument object defines both page settings and printer settings.

Second, you can set the dialog box's PageSettings property to a PageSettings object. If the user clicks OK, the dialog modifies that object's settings.

Your program calls the component's ShowDialog method to display the dialog. ShowDialog returns DialogResult.OK if the user clicks OK and it returns DialogResult.Cancel if the user cancels. Often, the program doesn't need to know whether the user accepted or canceled the dialog box, however, because the dialog box modifies a PageSettings object automatically if the user clicks OK. The program can use that object when printing later, so it doesn't need to keep track of whether the user accepted or canceled the dialog box.

The following code displays a PageSetupDialog attached to a PrintDocument object:

PageSetupDialog1.Document = New PrintDocument
PageSetupDialog1.ShowDialog()

The following table describes the PageSetupDialog component's most useful properties.

PROPERTY

PURPOSE

AllowMargins

Determines whether the dialog box lets the user modify its margin settings.

AllowOrientation

Determines whether the dialog box lets the user modify its orientation settings.

AllowPaper

Determines whether the dialog box lets the user modify its paper settings.

AllowPrinter

Determines whether the dialog box lets the user modify its printer settings.

Document

The PrinterDocument object that the dialog box will modify.

MinMargins

Gives the smallest allowed margin values. MinMargins is a reference to a Margins object that has Left, Right, Top, and Bottom properties that you can use to specify each margin separately.

PageSettings

The PageSettings object that the dialog box will modify.

PrinterSettings

The PrinterSettings object that the dialog box will modify when the user clicks the Printer button. If you set the Document property, the PrinterDocument object includes a PrinterSettings object.

ShowHelp

Determines whether the dialog box displays a Help button. If you set this to True, the application should catch the dialog box's HelpRequest event and give the user some help.

ShowNetwork

Determines whether the dialog box displays a Network button on the Printer setup dialog box when the user clicks the Printer button.

PANEL

The Panel control is a container of other controls. By setting the Anchor and Dock properties of the contained controls, you can make those controls arrange themselves when the Panel is resized.

You can use a Panel to make it easy to manipulate the controls it contains as a group. If you move the Panel, the controls it contains move also. If you set the Panel control's Visible property to False, the controls it contains are hidden. If you set the Panel control's Enabled property to False, the controls it contains are also disabled.

Similarly, you can set the Panel control's other style properties such as BackColor, ForeColor, and Font and any controls contained in the Panel inherit these values (although a few controls insist on keeping their own values for some properties, such as the TextBox control's ForeColor and BackColor properties).

A Panel also defines a separate group for radio buttons. If you have two Panel controls, each containing several radio buttons, then the two groups of buttons work independently, so clicking a button in one Panel doesn't deselect the buttons in the other Panel.

The most advanced feature of the Panel control is its auto-scroll capability. If you set the AutoScroll property to True, the control automatically provides working scroll bars if the controls that it contains don't fit. The AutoScrollMargin property lets you define extra space that the control should add around its contents when it is auto-scrolling.

Use the AutoScrollMinSize property to ensure that the control's scrolling area is at least a certain minimum size. For example, suppose that the Panel contains controls with coordinates between 0 and 100 in both the X and Y directions. Normally, the control would let you scroll over the area 0 <= X <= 100, 0 <= Y <= 100 so that you can see all of the controls. If you set AutoScrollMinSize to 200, 50, the control would let you scroll over the area 0 <= X <= 200, 0 <= Y <= 100 so that you can see the controls plus the area defined by AutoScrollMinSize.

The AutoScrollPosition property lets your program get or set the scroll bars' position at runtime. For example, the following code makes the panMap control scroll to make the upper-left corner of its contents visible:

panMap.AutoScrollPosition = New Point(0, 0)

If you set AutoScrollPosition to a point that is outside of the Panel's display area, the control adjusts the point so that it lies within the area.

Although a program often uses a Panel control as an invisible container for other controls, you can use its BackColor and BorderStyle properties to make it visible if you like.

PERFORMANCECOUNTER

The PerformanceCounter component represents a Windows NT-style performance counter. You can use the component's methods to read, increment, and decrement the counters. This is a fairly advanced and specialized topic, so it is not covered in detail here. See the online help at msdn.microsoft.com/system.diagnostics.performancecounter.aspx for more information.

PICTUREBOX

The PictureBox control displays images. It also provides a Graphics object that you can use to draw lines, rectangles, ellipses, and other shapes at runtime.

The control's Image property determines the picture that the control displays. Its SizeMode property determines how the image is sized to fit into the control. The following table describes the allowed SizeMode values.

VALUE

MEANING

Normal

The image is not resized. If it sticks off the edge of the PictureBox, the image is clipped.

StretchImage

The image is stretched to fill the control. This may change the image's shape, making it shorter and wider or taller and thinner than it should be.

AutoSize

The PictureBox adjusts its size to fit the image. If the control is displaying borders, it allows extra room for them.

CenterImage

The image is centered in the PictureBox at its normal size. If it sticks off the edge of the PictureBox, the image is clipped.

If you set the control's BackgroundImage property to a picture, the control tiles itself completely with copies of the picture. If you also set the Image property, the background shows behind the image. If you have SizeMode set to StretchImage or AutoSize, the image fills the entire control, so you will not see the background image.

The PictureBox control has several properties that deal with its size internally and externally. Its Size, Width, and Height properties give information about the size of the control, including its border if it has one. The ClientRectangle, ClientSize, and DisplayRectangle properties give information about the area inside the control, not including its border. You should use these properties when you draw on the control.

The PictureBox control's CreateGraphics method returns a Graphics object that represents the control's client area. Your code can use that object's methods to draw on the control.

Although you can draw on the object returned by the control's CreateGraphics method, that does not ensure that the drawing will remain. If you hide the PictureBox with another form and then bring it back to the top, the drawing is gone. There are two main approaches to keeping a drawing visible on a PictureBox.

First, you can place the drawing commands in the PictureBox control's Paint event handler. The Paint event occurs any time part of the control needs to be refreshed. That happens if the control is covered and then uncovered, when its form is minimized and then restored, and when the control is enlarged so that a new part of its display area is exposed.

The second approach is to make a Bitmap that fits the PictureBox, draw on the Bitmap, and then set the control's Image property equal to the Bitmap. After that, the control automatically displays its image.

This method takes more memory than the previous method of drawing in the control's Paint event handler. If the drawing is very complicated and takes a long time, however, it may be faster to generate the Bitmap once rather than redrawing the picture every time the control raises its Paint event.

The final PictureBox feature that is relevant to drawing is its Invalidate method. This method invalidates some or all of the control's display area and generates a Paint event. You can use this method to redraw the control if you have changed some data that will affect the drawing's appearance.

PRINTDIALOG

The PrintDialog component displays a dialog box that lets the user prepare to print. The dialog lets the user select a printer, modify printer properties, select the pages to print, and determine the number of copies to print. A program calls the component's ShowDialog method to display the dialog.

The following table describes the PrintDialog's most useful properties.

PROPERTY

PURPOSE

AllowPrintToFile

Determines whether the Print to file button is enabled.

AllowSelection

Determines whether the Selection radio button is enabled.

AllowSomePages

Determines whether the Pages radio button, as well as the From and To text boxes, are enabled.

Document

The PrintDocument object that provides the dialog with a PrinterSettings object.

PrinterSettings

The PrinterSettings object that the dialog modifies.

PrintToFile

Determines whether the Print to file box is checked.

ShowHelp

Determines whether the Help button is visible. If this is True, you should catch the component's HelpRequest event and give the user some help.

ShowNetwork

Determines whether the Network button is visible.

If the user clicks Print, the dialog returns DialogResult.OK. If the user clicks Cancel, the dialog box returns DialogResult.Cancel. The program can use the dialog box's PrintToFile property to see if the user checked the Print to file box, and it can use the PrinterSettings object to learn about the user's other selections.

The following table lists the PrinterSettings object's properties that are most useful for learning about the user's selections. You can set many of these properties before displaying the dialog box to give it initial values. After the dialog box closes, the properties indicate the user's selections.

PROPERTY

PURPOSE

CanDuplex

Indicates whether the printer can print in duplex.

Collate

Indicates whether the user checked the Collate box.

Copies

The number of copies the user selected.

Duplex

Indicates whether the user asked for duplex printing.

FromPage

The number the user entered in the From text box.

InstalledPrinters

Returns a collection listing the system's installed printers.

IsDefaultPrinter

True if the printer given by the PrinterName property is the default printer.

IsPlotter

True if the printer is a plotter device.

IsValid

True if the printer given by the PrinterName property is a valid printer.

LandscapeAngle

The angle at which the printout is rotated to produce landscape printing. The valid angles are 90 and 270 degrees, or 0 if the printer doesn't support landscape printing.

MaximumCopies

The maximum number of copies that the printer will let you print at a time.

MaximumPage

The largest value that the user is allowed to enter in the To and From boxes.

MinimumPage

The smallest value that the user is allowed to enter in the To and From boxes.

PaperSizes

Returns a collection of objects describing the paper sizes supported by the printer. These PaperSize objects have the properties Height, Width, PaperName, and Kind (for example, Letter).

PaperSources

Returns a collection of objects describing the paper trays provided by the printer. These PaperSource objects have the properties SourceName (for example, Default tray) and Kind (for example, Upper).

PrinterName

Gets or sets the name of the printer to use.

PrinterResolutions

Returns a collection of PrinterResolution objects that describe the resolutions supported by the printer. PrinterResolution objects have the properties Kind (High, Medium, Low, Draft, or Custom), X, and Y. The X and Y properties return negative values for standard resolutions and the number of dots per inch (dpi) for custom resolutions.

PrintRange

Indicates the pages that the user wants to print. This can have the value AllPages (print everything), Selection (print the current selection), or SomePages (print the pages between FromPage and ToPage).

PrintToFile

Indicates whether the Print to file check box is selected.

SupportsColor

True if the printer supports color.

ToPage

The number the user entered in the To text box.

The FromPage and ToPage properties must lie between the MinimumPage and MaximumPage values before you display the dialog box or the dialog box throws an error. If the user enters a value outside of the range MinimumPage to MaximumPage and clicks Print, the dialog box displays a message similar to "This value is not within the page range. Enter a number between 10 and 30." It then refuses to close.

Usually a program associates a PrintDialog with a PrintDocument object and that object provides the PrinterSettings object. You can either create the PrintDialog object at runtime, or you can use the PrintDocument component described in the following section at design time. If you create a PrintDocument component at design time, you can also set the PrintDialog's Document property to that component at design time.

Example program UsePrintDialog uses the following code to print a document. In this example, the pdlgRectangle and pdlgRectangle components were created and pdlgRectangle.Document was set to pdlgRectangle at design time. When the user clicks the Print button, the program displays the PrintDialog. If the user clicks the dialog box's Print button, the code calls the PrintDocument object's Print method. When the PrintDocument object needs to generate a page for printing, it raises its PrintPage event. In this example, the event handler draws a rectangle and indicates that the document has no more pages to draw.

Imports System.Drawing.Printing

Public Class Form1
    ' Display the print dialog.
    Private Sub btnPrint_Click() Handles btnPrint.Click
        If pdlgRectangle.ShowDialog() = Windows.Forms.DialogResult.OK Then
            ' Print the document.
            pdocRectangle.Print()
        End If
    End Sub

    ' Print a page of the document.
    Private Sub PrintDocument1_PrintPage(ByVal sender As Object,
     ByVal e As System.Drawing.Printing.PrintPageEventArgs) _
     Handles pdocRectangle.PrintPage
        e.Graphics.DrawRectangle(Pens.Black, 100, 100, 600, 300)
        e.HasMorePages = False
    End Sub
End Class
                                                  
PRINTDIALOG

For more information on the PrintDocument object, see the following section.

PRINTDOCUMENT

The PrintDocument component represents an object that will be printed. Your program can use this object to send output to a printer.

The general procedure for printing using this object is to create the object, set its properties to determine how the printout is generated (the printer's name, paper tray, and so forth), and then call the object's Print method.

When the object needs to generate a page of output, it raises its PrintPage event. Your code catches that event, draws the page, and then sets the event handler's e.HasMorePages value to indicate whether that was the last page of output. See the previous section, "PrintDialog," for a small example.

The PrintDocument object provides only a few important properties itself. You set most of the values that describe the printing operation using the PrinterSettings object referenced by the component's PrinterSettings property. See the previous section, "PrintDialog," for information on the PrinterSettings object.

In addition to its PrinterSettings property, the PrintDocument object provides a DocumentName property that determines the name displayed for the document in printing-related dialog boxes such as the printer queue display.

This component also provides an OriginAtMargins property that determines whether each page's graphical origin begins at the page's margins. Setting OriginAtMargins to True makes it easier to draw relative to the left and top margins, rather than the upper-left corner of the physical page.

PRINTPREVIEWCONTROL

The PrintPreviewControl control (and yes, the word Control is part of the control's name, possibly to differentiate it from the PrintPreviewDialog control) displays a print preview within one of your forms. Usually, it is easier to use the PrintPreviewDialog control described in the next section to display a print preview dialog box, but you can use this control to display a preview integrated into some other part of your application.

Example program UsePrintPreviewControl uses the following code to display three printed pages inside a PrintPreviewControl. The module-level variable m_PageNum indicates the next page that the pdocShapes PrintDocument component should draw. When it needs to generate a page, pdocShapes raises its PrintPage event. The event handler uses a Select Case statement to see which page it should generate and it draws an appropriate shape. It sets e.HasMorePages appropriately and increments the page number.

Public Class Form1
    ' The number of the current page.
    Private m_PageNum As Integer = 1

    ' Generate the print document.
    Private Sub pdocShapes_PrintPage(ByVal sender As System.Object,
     ByVal e As System.Drawing.Printing.PrintPageEventArgs) _
     Handles pdocShapes.PrintPage
        Select Case m_PageNum
            Case 1 ' Page 1. Draw a triangle.
                Dim pts() As Point = {
                    New Point(e.MarginBounds.X + e.MarginBounds.Width  2,
                              e.MarginBounds.Y),
                    New Point(e.MarginBounds.X + e.MarginBounds.Width,
                              e.MarginBounds.Y + e.MarginBounds.Height),
                    New Point(e.MarginBounds.X,
                              e.MarginBounds.Y + e.MarginBounds.Height)
                }
                e.Graphics.DrawPolygon(Pens.Red, pts)
                e.HasMorePages = True
                m_PageNum += 1
            Case 2 ' Page 2. Draw a rectangle.
                e.Graphics.DrawRectangle(Pens.Green, e.MarginBounds())
                e.HasMorePages = True
                m_PageNum += 1
Case 3 ' Page 3. Draw an ellipse.
                e.Graphics.DrawEllipse(Pens.Blue, e.MarginBounds())
                e.HasMorePages = False
                m_PageNum = 1
        End Select
    End Sub
End Class
                                                  
PRINTPREVIEWCONTROL

That's all the code that the program needs. When the program starts, the PrintPreviewControl control uses pdocShapes to generate the pages it needs and it displays them.

The following table describes some of the PrintPreviewControl control's most useful properties.

PROPERTY

PURPOSE

AutoZoom

Determines whether the control automatically adjusts its Zoom property to make the display fill the control.

Columns

The number of columns of pages that the control displays. In Figure G-7, Columns = 3.

Document

The PrintDocument object that the control previews.

Rows

The number of rows of pages that the control displays. In Figure G-7, Rows = 1.

StartPage

The page number (starting with 0) displayed in the control's first page. Your code can use this property to change the pages displayed.

UseAntiAlias

Determines whether the control uses the system's anti-aliasing features to smooth the preview image. Setting this to True may make the image smoother, but it may also slow down the display.

Zoom

Determines the size of the pages within the control. The value 1.0 is full size, 0.5 is half-size, 2.0 is double size, and so forth. It's usually easier to just set AutoZoom to True and let the control make the pages as large as possible. If you set the scale so large that the page(s) won't fit, the control adds scroll bars so the user can see the results.

The PrintPreviewDialog component lets you easily display a full-featured print preview dialog box.

Figure G.7. The PrintPreviewDialog component lets you easily display a full-featured print preview dialog box.

The control's InvalidatePreview method makes the control regenerate the print preview.

See the following section for information about the PrintPreviewDialog control. You can use that control to display a print preview without needing to build your own dialog.

PRINTPREVIEWDIALOG

The PrintPreviewDialog component displays a dialog box that shows what a print document will look like when it is printed. You can use this component to display a print preview dialog similar to the one shown in Figure G-7. This dialog box contains a PrintPreviewControl, plus some extra tools to let the user control the preview.

The tools that run from left to right across the top of the dialog box automatically give the user the following features:

  • A Print button that prints the document

  • A Zoom menu that lets the user zoom to scales between 10% and 500%, or to select Auto zoom

  • Buttons that make the dialog box display one, two, three, four, or six pages at a time

  • A button that closes the dialog box

  • A text box and numeric up/down control that let the user select the number of the page to display

The dialog box's most important property is Document. This property determines the PrintDocument object that the dialog box previews. See the section "PrintDocument" earlier in this appendix for more information about this class.

The component's most important methods are Show, which displays the dialog box, and ShowDialog, which displays the dialog box modally.

Using this component is remarkably simple. Set its Document property and catch the PrintDocument object's PrintPage event as shown in the previous section. Then display the dialog box as in the following code:

dlgPrintPreview.ShowDialog()

The rest is automatic. The dialog box lets the user move through the document's pages, zoom in and out, and even print the document.

PROCESS

The Process component provides access to the processes running on the computer. You can use this object to start, stop, and monitor processes. You can use the object to get information about a running process such as its threads, the modules it has loaded, and the amount of memory it is using.

The UseProcess example program, which is available for download on the book's web site, uses the following code to start an executable program. It creates a new Process object and sets values in its StartInfo property to define the application to run. This example sets the executable file name to the string contained in the txtFileName text box and sets the component's Verb to Open ("opening" an executable file makes it run). The program then calls the object's Start method.

' Start the process.
Private Sub btnRun_Click() Handles btnRun.Click
    Dim new_process As New Process
    new_process.StartInfo.FileName = txtFileName.Text
    new_process.StartInfo.Verb = "Open"
    new_process.Start()
End Sub
                                                  
PROCESS

The Process object's StartInfo property contains several values that tell the object how to start the new process. These values indicate whether the new process should be created without a window; what environment variables it should use; whether the new process's standard input, output, and error streams should be redirected; and the new process's working directory.

The Process object itself provides only a few properties at design time. Other than the StartInfo property, the most useful of these is EnableRaisingEvents. If this property is True, the component monitors the new process and raises an Exited event when the process ends.

At runtime, the Process object provides read-only StandardInput, StandardOutput, and StandardError properties that the program can use to interact with the new process. It also provides methods for reading and writing with these streams, and properties for monitoring the process. For example, it lets you learn about the process's working set size, paged memory size, and total processor time.

This is a fairly advanced and specialized topic, so it is not covered in greater detail here. For more information, see the Process component's web page at msdn.microsoft.com/system.diagnostics.process.aspx.

PROGRESSBAR

The ProgressBar control lets a program display a visible indication of its progress during a long task. As the task proceeds, the ProgressBar fills in from the left to the right. Ideally, the ProgressBar is completely full just as the task finishes.

The control's Minimum and Maximum properties determine the integers over which the ProgressBar control's values will range. When the control's Value property equals its Minimum property, the control is completely blank. When its Value property equals its Maximum property, the control is completely filled.

By default, Minimum and Maximum are set to 0 and 100, respectively, so the Value property indicates the percentage of the task that is complete. However, you can set Minimum and Maximum to any values that make sense for the application. For example, if a program must back up some data by copying 173 files from one directory to another, you could set these properties to 0 and 173. As it copies each file, the program would set the ProgressBar control's Value property to the number of files it has copied.

Instead of setting the control's Value property to indicate the task's status, you can set the Step property to indicate how much the control should update at each step. Then you can call the ProgressBar control's PerformStep method to increment the Value by that amount.

Note that the Minimum, Maximum, Value, and Step properties are all integers. If the value you want to display has some other data type (such as Double or TimeSpan), you must convert the values into integers before you use them with the ProgressBar.

PROPERTYGRID

The PropertyGrid control displays information about an object in a format similar to the one used by the Properties window at design time. The control lets the user organize the properties alphabetically or by category, and lets the user edit the property values. Figure G-8 shows a PropertyGrid displaying information about an Employee object.

The control's two most important properties are SelectedObject and SelectedObjects, which get or set the object(s) associated with the PropertyGrid.

The PropertyGrid control displays only object properties, not public variables. It also displays only properties that are browsable. If you give a property the Browsable(False) attribute, the PropertyGrid will not display it.

For more information, refer to the PropertyGrid class's web page at msdn.microsoft.com/system.windows.forms.propertygrid.aspx.

The PropertyGrid control displays an object's properties.

Figure G.8. The PropertyGrid control displays an object's properties.

RADIOBUTTON

A RadioButton control represents one of an exclusive set of options. For example, suppose that you want to let the user select between the choices Small, Medium, and Large. You could add three RadioButtons to a form with those captions. When the user clicks one button, Visual Basic selects it and deselects the others.

All the RadioButton controls within a particular container are part of the same RadioButton group. If the user clicks a RadioButton, Visual Basic automatically deselects the others in the same group.

If you want to make more than one group on the same form, you must place the controls in separate containers (such as GroupBox or Panel controls). For example, you could put the Small, Medium, and Large buttons in one GroupBox and then put the Red, Green, and Blue buttons in another GroupBox. Then, when the user selects a size button, the other size buttons are deselected, but the color buttons are unaffected. When the user selects a color, the other colors are deselected, but the size buttons are unaffected.

RadioButton groups provide special navigation for the user. If one of the buttons in the group has the focus, the user can press the arrow keys to move forward and backward through the group. If the user presses the Tab key, focus moves out of the group to the next control in the tab sequence.

The following table describes the RadioButton control's most useful properties.

PROPERTY

PURPOSE

Appearance

Determines whether the control displays with its default appearance of a selection circle containing a black dot (Appearance = Normal) or a raised button (Appearance = Button).

AutoCheck

Determines whether the control automatically selects itself when the user clicks it. If this is False, the code must check and uncheck the control and any other controls in the RadioButton group. Usually it's better to use a CheckBox control instead if you don't want the button to behave like a normal RadioButton.

CheckAlign

Determines whether the control's selection circle is positioned in the bottom center, top center, middle right, and so forth.

Checked

Determines whether the control is selected.

Image

Determines the image that the control displays.

ImageAlign

Determines whether the control's image is positioned in the bottom center, top center, middle right, and so forth.

Text

Determines the text that the control displays.

TextAlign

Determines whether the control's text is positioned in the bottom center, top center, middle right, and so forth.

The RadioButton control's most useful events are Click, which occurs when the user clicks the control, and CheckedChanged, which occurs when the control is checked or unchecked either because the user clicked a RadioButton in the group or because the code changed the button's state.

RICHTEXTBOX

The RichTextBox control is a text box that supports rich text extensions. Those extensions let the control display text that is bold, underlined, italicized, indented, in different fonts, and has other special visual properties.

The control can load and save its contents in plain-text files (in which case the formatting is lost) or in Rich Text Format (RTF) files (which preserve formatting).

A program can use the RichTextBox control's Select method to select some of its text. It can then use one of the control's properties to change the appearance of the selected text. For example, the following code selects the 10 characters starting with character 50 (the first character is number 0). It then sets the selection's color to red and makes its font bold.

rchNotes.Select(50, 10)
rchNotes.SelectionColor = Color.Red
rchNotes.SelectionFont = New Font(RichTextBox1.SelectionFont, FontStyle.Bold)

The following table lists the RichTextBox control's most useful properties.

PROPERTY

PURPOSE

AcceptsTab

For multiline controls, determines whether pressing the Tab key adds a Tab to the text, rather than moving to the next control in the tab sequence.

AutoSize

For single-line controls, determines whether the control automatically sets its height for the fonts it contains.

BulletIndent

Determines the number of pixels added after a bullet as indentation. If you make the selection a bulleted paragraph and then change this value, the paragraph's indentation is adjusted accordingly.

CanRedo

Indicates whether the control has any redo information that it can apply. See the discussion later in this section for an example.

CanUndo

Indicates whether the control has any undo information that it can apply. See the discussion later in this section for an example.

DetectUrls

Determines whether the control automatically recognizes web URLs when they are typed. If some text looks like a URL, the control displays it in blue, underlines it, and displays a hyperlink cursor (pointing hand) when the mouse hovers over the text. If the user clicks a recognized link, the control raises its LinkClicked event.

Lines

An array of strings giving the lines of text (separated by carriage returns) that are displayed by the control. You can use this property to give the control more than one paragraph at design time.

MaxLength

The maximum number of characters the user can enter into the control.

MultiLine

Determines whether the control displays multiple lines.

PreferredHeight

Returns the height a single-line control would want for the font size.

ReadOnly

Determines whether the user can modify the control's text.

RedoActionName

The name of the action that will be redone if the program calls the control's Redo method (for example, Typing or Delete). You can use this property to show the user what the next redo action is.

RightMargin

Determines the control's right margin in pixels. The value 0 means there is no right margin.

Rtf

Determines the RTF codes for the control's text. This includes the text itself, font information, and paragraph information (such as indentation, bulleting, and so forth).

ScrollBars

Determines which scroll bars the control displays. The values Horizontal, Vertical, and Both make the control display the corresponding scroll bars only when they are needed. The values ForcedHorizontal, ForcedVertical, and ForcedBoth make the control display the corresponding scroll bars always. The value None makes the control display no scroll bars. Note that some of these values may not always be honored. For example, if WordWrap is True or RightMargin is nonzero, the control never displays horizontal scroll bars.

SelectedRtf

Determines the selected text's value and RTF formatting code.

SelectedText

Determines the selected text's value without RTF formatting codes.

SelectionAlignment

Determines the selected text's alignment (Left, Center, or Right).

SelectionBullet

Determines whether the selected text's paragraph is bulleted.

SelectionCharOffset

Determines the selected text's character offset above or below the baseline in pixels.

SelectionColor

Determines the selected text's color.

SelectionFont

Determines the selected text's font.

SelectionHangingIndent

Determines the selected text's hanging indent.

SelectionIndent

Determines the number of pixels by which subsequent lines are indented in the selected text's paragraph.

SelectionLength

Determines the length of the selected text. You can use SelectionStart and SelectionLength to select text, or you can use the Select method.

SelectionProtected

Determines whether the selected text is protected so that the user cannot modify it.

SelectionRightIndent

Determines the number of pixels by which the selected text's paragraph is indented on the right.

SelectionStart

Determines the start of the selection. You can use SelectionStart and SelectionLength to select text, or you can use the Select method.

SelectionTabs

Determines the tabs for the selected text's paragraph. For example, the array {20, 40, 60} sets tabs 20, 40, and 60 pixels from the left margin.

ShowSelectionMargin

If True, the control adds a selection margin on the left. If the user clicks inside this margin, the control selects the text to the right.

Text

Determines the control's text, not including any formatting information. If you want to preserve formatting information, use the SelectedRtf property.

TextLength

Returns the length of the control's text.

UndoActionName

The name of the action that will be undone if the program calls the control's Undo method (for example, Typing or Delete). You can use this property to show the user what the next undo action is.

WordWrap

For multiline controls, determines whether the control wraps text to a new line if it is too long to fit.

The control also provides several important methods, as shown in the following table.

METHOD

PURPOSE

AppendText

Adds text to the end of the control's text.

CanPaste

Determines whether you can paste data of a specified format from the clipboard into the control.

Clear

Clears the control's text.

ClearUndo

Empties the control's undo list.

Copy

Copies the control's selection to the clipboard.

Cut

Copies the control's selection to the clipboard and removes it from the control's text.

Find

Finds and selects text. Overloaded versions let you search for one of a group of characters or a string, possibly with options (MatchCase, NoHighlight, Reverse, or WholeWord), and possibly within a range of characters.

GetCharFromPosition

Finds the character closest to a specified (X, Y) position.

GetCharIndexFromPosition

Finds the index of the character closest to a specified (X, Y) position.

GetLineFromCharIndex

Returns the number of the line containing the specified character index.

GetPositionFromCharIndex

Returns the (X, Y) position of the character at a specified index.

LoadFile

Loads an RTF or text file or a stream into the control.

Paste

Pastes the clipboard's contents into the control, replacing the current selection.

Redo

Reapplies the last action that was undone.

SaveFile

Saves the control's text into an RTF or text file or stream.

ScrollToCaret

Scrolls the text so the insertion position is visible.

Select

Selects the indicated text.

SelectAll

Selects all of the control's text.

Undo

Undoes the most recent action.

A program can use the CanUndo and CanRedo properties to determine when it should enable Undo and Redo buttons and menu items. The following code shows how a program can manage Undo and Redo buttons for the rchNotes control. When the control's contents change, the TextChanged event handler enables or disables the buttons, depending on which information the control has. The buttons simply call the control's Undo and Redo methods.

Private Sub rchNotes_TextChanged() Handles rchNotes.TextChanged
    btnUndo.Enabled = rchNotes.CanUndo
    btnRedo.Enabled = rchNotes.CanRedo
End Sub

Private Sub btnUndo_Click() Handles btnUndo.Click
    rchNotes.Undo()
End Sub

Private Sub btnRedo_Click() Handles btnRedo.Click
    rchNotes.Redo()
End Sub
                                                  
RICHTEXTBOX

The following version of the TextChanged event handler adds the values returned by the UndoActionName and RedoActionName methods to the buttons' captions. For example, after the user deletes some text, the undo button's caption says "Undo Delete."

Private Sub rchNotes_TextChanged() Handles rchNotes.TextChanged
    btnUndo.Enabled = rchNotes.CanUndo
    btnRedo.Enabled = rchNotes.CanRedo

    If btnUndo.Enabled Then
        btnUndo.Text = "Undo " & rchNotes.UndoActionName
    Else
        btnUndo.Text = "Undo"
    End If

    If btnRedo.Enabled Then
        If btnRedo.Enabled Then btnRedo.Text = "Redo " & rchNotes.RedoActionName
    Else
        If btnRedo.Enabled Then btnRedo.Text = "Redo"
    End If
End Sub
                                                  
RICHTEXTBOX

The RichTextBox control's most useful event is TextChanged. You can use this event to take action when the user changes the control's text. For example, you can display a visible indication that the data has been modified or, as the previous examples show, you can enable and disable Undo and Redo buttons.

SAVEFILEDIALOG

The SaveFileDialog component displays a dialog box that lets the user select a file for saving. The ShowDialog method returns DialogResult.OK if the user selects a file and clicks OK. It returns DialogResult.Cancel if the user cancels.

This component provides many properties for determining the kinds of files the user can specify. Most of these properties are the same as those provided by the OpenFileDialog component described earlier in this appendix. See the section "OpenFileDialog" earlier in this appendix for more information about those properties.

Unlike OpenFileDialog, this component does not provide the properties MultiSelect, ReadOnlyChecked, and ShowReadOnly because those properties don't make sense when the user is selecting a file for saving. The FileNames collection is also less useful for this component because the user will always select only one file, so you can use the FileName property instead.

The SaveFileDialog component provides one additional property not provided by the OpenFileDialog: CreatePrompt. If this property is True and the user enters the name of a file that doesn't exist, the dialog asks the user if it should create the file. If the user clicks No, the dialog box continues letting the user select a different file.

Like the OpenFileDialog, this component raises its FileOk event when the user tries to accept a file. You can use an event handler to catch the event and perform extra validation. Set the event's e.Cancel value to True to stop the dialog box from accepting the selection.

Note that the dialog box adds its default extension if applicable before it raises the FileOk event. If the component has DefaultExt = "dat" and AddExtension = True, this example would accept a file name with no extension.

SERIALPORT

The SerialPort component represents one of the computer's physical serial ports. It provides properties and methods for reading and configuring the port's baud rate, break signal, Data Set Ready (DSR) state, port name, parity, and stop bits. The class has methods to write data to the port and to read synchronously or asynchronously.

Serial communications is a fairly advanced and specialized topic that depends on your particular application, so it is not covered in detail here. See the online help at msdn.microsoft.com/system.io.ports.serialport.aspx for more information. You may also find these articles useful:

  • Programming Serial Ports Using Visual Basic 2005 (www.devx.com/dotnet/Article/31001)

  • RS232 Serial Communication in .NET (http://www.freevbcode.com/ShowCode.asp?ID=4666)

If you plan to work extensively with serial communication, you might want to find a good book on the topic such as Visual Basic Programmer's Guide to Serial Communications, 4th Edition by Richard Grier (Mabry Software, 2004).

Unfortunately all of these resources are fairly old but the basic concepts shouldn't have changed much in the last couple of Visual Basic releases.

SERVICECONTROLLER

The ServiceController component represents a Windows service process. It provides methods that let you connect to a running or stopped service to control it or get information about it.

The ServiceController component's ServiceName property gets or sets the name of the service associated with the component. To set this value at design time, select a ServiceController in the form designer. Then, click the ServiceName property in the Properties window and click the drop-down arrow on the right to see a list of available services on the system. The class's methods let you start, pause, continue, or stop the service.

Windows services and their control is a relatively advanced topic, so it is not covered in detail here. For more information, see the ServiceController class's web page at msdn.microsoft.com/system.serviceprocess.servicecontroller.aspx. For an introduction to Windows service applications, refer to msdn.microsoft.com/y817hyb6.aspx. For a walkthrough that creates a Windows service application, see msdn.microsoft.com/zt39148a.aspx.

SPLITCONTAINER

The SplitContainer control represents an area divided into two regions either vertically or horizontally. The control contains a bar (called the splitter) that the user can drag to adjust the amount of space given to each region.

Each of the SplitContainer control's regions holds a Panel control and you can place other controls inside the Panels. You can also use the Panel control's properties to affect their behavior. For example, you can set their AutoScroll properties to True so the Panels display scroll bars when their contents don't fit.

The following table describes the SplitContainer control's most useful properties.

PROPERTY

PURPOSE

BorderStyle

Determines the control's border style.

FixedPanel

Determines which panel keeps the same size when the control is resized.

IsSplitterFixed

Determines whether the user can drag the splitter.

Orientation

Determines whether the Panels are arranged vertically or horizontally.

Panel1

Returns a reference to the first panel (left or top depending on Orientation).

Panel1Collapsed

Determines whether the first Panel is collapsed. When collapsed, a Panel is completely hidden and the user cannot get it back by dragging the splitter.

Panel1MinSize

Determines the minimum size (width or height depending on Orientation) of the first Panel.

Panel2

Returns a reference to the second panel (right or bottom depending on Orientation).

Panel2Collapsed

Determines whether the second Panel is collapsed. When collapsed, a Panel is completely hidden and the user cannot get it back by dragging the splitter.

Panel2MinSize

Determines the minimum size (width or height depending on Orientation) of the second Panel.

SplitterDistance

Determines the distance from the control's left or top edge (depending on Orientation) to the splitter.

SplitterIncrement

Determines the number of pixels by which the splitter will move when dragged. For example, if SplitterIncrement is 10, the splitter jumps in 10-pixel increments are you drag it. The default is 1.

SplitterRectangle

Returns a Rectangle representing the splitter's current size and location within the SplitContainer.

SplitterWidth

Determines the splitter's width in pixels. The default is 4.

The SplitterContainer control's most interesting events are SplitterMoving and SplitterMoved. You can catch these events if you need to take action when the user drags the splitter. You can also use the Panel controls' sizing events Resize, ResizeBegin, ResizeEnd, and SizeChanged to take action when the Panel controls resize.

One rather confusing feature of the SplitterContainer is the way its contained Panel controls behave in the form designer. The drop-down list at the top of the Properties window lets you select the controls on the form, including the SplitterContainer. The Panel controls are contained inside the SplitterContainer, so they are not always listed in this dropdown. If you click one of the Panel controls, the dropdown lists the Panel and the Properties window lets you view and edit the control's properties. If some other control is selected, however, the SplitterContainer is listed in the dropdown, but not its Panel controls.

SPLITTER

The Splitter control provides the thin strip that users can grab to resize the two panes of a SplitContainer. In addition to using the Splitter within a SplitContainer control, you can also use it directly to separate any two other controls.

Visual Basic uses the Dock properties and stacking order of the two controls and the Splitter to determine how the Splitter behaves. To build a simple vertical splitter between two Panel controls, add the first Panel to the form and set its Dock property to Left so that it fills the left side of the form. Next, add a Splitter control. By default, its Dock property is also Left, so it attaches to the right side of the Panel. Finally, add a second Panel control, and set its Dock property to Fill so that it fills the rest of the form. Now, when you drag the Splitter back and forth, Visual Basic adjusts the Panel controls accordingly.

You can use multiple Splitters to separate more than two controls. For example, you could add a Panel with Dock set to Left, a Splitter, another Panel with Dock set to Left, another Splitter, and a final Panel with Dock set to Fill. This would let the user divide the form between the three Panel controls.

The Splitter control uses the controls' stacking order to determine the order of the controls. When you initially create controls, their stacking order is the same as their order of creation. Unfortunately, if the stacking order changes, the positions of the controls can become very confusing very quickly. In some cases, it's easier to delete all of the controls and start over than it is to fix the stacking order.

It's far easier to use the SplitContainer control than it is to use Splitters directly, so you should use the SplitContainer when you have fairly straightforward needs. Only use Splitters directly if you need to provide unusual configurations such as dividing a form among three Panel controls.

STATUSSTRIP

The StatusStrip control provides an area where the application can display brief status information, usually at the bottom of the form.

The StatusStrip can contain several kinds of objects such as drop-down buttons, progress bars, and panels. These objects are represented by different kinds of controls contained in the form. For example, a progress bar is represented by a ToolStripProgressBar control.

You can edit a StatusStrip much as you edit a MenuStrip. When you click the StatusStrip, a box appears that contains the text "Type Here." Enter the text that you want to display on this object and press Enter. Click an object and then click the little action arrow on the object's right edge to change the object's type (progress bar, panel, and so forth) and to configure the item.

You can also edit an object's properties in the Properties window. Simply click the object and then use the Properties window to change its appearance.

The StatusStrip control provides access to the objects it contains through its Items collection. If you click the ellipsis to the right of this property in the Properties window, the Items Collection Editor appears. To make new items, select the type of object you want to add from the editor's dropdown and click the Add button. Click an item and use the other buttons to move or delete it. Use the properties grid on the editor's right to modify the object's appearance.

The following list shows the types of objects you can add to a StatusStrip control:

  • ToolStripStatusLabel ā€” A simple label.

  • ToolStripProgressBar ā€” A Progress bar.

  • ToolStripDropDownButton ā€” A button that displays text in the StatusStrip. When you click its drop-down arrow, a list of buttons appears.

  • ToolStripSplitButton ā€” A button that displays an image in the StatusStrip. When you click its drop-down arrow, a list of buttons appears.

See the online help at msdn.microsoft.com/system.windows.forms.statusstrip.aspx for more information about these classes and the StatusStrip control.

TABCONTROL

The TabControl control (for some reason, the word Control is part of the class's name) displays a series of tabs attached to separate pages. Each page is a control container, holding whatever controls you want for that tab. When you click a tab at design time or the user clicks one at runtime, the control displays the corresponding page.

The control's tabs are represented programmatically by TabPage objects contained in the control's TabPages collection. To edit these objects at design time, select the control's TabPages property and click the ellipsis on the right to display the collection editor.

The following table describes the TabPage object's most useful properties.

PROPERTY

PURPOSE

AutoScroll

If True, the tab page automatically provides scroll bars if it is not big enough to display all of its contents.

BackColor

Determines the tab page's background color. This affects the tab's page, not the tab itself.

BackgroundImage

Determines the background image that tiles the tab's page. This affects the tab's page, not the tab itself.

BorderStyle

Determines the style of border around the tab's page. This can be None, FixedSingle, or Fixed3D.

Font

Determines the font used by the controls contained in the tab's page. To change the font used to draw the tabs, set the TabControl control's Font property.

ImageIndex

If the TabControl control's ImageList property is set to an ImageList control, this property determines the image within that list that the tab displays.

Text

Determines the text displayed on the tab.

ToolTipText

Determines the tooltip text displayed when the user hovers the mouse over the tab. This is ignored unless the TabControl control's ShowToolTips property is True.

The TabPage object provides several events of its own. These include the usual assortment of events for a control container such as Click, Layout, Resize, Paint, and various mouse events.

The TabControl provides several properties that are useful for arranging the tabs. The following table describes the most useful of these properties.

PROPERTY

PURPOSE

Alignment

Determines whether the control places its tabs on the Top, Bottom, Left, or Right. If you set this to Left or Right, the control rotates its tabs' text sideways. If a tab contains an image, the image is not rotated.

Appearance

Determines how the control displays its tabs. This property can take the value Normal, Buttons, or FlatButtons.

DrawMode

Determines whether the control draws the tabs automatically (DrawMode = Normal) or whether the code draws them (DrawMode = OwnerDrawFixed). See the discussion later in this section for an example.

Enabled

Determines whether the TabControl is enabled. If Enabled is False, none of the tabs will respond to the user (although the tabs do not look disabled) and all of the controls on the tab pages are disabled.

Font

Determines the font that the control uses to draw its tabs. This does not affect the font used within the tab pages.

HotTrack

If this is True, the tabs visually change when the mouse moves over them. For example, the tabs' text may change color.

ImageList

Determines the ImageList control that provides images for the tabs.

ItemSize

Determines the height of all of the tabs. Also determines the width of fixed-width tabs (see the SizeMode property) and owner-drawn tabs (see the DrawMode property).

MultiLine

Determines whether the control allows more than one line of tabs. If MultiLine is False and the tabs won't all fit, the control displays left-arrow and right-arrow buttons on the right to let the user scroll through the tabs.

Padding

Determines the horizontal and vertical space added around the tabs' text and images.

RowCount

Returns the current number of tab rows.

SelectedIndex

Sets or gets the index of the currently selected tab. At design time, you can simply click the tab you want to select.

SelectedTab

Sets or gets the currently selected TabPage object. At design time, you can simply click the tab you want to select.

ShowToolTips

Determines whether the control displays the TabPage controls' ToolTip values when the user hovers the mouse over the tabs.

SizeMode

Determines how the control sizes its tabs. This property can take the values Normal (tabs fit their contents), FillToRight (if the control needs more than one row of tabs, the tabs resize so each row fills the width of the control), and Fixed (all tabs have the same width).

TabCount

Returns the number of tabs.

TabPages

The collection of TabPage objects.

The TabControl control's most useful event is SelectedIndexChanged, which fires when the control's selected tab index changes either because the user clicked a new tab, or because the code set the SelectedIndex or SelectedTab property.

If you set the TabControl control's DrawMode property to OwnerDrawFixed, your code must draw the tabs in the control's DrawItem event. Example program UseTabControlOwnerDrawn uses the following code to draw colored ellipses on its tabs:

' Draw ellipses in the tabs.
Private Sub tabProject_DrawItem(ByVal sender As Object,
 ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles tabProject.DrawItem
    ' Decide how thick to draw the outline.
    Dim line_wid As Integer = 1
    If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
        line_wid = 3
    End If

    ' Get the drawing bounds.
    Dim rect As New Rectangle(
        e.Bounds.Left + (line_wid + 1)  2,
        e.Bounds.Top + (line_wid + 1)  2 + 1,
        e.Bounds.Width-line_wid - 2,
        e.Bounds.Height-line_wid - 2)

    ' Get the fill colors.
    Dim fill_colors() As Color = {Color.Red, Color.Green, Color.Blue}

    ' Fill.
    Using the_brush As New SolidBrush(fill_colors(e.Index))
        e.Graphics.FillEllipse(the_brush, rect)
    End Using

    ' Outline.
    Using the_pen As New Pen(Color.Black, line_wid)
        e.Graphics.DrawEllipse(the_pen, rect)
    End Using
End Sub
                                                  
TABCONTROL

The DrawItem event handler starts by setting the line_wid variable to the pen width it will use to draw the ellipse. It makes the line width larger for the selected tab.

The code then builds a rectangle to define the ellipse. It starts with the event handler's e.Bounds property and then shrinks the area slightly to make room for the ellipse's border.

The code makes a brush of the appropriate color for each tab and fills the ellipse. It finishes by making a black pen of the correct thickness and outlining the ellipse.

The TabControl is ideal for displaying multiple pages of related information in a limited amount of space. It works particularly well when the information is naturally categorized and each tab represents a category of data. It doesn't work as well if different tabs contain data that the user might want to compare to each other.

TABLELAYOUTPANEL

The TableLayoutPanel control displays the controls that it contains in rows and columns. This makes it easy to build grids of regularly spaced controls.

The following table describes the TableLayoutPanel control's most useful properties.

PROPERTY

PURPOSE

AutoScroll

Determines whether the control automatically provides scroll bars if the controls it contains won't fit.

CellBorderStyle

Determines the cell border style. This can be None, NotSet (an appropriate style is selected based on the row and column styles), Inset (single sunken line), InsetDouble (double sunken line), Outset (single raised line), OutsetDouble (double raised line), OutsetPartial (single line containing a raised area), and Single (single line).

ColumnCount

Determines the number of columns.

ColumnStyles

A collection giving column styles.

ColumnWidths

An array of column widths.

Controls

A collection of controls contained within the control.

Enabled

Determines whether the control is enabled. If the TableLayoutPanel is disabled, the controls it contains are also disabled.

GrowStyle

Determines how the control grows when you add new child controls to it. This can be AddRows, AddColumns, or FixedSize (the control throws an exception if you add more controls).

RowCount

Determines the number of rows.

RowHeights

An array of row heights.

RowStyles

A collection of row styles.

Visible

Determines whether the control and its contents are visible.

The following table describes the TableLayoutPanel control's most useful methods.

METHOD

PURPOSE

GetColumn

Returns a child control's column number.

GetColumnSpan

Returns the number of columns that a child control spans.

GetRow

Returns a child control's row number.

GetRowSpan

Returns the number of rows that a child control spans.

ScrollControlIntoView

If the TableLayoutPanel control has AutoScroll set to True, this scrolls an indicated child control into view.

SetColumn

Sets a child control's column number.

SetColumnSpan

Sets a child control's column span.

SetRow

Sets a child control's row number.

SetRowSpan

Sets a child control's row span.

In addition to providing its own properties, the TableLayoutPanel acts as a property provider for its child controls. These properties include Column, ColumnSpan, Row, and RowSpan. For example, if you add a button to the TableLayoutPanel control named TableLayoutPanel1, the button's Properties window will contain an entry labeled "Column on TableLayoutPanel1" that determines the button's column.

The TableLayoutPanel control also changes the meaning of its child controls' Anchor property. By default, a child control has Anchor property set to None, so it is centered in its table cell. If you set Anchor to Left, the control is moved to the left edge of the cell. If you set Anchor to "Left, Right," both of the control's edges are attached to the cell's edges, so the control stretches to fit the cell's width. The Top and Bottom Anchor settings work similarly.

The FlowLayoutPanel control also arranges contained controls, but not in a grid. Instead it places controls one after another to fill either rows or columns. For information on that control, see the section "FlowLayoutPanel" earlier in this appendix.

TEXTBOX

The TextBox control is a typical everyday text box. The user can enter and modify text, click and drag to select text, press Ctrl+C to copy the selected text to the clipboard, and so forth.

The TextBox control is much simpler than the RichTextBox control described earlier in this appendix. It can use only one font, background color, and foreground color for all of its text. It also cannot provide special formatting such as bullets, hanging indentation, and margins the way the RichTextBox control can. If you need those extra features, use a RichTextBox instead of a TextBox control.

The following table describes the TextBox control's most useful properties.

PROPERTY

PURPOSE

AcceptsReturn

For multiline controls, determines whether pressing the Enter key adds a new line to the text rather than triggering the form's Accept button.

AcceptsTab

For multiline controls, determines whether pressing the Tab key adds a Tab to the text rather than moving to the next control in the tab sequence.

AutoSize

For single-line controls, determines whether the control automatically sets its height for the fonts it contains.

CharacterCasing

Determines whether the control automatically changes the case of text as it is entered. This property can take the values Normal (leave the case alone), Upper (uppercase), and Lower (lowercase). The control changes the text's case whether the user types or pastes it into the control, or if the program sets the control's text.

Lines

An array of strings giving the lines of text (separated by carriage returns) displayed by the control. You can use this property to give the control more than one paragraph at design time.

MaxLength

The maximum number of characters the user can enter into the control.

MultiLine

Determines whether the control displays multiple lines.

PasswordChar

Determines the password character displayed by a single-line TextBox control for each character it contains. For example, if you set PasswordChar to *, each character the user types appears as a * in the text box. The control's Text property returns the actual text to the program.

PreferredHeight

Returns the height a single-line control would want to use for the font size.

ReadOnly

Determines whether the user can modify the control's text. You can display read-only text in a label, but then the user cannot select it and copy it to the clipboard. If you want to display information that the user might want to copy, place it in a TextBox control and set ReadOnly to True.

ScrollBars

Determines which scroll bars the control displays. This property can take the values None, Vertical, Horizontal, and Both. The appropriate scroll bars are always displayed, although they are disabled when they are not needed. Note that some of these values may not always be honored. For example, if WordWrap is True, the control never displays horizontal scroll bars.

SelectedText

Gets or sets the selected text's value.

SelectionLength

Gets the length of the selected text, or selects this number of letters. You can use SelectionStart and SelectionLength to select text, or you can use the Select method.

SelectionStart

Gets or sets the start of the selection. You can use SelectionStart and SelectionLength to select text, or you can use the Select method.

Text

Gets or sets the control's text.

TextAlign

Determines the text's alignment within the control. This can be Left, Right, or Center.

TextLength

Returns the length of the control's text.

WordWrap

For multiline controls, determines whether the control wraps text to a new line if it is too long to fit.

The TextBox control also provides several important methods, described in the following table.

METHOD

PURPOSE

AppendText

Adds text to the end of the control's text.

Clear

Clears the control's text.

ClearUndo

Empties the control's undo list.

Copy

Copies the control's selection to the clipboard.

Cut

Copies the control's selection to the clipboard and removes it from the control's text.

Paste

Pastes the clipboard's contents into the control, replacing the current selection. This method does nothing if the clipboard doesn't contain textual data.

ScrollToCaret

Scrolls the text so the insertion position is visible.

Select

Selects the indicated text.

SelectAll

Selects all of the control's text.

Undo

Undoes the most recent action. The TextBox stores information for only one undo action, so calling Undo again undoes the undo. That also means that the TextBox doesn't need a Redo method because it would do the same thing as Undo.

The TextBox control's most useful event is TextChanged. You can use this event to take action when the user changes the control's text. For example, you can display a visible indication that the data has been modified.

TIMER

The Timer component periodically raises a Tick event so the program can take action at specific intervals.

The component's Interval property determines the number of milliseconds (1000ths of a second) between events. This property is a 32-bit integer that must be greater than zero, so it can hold values between 1 and 2,147,483,647. If you set Interval to its maximum value, the component raises its Tick event roughly every 24.86 days.

The Timer component's Enabled property determines whether the Timer generates Tick events. The component continues raising its event as long as Enabled is True.

The component's Start and Stop methods simply set its Enabled property to True and False, respectively.

TOOLSTRIP

The ToolStrip control displays a series of buttons, dropdowns, and other tools. The user can access these tools quickly without navigating through a series of menus, so they are most useful for performing frequently needed tasks. Menus are more appropriate for commands that are needed less often.

The following list shows the types of items that a ToolStrip may contain:

ToolStripButton

ToolStripProgressBar

ToolStripComboBox

ToolStripSeparator

ToolStripDropDownButton

ToolStripSplitButton

ToolStripLabel

ToolStripTextBox

These tools are relatively straightforward. ToolStripButton is a button that sits on a ToolStrip, ToolStripComboBox is a combo box that sits on a ToolStrip, and so forth.

The only tool that doesn't correspond to another type of control is the SplitButton. This control is a button with a drop-down area. If the user clicks the button, it raises a Click event. If the user clicks the drop-down arrow, the control displays a drop-down menu containing menu items that the user can select as usual. See the online help at msdn.microsoft.com/system.windows.forms.toolstrip.aspx for more information on SplitButton and the other tool control classes.

The ToolStrip control stores its tools in its Items collection. At runtime, a program can access the controls inside this collection, or it can refer to the tools directly by name. At design time, you can select a ToolStrip, click its Items property in the Properties window, and click the ellipsis to the right to display an Items Collection Editor.

You can also click the ToolStrip and add items to it much as you edit a MenuStrip control.

The following table describes the ToolStrip control's most useful properties.

PROPERTY

PURPOSE

AllowItemReorder

Determines whether the user can drag and drop items to reorder them.

AllowMerge

Determines whether the ToolStrip can merge with others.

CanOverflow

Determines whether items can be sent to an overflow menu if the ToolStrip doesn't fit completely on the form.

GripDisplayStyle

Gets the orientation of the control's move handle.

GripMargin

Determines the space around the control's move handle.

GripRectangle

Gets the boundaries of the control's move handle.

GripStyle

Determines whether the control's move handle is visible or hidden.

Items

Returns a collection of ToolStripItem objects representing the control's tools.

OverflowButton

Returns a ToolStripItem representing the control's overflow button.

ShowItemToolTips

Determines whether the control's tools display their tooltips.

TOOLSTRIPCONTAINER

The ToolStripContainer control contains a ToolStripPanel along each of its edges where a ToolStrip control can dock. The control's center is filled with another ToolStripPanel that can contain other controls that are not part of the tool strips.

The user can drag the ToolStrips around and position them inside of any of the ToolStripPanel controls much as you can move the toolbars in the Visual Basic development environment. The user can drag the ToolStrips into multiple rows or columns within the panels.

Figure G-9 shows a form containing a ToolStripContainer with its Dock property set to Fill, so it fills the form. The lighter area in the middle is a PictureBox sitting inside the middle ToolStripPanel, also with its Dock property set to Fill.

The ToolStripContainer control lets the user rearrange ToolStrip controls at runtime.

Figure G.9. The ToolStripContainer control lets the user rearrange ToolStrip controls at runtime.

The ToolStripContainer in Figure G-9 holds five ToolStrip controls positioned in the container's various edge panels. Each ToolStrip contains a label identifying the ToolStrip. The ToolStrip3 control's TextDirection property is set to Vertical90, so it sits along the right edge of the form. The ToolStrip1 and ToolStrip2 controls have been dragged into two rows at the top of the form. The ToolStrip1 and ToolStrip2 controls share a row at the bottom.

The ToolStripContainer control's LeftToolStripPanel, RightToolStripPanel, TopToolStripPanel, BottomToolStripPanel, and ContentPanel properties contain references to the ToolStripPanel controls that the control contains. Its LeftToolStripPanelVisible, RightToolStripPanelVisible, TopToolStripPanelVisible, and BottomToolStripPanelVisible properties let you show or hide specific panels. For example, you can hide the bottom or side panels if you don't want the user to drag ToolStrips there.

The ToolStripContainer control's other properties are relatively straightforward. See the online help at msdn.microsoft.com/system.windows.forms.toolstripcontainer.aspx for more information.

TOOLTIP

The ToolTip component allows you to provide tooltip help when the user hovers the mouse over another control. After you add a ToolTip component to a form, the other controls on the form get a special ToolTip property. For example, suppose that you create a ToolTip component named ttHint. Then a button on the form would have a new property named "ToolTip on ttHint." Set that property to the text you want the ToolTip to display, and you are all set.

The following table describes the ToolTip component's most useful properties.

PROPERTY

PURPOSE

Active

Determines whether the component displays tooltips.

AutomaticDelay

Sets the AutoPopDelay, InitialDelay, and ReshowDelay properties to values that are appropriate for this value.

AutoPopDelay

The number of milliseconds before the tooltip disappears if the mouse remains stationary in the tooltip's area.

BackColor

Determines the tooltip's background color.

ForeColor

Determines the tooltip's foreground color.

InitialDelay

The number of milliseconds that the mouse must remain stationary inside the tooltip's area before the component displays the tooltip.

IsBalloon

Determines whether the tooltip is displayed as a balloon rather than a rectangle.

OwnerDraw

Determines whether your code will draw the tooltip. If you set this to True, catch the ToolTip component's Draw method and draw the tooltip. Parameters to the method give the Graphics object to use, the bounds of the area to draw, and the tooltip text. This property is ignored if IsBalloon is True.

ReshowDelay

The number of milliseconds before the next tooltip will display when the mouse moves from one tooltip area to another. The idea is that subsequent tooltips display more quickly if one is already visible.

ShowAlways

Determines whether the component still displays tooltips, even if the form does not have the focus. The mouse still must hover over the tooltip area as usual if ShowAlways is True.

StripAmpersands

Determines whether the component removes ampersand characters from tooltip text. This can be useful if the tooltip text looks like menu and label captions where ampersands are converted into underscores.

UseAnimation

Determines whether animation effects are used to show and hide the tooltip.

UseFading

Determines whether fading effects are used to show and hide the tooltip.

The ToolTip component's SetToolTip method lets a program associate a tooltip with a control at runtime. The following code adds tooltip text to several address controls:

ttHint.SetToolTip(txtFirstName, "Customer first name")
ttHint.SetToolTip(txtLastName, "Customer last name")
ttHint.SetToolTip(txtStreet, "Mailing address street number and name")
ttHint.SetToolTip(txtCity, "Mailing address city")
ttHint.SetToolTip(cboState, "Mailing address state")
ttHint.SetToolTip(txtZip, "Mailing address ZIP code")

The following table lists the ToolTip component's most useful methods.

METHOD

PURPOSE

GetToolTip

Returns a control's associated tooltip text.

RemoveAll

Removes all tooltip text associated with this ToolTip component.

SetToolTip

Sets a control's associated tooltip text. Set the text to Nothing or an empty string to remove that control's tooltip text.

Show

Displays a tooltip over a specific control. Different overloaded versions let you specify the tooltip's location and duration.

TRACKBAR

The TrackBar control allows the user to drag a pointer along a bar to select a numeric value. This control is very similar to a horizontal scroll bar, but with a different appearance.

The following table describes the control's most useful properties.

PROPERTY

PURPOSE

AutoSize

Determines whether the control automatically sets its height or width, depending on its Orientation property. For example, if the control's orientation is horizontal, setting AutoSize to True makes the control pick a height that is appropriate for the control's width.

LargeChange

The amount by which the control's value changes when the user clicks the TrackBar, but not on its pointer.

Maximum

The largest value that the user can select.

Minimum

The smallest value that the user can select.

Orientation

Determines the control's orientation. This can be Horizontal or Vertical.

SmallChange

The amount by which the control's value changes when the user presses an arrow key.

TickFrequency

The number of values between tick marks on the control.

TickStyle

Determines the position of tick marks on the control. This can be TopLeft (on the top if Orientation is Horizontal; on the left if Orientation is Vertical), BottomRight (on the bottom if Orientation is Horizontal; on the right if Orientation is Vertical), Both, or None.

Value

The control's current numeric value.

The control's Value, Minimum, Maximum, and TickFrequency properties are integer values, so the TrackBar control is not ideal for letting the user select a nonintegral value such as 1.25. (You can multiply the values by 100 to get finer grained resolution but the user still can't select truly nonintegral values.)

The control's Scroll event fires when the user changes the control's value interactively. The ValueChanged event occurs when the control's value changes either because the user changed it interactively or because the program changed it with code.

TREEVIEW

The TreeView control displays a hierarchical data set graphically, as shown in Figure G-10.

The TreeView control uses TreeNode objects to represent the items it contains. The control's Nodes collection contains references to the top-level objects called its root nodes. In Figure G-10, the R & D and Sales & Support items are the root nodes.

The TreeView control displays hierarchical data graphically.

Figure G.10. The TreeView control displays hierarchical data graphically.

Each TreeNode object has a Nodes collection of its own that contains references to its child nodes. For example, in Figure G-10 the R & D root node has children labeled Engineering and Test. Each of those nodes has child nodes representing employees.

You can assign each of the TreeNode objects an icon to display. In Figure G-10, the nodes display images representing factories, workgroups, and people.

Your program can manipulate the TreeNode objects at runtime, but you can also edit the tree data at design time. Select the TreeView control, select its Nodes property in the Properties window, and click the ellipsis to the right to make Visual Basic display the TreeNode Editor.

Click Add Root to add a new root node to the tree. Select a node and click Add Child to give the node a new child. Select a node and click Delete to remove the node and any descendants it contains.

If the TreeView control's ImageList property is set to an ImageList control, you can set a node's ImageIndex property to the index of the image in the ImageList that the node should display. Set the node's SelectedImageIndex to the index of the image that the control should display when the node is selected.

The following table describes the TreeView control's most useful properties.

PROPERTY

PURPOSE

BorderStyle

Determines the control's border style.

CheckBoxes

Determines whether the control displays check boxes next to the nodes.

DrawMode

Determines whether your code draws nothing (the default), the nodes' text, or the nodes' text and lines.

FullRowSelect

Determines whether selection highlights span the whole width of the control.

HideSelection

Determines whether the selected node remains visibly highlighted even when the TreeView control loses the focus.

HotTracking

Determines whether node labels look like hyperlinks when the mouse moves over them.

ImageIndex

Determines the default image index for the nodes.

ImageList

Determines the ImageList control that contains the images used by the nodes.

Indent

Determines the indentation distance for each level in the tree.

ItemHeight

Determines the height of each node.

LabelEdit

Determines whether the user can edit the nodes' labels.

LineColor

Determines the color of the lines connecting the nodes.

Nodes

Returns the collection of tree nodes.

PathSeparator

Determines the delimiter string used to represent paths in the tree. For example, using the default separator , the path to the first person in Figure G-10 is "R & DEngineeringCameron, Charlie."

Scrollable

Determines whether the control displays scroll bars when necessary.

SelectedImageIndex

Determines the default image index for the selected nodes.

SelectedNode

Determines the currently selected node.

ShowLines

Determines whether the control draws lines connecting the nodes.

ShowNodeToolTips

Determines whether the control displays tooltips when the mouse hovers over a node. Use the TreeNode objects' ToolTipText properties to set the tooltip text.

ShowPlusMinus

Determines whether the control displays plus and minus signs next to tree nodes. The user can click the plus and minus signs or double-click the nodes to expand and collapse them.

ShowRootLines

Determines whether the control draws lines between the root nodes. In Figure G-10, ShowRootLines is True.

Sorted

Determines whether the control displays the nodes in sorted order.

TopNode

Returns the first node that is currently completely visible.

VisibleCount

Returns the number of nodes that could be fully visible. Fewer nodes may actually be visible if some are collapsed.

The TreeView control provides several methods that let your code manage the data at runtime. The following table describes the most useful of these methods.

METHOD

PURPOSE

CollapseAll

Collapses all of the control's nodes.

ExpandAll

Expands all of the control's nodes. In the process, the control scrolls down, so the last node is visible and selects the topmost visible control. To select some other control, such as the topmost root node, set the control's SelectedNode property as in:

trvOrgChart.SelectedNode = trvOrg.Nodes(0)

GetNodeAt

Returns the TreeNode object at a specific (X, Y) location.

GetNodeCount

Returns the number of the tree's nodes. If the method's includeSubTrees parameter is False, the routine returns only the number of root nodes. If includeSubTrees is True, the routine returns the total number of nodes in the tree.

The control provides a series of events that fire before and after the user takes certain actions. For example, when the user clicks a node's check box, the control raises its BeforeCheck event, changes the node's checked state, and then raises its AfterCheck event. The other actions that have similar Before and After event handlers are Collapse, Expand, LabelEdit, and Select.

Each of the Before event handlers provides a parameter that the code can set to cancel the event. For example, the UseTreeView example program, which is available for download on the book's web site, uses the following code to prevent the user from editing the labels of the tree's root nodes:

Private Sub trvOrgChart_BeforeLabelEdit(ByVal sender As Object,
 ByVal e As System.Windows.Forms.NodeLabelEditEventArgs) _
 Handles trvOrgChart.BeforeLabelEdit
    e.CancelEdit = Not e.Node.FullPath.Contains(trvOrgChart.PathSeparator)
End Sub
                                                  
The TreeView control displays hierarchical data graphically.

When the user tries to edit a node's label, the BeforeLabelEdit event fires. The value e.Node represents the node that the user is about to edit. Its FullPath property returns a delimited path showing the node's position in the tree.

The code searches this path for the path separator character (normally ). If the node is a root node, the separator is not in the path so the Contains method returns False and the code sets e.CancelEdit to True so the edit never occurs. If Contains finds the path separator in the node's FullPath, the code sets e.CancelEdit to False so the edit takes place as usual.

The TreeNode object also provides properties and methods if its own. The following table describes the TreeNode object's most useful properties.

PROPERTY

PURPOSE

Checked

Determines whether the node is checked, assuming that the TreeView control's CheckBoxes property is True.

FirstNode

Returns the node's first child node.

FullPath

Returns a string representing the node and its ancestors in the tree, delimited by the character specified by the TreeView control's PathSeparator property.

ImageIndex

Determines the index of the node's image in the ImageList control specified by the TreeView control's ImageList property.

Index

Returns the node's index within its parent node's collection of children.

IsEditing

Indicates whether the user is editing the node's label.

IsExpanded

Indicates whether the node is expanded.

IsSelected

Indicates whether the node is selected.

IsVisible

Indicates whether the node is at least partly visible.

LastNode

Returns the node's last child node.

Level

Returns the node's level in the tree. Root nodes have level 0, their children have level 1, the children of those nodes have level 2, and so forth.

NextNode

Returns the node's next sibling node.

NextVisibleNode

Returns the next node that is not hidden because of a collapse. This may be a sibling, child, or some other node, depending on which nodes are expanded at the time. Note that this node may lie below the visible scrolling area, so it may not really be visible.

NodeFont

The font used to draw the node's text. If the node's font makes the text bigger than the TreeView control's Font property does, the text is clipped.

Nodes

The collection of this node's child nodes.

Parent

Returns a reference to the node's parent node in the tree.

PrevNode

Returns the node's previous sibling node.

PrevVisibleNode

Returns the previous node that is not hidden because of a collapse. This may be a sibling, parent, or some other node, depending on which nodes are expanded at the time. Note that this node may be above the visible scrolling area, so it may not really be visible.

SelectedImageIndex

Determines the index of the node's selected image in the ImageList control specified by the TreeView control's ImageList property. The node displays this image while it is selected.

Text

Determines the text displayed in the node's label.

ToolTipText

Determines the node's tooltip text.

TreeView

Returns a reference to the TreeView control that contains the node.

The TreeNode object also provides several methods. The following table describes the most useful of these.

METHOD

PURPOSE

BeginEdit

Begins editing of the node's label. This raises an error if the TreeView control's LabelEdit property is False.

Clone

Copies the node and its entire subtree.

Collapse

Collapses the node's subtree.

EndEdit

Ends editing of the node's label.

EnsureVisible

Expands nodes and scrolls the TreeView as necessary to ensure that the node is visible.

Expand

Expands the node to display its children.

ExpandAll

Expands the node's whole subtree.

GetNodeCount

Returns the number of child nodes.

Remove

Removes the node and its subtree.

Toggle

Toggles the node between expanded and collapsed.

VSCROLLBAR

The VScrollBar control is similar to the HScrollBar control, except that it is oriented vertically instead of horizontally. See the section "HScrollBar" earlier in this appendix for more information on the control.

WEBBROWSER

The WebBrowser control displays the contents of web pages, XML documents, text files, and other documents understood by the browser. The control can automatically follow links that the user clicks in the document and provides a standard web browser context menu, containing commands such as Back, Forward, Save Background As, and Print.

Using this control, you can easily add Web-based hypertext to your applications. For example, you could display an HTML help system or tutorial pages within the control.

The control provides several properties and methods for navigating to different documents. The following table describes the most useful of these.

PROPERTY/METHOD

PURPOSE

Url

Gets or sets the control's current web address.

Navigate

Makes the control open a specific URL.

GoBack

Makes the control move to the URL it previously displayed.

GoForward

After a call to GoBack, makes the control move forward to the next URL it displayed.

GoHome

Makes the control go to the current user's home page.

GoSearch

Makes the control go to the current user's search page.

Whenever the control moves to a new document, it fires three events. The Navigating event fires before the control moves to the new document. The Navigated event occurs after the control has navigated to the new document and is loading it. The DocumentCompleted event occurs when the control has finished loading the new document.

The control also supports a variety of other events that tell a program when something has changed. Some of the more useful of these notification events include CanGoBackChanged, CanGoForwardChanged, DocumentTitleChanged, NewWindow (the browser is about to open a new window), ProgressChanged (gives progress information on the download of a document), and StatusTextChanged.

After the control loads a document, the program can manipulate the document through the control's Document property. This property contains a reference to an HtmlDocument object that gives access to the document's images, forms, links, and other HTML document elements.

In addition to opening existing documents, a program can make the WebBrowser display a file generated within the application by setting its DocumentText or DocumentStream properties.

The WebBrowser control provides all of the power and flexibility of Internet Explorer. Unfortunately, that power and flexibility makes the control quite complicated, so it is not described further here. Refer to the online help at msdn.microsoft.com/system.windows.forms.webbrowser.aspx for more information.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.104.160