- •Using Your Sybex Electronic Book
- •Acknowledgments
- •Contents at a Glance
- •Introduction
- •Who Should Read This Book?
- •How About the Advanced Topics?
- •The Structure of the Book
- •How to Reach the Author
- •The Integrated Development Environment
- •The Start Page
- •Project Types
- •Your First VB Application
- •Making the Application More Robust
- •Making the Application More User-Friendly
- •The IDE Components
- •The IDE Menu
- •The Toolbox Window
- •The Solution Explorer
- •The Properties Window
- •The Output Window
- •The Command Window
- •The Task List Window
- •Environment Options
- •A Few Common Properties
- •A Few Common Events
- •A Few Common Methods
- •Building a Console Application
- •Summary
- •Building a Loan Calculator
- •How the Loan Application Works
- •Designing the User Interface
- •Programming the Loan Application
- •Validating the Data
- •Building a Math Calculator
- •Designing the User Interface
- •Programming the MathCalculator App
- •Adding More Features
- •Exception Handling
- •Taking the LoanCalculator to the Web
- •Working with Multiple Forms
- •Working with Multiple Projects
- •Executable Files
- •Distributing an Application
- •VB.NET at Work: Creating a Windows Installer
- •Finishing the Windows Installer
- •Running the Windows Installer
- •Verifying the Installation
- •Summary
- •Variables
- •Declaring Variables
- •Types of Variables
- •Converting Variable Types
- •User-Defined Data Types
- •Examining Variable Types
- •Why Declare Variables?
- •A Variable’s Scope
- •The Lifetime of a Variable
- •Constants
- •Arrays
- •Declaring Arrays
- •Initializing Arrays
- •Array Limits
- •Multidimensional Arrays
- •Dynamic Arrays
- •Arrays of Arrays
- •Variables as Objects
- •So, What’s an Object?
- •Formatting Numbers
- •Formatting Dates
- •Flow-Control Statements
- •Test Structures
- •Loop Structures
- •Nested Control Structures
- •The Exit Statement
- •Summary
- •Modular Coding
- •Subroutines
- •Functions
- •Arguments
- •Argument-Passing Mechanisms
- •Event-Handler Arguments
- •Passing an Unknown Number of Arguments
- •Named Arguments
- •More Types of Function Return Values
- •Overloading Functions
- •Summary
- •The Appearance of Forms
- •Properties of the Form Control
- •Placing Controls on Forms
- •Setting the TabOrder
- •VB.NET at Work: The Contacts Project
- •Anchoring and Docking
- •Loading and Showing Forms
- •The Startup Form
- •Controlling One Form from within Another
- •Forms vs. Dialog Boxes
- •VB.NET at Work: The MultipleForms Project
- •Designing Menus
- •The Menu Editor
- •Manipulating Menus at Runtime
- •Building Dynamic Forms at Runtime
- •The Form.Controls Collection
- •VB.NET at Work: The DynamicForm Project
- •Creating Event Handlers at Runtime
- •Summary
- •The TextBox Control
- •Basic Properties
- •Text-Manipulation Properties
- •Text-Selection Properties
- •Text-Selection Methods
- •Undoing Edits
- •VB.NET at Work: The TextPad Project
- •Capturing Keystrokes
- •The ListBox, CheckedListBox, and ComboBox Controls
- •Basic Properties
- •The Items Collection
- •VB.NET at Work: The ListDemo Project
- •Searching
- •The ComboBox Control
- •The ScrollBar and TrackBar Controls
- •The ScrollBar Control
- •The TrackBar Control
- •Summary
- •The Common Dialog Controls
- •Using the Common Dialog Controls
- •The Color Dialog Box
- •The Font Dialog Box
- •The Open and Save As Dialog Boxes
- •The Print Dialog Box
- •The RichTextBox Control
- •The RTF Language
- •Methods
- •Advanced Editing Features
- •Cutting and Pasting
- •Searching in a RichTextBox Control
- •Formatting URLs
- •VB.NET at Work: The RTFPad Project
- •Summary
- •What Is a Class?
- •Building the Minimal Class
- •Adding Code to the Minimal Class
- •Property Procedures
- •Customizing Default Members
- •Custom Enumerations
- •Using the SimpleClass in Other Projects
- •Firing Events
- •Shared Properties
- •Parsing a Filename String
- •Reusing the StringTools Class
- •Encapsulation and Abstraction
- •Inheritance
- •Inheriting Existing Classes
- •Polymorphism
- •The Shape Class
- •Object Constructors and Destructors
- •Instance and Shared Methods
- •Who Can Inherit What?
- •Parent Class Keywords
- •Derived Class Keyword
- •Parent Class Member Keywords
- •Derived Class Member Keyword
- •MyBase and MyClass
- •Summary
- •On Designing Windows Controls
- •Enhancing Existing Controls
- •Building the FocusedTextBox Control
- •Building Compound Controls
- •VB.NET at Work: The ColorEdit Control
- •VB.NET at Work: The Label3D Control
- •Raising Events
- •Using the Custom Control in Other Projects
- •VB.NET at Work: The Alarm Control
- •Designing Irregularly Shaped Controls
- •Designing Owner-Drawn Menus
- •Designing Owner-Drawn ListBox Controls
- •Using ActiveX Controls
- •Summary
- •Programming Word
- •Objects That Represent Text
- •The Documents Collection and the Document Object
- •Spell-Checking Documents
- •Programming Excel
- •The Worksheets Collection and the Worksheet Object
- •The Range Object
- •Using Excel as a Math Parser
- •Programming Outlook
- •Retrieving Information
- •Recursive Scanning of the Contacts Folder
- •Summary
- •Advanced Array Topics
- •Sorting Arrays
- •Searching Arrays
- •Other Array Operations
- •Array Limitations
- •The ArrayList Collection
- •Creating an ArrayList
- •Adding and Removing Items
- •The HashTable Collection
- •VB.NET at Work: The WordFrequencies Project
- •The SortedList Class
- •The IEnumerator and IComparer Interfaces
- •Enumerating Collections
- •Custom Sorting
- •Custom Sorting of a SortedList
- •The Serialization Class
- •Serializing Individual Objects
- •Serializing a Collection
- •Deserializing Objects
- •Summary
- •Handling Strings and Characters
- •The Char Class
- •The String Class
- •The StringBuilder Class
- •VB.NET at Work: The StringReversal Project
- •VB.NET at Work: The CountWords Project
- •Handling Dates
- •The DateTime Class
- •The TimeSpan Class
- •VB.NET at Work: Timing Operations
- •Summary
- •Accessing Folders and Files
- •The Directory Class
- •The File Class
- •The DirectoryInfo Class
- •The FileInfo Class
- •The Path Class
- •VB.NET at Work: The CustomExplorer Project
- •Accessing Files
- •The FileStream Object
- •The StreamWriter Object
- •The StreamReader Object
- •Sending Data to a File
- •The BinaryWriter Object
- •The BinaryReader Object
- •VB.NET at Work: The RecordSave Project
- •The FileSystemWatcher Component
- •Properties
- •Events
- •VB.NET at Work: The FileSystemWatcher Project
- •Summary
- •Displaying Images
- •The Image Object
- •Exchanging Images through the Clipboard
- •Drawing with GDI+
- •The Basic Drawing Objects
- •Drawing Shapes
- •Drawing Methods
- •Gradients
- •Coordinate Transformations
- •Specifying Transformations
- •VB.NET at Work: Plotting Functions
- •Bitmaps
- •Specifying Colors
- •Defining Colors
- •Processing Bitmaps
- •Summary
- •The Printing Objects
- •PrintDocument
- •PrintDialog
- •PageSetupDialog
- •PrintPreviewDialog
- •PrintPreviewControl
- •Printer and Page Properties
- •Page Geometry
- •Printing Examples
- •Printing Tabular Data
- •Printing Plain Text
- •Printing Bitmaps
- •Using the PrintPreviewControl
- •Summary
- •Examining the Advanced Controls
- •How Tree Structures Work
- •The ImageList Control
- •The TreeView Control
- •Adding New Items at Design Time
- •Adding New Items at Runtime
- •Assigning Images to Nodes
- •Scanning the TreeView Control
- •The ListView Control
- •The Columns Collection
- •The ListItem Object
- •The Items Collection
- •The SubItems Collection
- •Summary
- •Types of Errors
- •Design-Time Errors
- •Runtime Errors
- •Logic Errors
- •Exceptions and Structured Exception Handling
- •Studying an Exception
- •Getting a Handle on this Exception
- •Finally (!)
- •Customizing Exception Handling
- •Throwing Your Own Exceptions
- •Debugging
- •Breakpoints
- •Stepping Through
- •The Local and Watch Windows
- •Summary
- •Basic Concepts
- •Recursion in Real Life
- •A Simple Example
- •Recursion by Mistake
- •Scanning Folders Recursively
- •Describing a Recursive Procedure
- •Translating the Description to Code
- •The Stack Mechanism
- •Stack Defined
- •Recursive Programming and the Stack
- •Passing Arguments through the Stack
- •Special Issues in Recursive Programming
- •Knowing When to Use Recursive Programming
- •Summary
- •MDI Applications: The Basics
- •Building an MDI Application
- •Built-In Capabilities of MDI Applications
- •Accessing Child Forms
- •Ending an MDI Application
- •A Scrollable PictureBox
- •Summary
- •What Is a Database?
- •Relational Databases
- •Exploring the Northwind Database
- •Exploring the Pubs Database
- •Understanding Relations
- •The Server Explorer
- •Working with Tables
- •Relationships, Indices, and Constraints
- •Structured Query Language
- •Executing SQL Statements
- •Selection Queries
- •Calculated Fields
- •SQL Joins
- •Action Queries
- •The Query Builder
- •The Query Builder Interface
- •SQL at Work: Calculating Sums
- •SQL at Work: Counting Rows
- •Limiting the Selection
- •Parameterized Queries
- •Calculated Columns
- •Specifying Left, Right, and Inner Joins
- •Stored Procedures
- •Summary
- •How About XML?
- •Creating a DataSet
- •The DataGrid Control
- •Data Binding
- •VB.NET at Work: The ViewEditCustomers Project
- •Binding Complex Controls
- •Programming the DataAdapter Object
- •The Command Objects
- •The Command and DataReader Objects
- •VB.NET at Work: The DataReader Project
- •VB.NET at Work: The StoredProcedure Project
- •Summary
- •The Structure of a DataSet
- •Navigating the Tables of a DataSet
- •Updating DataSets
- •The DataForm Wizard
- •Handling Identity Fields
- •Transactions
- •Performing Update Operations
- •Updating Tables Manually
- •Building and Using Custom DataSets
- •Summary
- •An HTML Primer
- •HTML Code Elements
- •Server-Client Interaction
- •The Structure of HTML Documents
- •URLs and Hyperlinks
- •The Basic HTML Tags
- •Inserting Graphics
- •Tables
- •Forms and Controls
- •Processing Requests on the Server
- •Building a Web Application
- •Interacting with a Web Application
- •Maintaining State
- •The Web Controls
- •The ASP.NET Objects
- •The Page Object
- •The Response Object
- •The Request Object
- •The Server Object
- •Using Cookies
- •Handling Multiple Forms in Web Applications
- •Summary
- •The Data-Bound Web Controls
- •Simple Data Binding
- •Binding to DataSets
- •Is It a Grid, or a Table?
- •Getting Orders on the Web
- •The Forms of the ProductSearch Application
- •Paging Large DataSets
- •Customizing the Appearance of the DataGrid Control
- •Programming the Select Button
- •Summary
- •How to Serve the Web
- •Building a Web Service
- •Consuming the Web Service
- •Maintaining State in Web Services
- •A Data-Driven Web Service
- •Consuming the Products Web Service in VB
- •Summary
DESIGNING IRREGULARLY SHAPED CONTROLS 421
The code also compares the current date/time to the setting of the m_AlarmTime property, and if the difference is negative, it means that the alarm must go off. If so, it raises the TimeOut event.
Designing Irregularly Shaped Controls
With VB.NET it’s quite easy to create irregularly shaped controls. It’s possible to create irregularly shaped forms too, but, unlike irregularly shaped controls, an irregularly shaped form is still quite uncommon. By the way, you can also create semitransparent forms with VB.NET—if you can come up with a good reason to do so.
To change the default shape of a custom control, you must use the Region object. This is another graphics-related object that specifies a closed area. You can even use Bezier curves to make highly unusual and smooth shapes for your controls. In this section, we’ll do something less ambitious: We’ll create controls with the shape of an ellipse, as shown in Figure 9.9.
Figure 9.9
Two instances of an ellipse-shaped control
You can turn any control to any shape you like by creating the appropriate Region object and then applying it to the Region property of the control. This must take place from within the control’s Load event. Listing 9.17 shows the statements that change the shape of the control.
Listing 9.17: Creating a Non-Rectangular Control
Private Sub RoundButton_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load
Dim G As Graphics
G = Me.CreateGraphics
Dim roundPath As New GraphicsPath()
Dim R As New Rectangle(0, 0, Me.Width, Me.Height) roundPath.AddEllipse(R)
Me.Region = New Region(roundPath) Me.CreateGraphics.DrawEllipse(New Pen(Color.DarkGray, 3), R)
End Sub
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
422 Chapter 9 BUILDING CUSTOM WINDOWS CONTROLS
First, we retrieve the Graphics object of the UserControl object and store it in the G variable. Then we create a GraphicsPath, the roundPath object, and add an ellipse to it. The ellipse is based on the rectangle that encloses the ellipse. The R object is used temporarily to specify the ellipse. The new path is then used to create a Region object, which is assigned to the Region property of the UserControl object. This gives our control the shape of an ellipse. The last statement draws an ellipse with the dark gray pen around the perimeter of the control. This step is optional, but it’s equivalent to adding a border to the control.
To demonstrate the design of an irregularly shaped control, we’ll build the RoundButton control, which was shown in Figure 9.9 earlier. You can find this control along with its test form in the NonRectangular project on the CD. The most important section of the control’s code is the Load event handler, which was shown in Listing 9.17.
Irregularly shaped controls are used in fancy interfaces, and they usually react to movement of the mouse. The control of Figure 9.9 changes its background color and caption when the mouse is over the control. Listing 9.18 shows the code behind the control’s MouseEnter and MouseLeave events. When the mouse enters the control’s area (this is detected by the control automatically—you won’t have to write a single line of code for it), the currentState variable is set to Active, the control’s background color to green, and its caption to “Play.” Similar actions take place in the control’s MouseLeave event handler: the control’s background color changes to red and its caption to “Pause”. In addition, each time the control switches state (from Pause to Play or vice versa), one of the NowPlaying and NowPausing events is fired.
Listing 9.18: The RoundButton Control’s MouseEnter and MouseLeave Events
Private Sub RoundButton_MouseEnter(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.MouseEnter If currentState = State.Active Then
Me.BackColor = Color.Green currentCaption = “Play” RaiseEvent NowPlaying()
End If End Sub
Private Sub RoundButton_MouseLeave(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.MouseLeave If currentState = State.Active Then
Me.BackColor = Color.Red currentCaption = “Pause” RaiseEvent NowPausing()
End If End Sub
These two events set up the appropriate variables, and the drawing of the control takes place in the OnPaint method, which is shown in Listing 9.19.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
DESIGNING IRREGULARLY SHAPED CONTROLS 423
Listing 9.19: The RoundButton Control’s OnPaint Method
Protected Overrides Sub OnPaint(ByVal pe As PaintEventArgs) Dim roundPath As New GraphicsPath()
Dim R As New Rectangle(0, 0, Me.Width, Me.Height) roundPath.AddEllipse(R)
Me.Region = New Region(roundPath) pe.Graphics.DrawEllipse(New Pen(Color.DarkGray, 3), R) Dim fnt As Font
If currentState = State.Active Then
If Me.BackColor.Equals(Color.Silver) Then Me.BackColor = Color.Green fnt = New Font(“Verdana”, 24, FontStyle.Bold)
Else
fnt = New Font(“Verdana”, 14, FontStyle.Regular) End If
Dim X As Integer = (Me.Width - pe.Graphics.MeasureString( _ currentCaption, fnt).Width) / 2
Dim Y As Integer = (Me.Height - pe.Graphics.MeasureString( _ currentCaption, fnt).Height) / 2
pe.Graphics.DrawString(currentCaption, fnt, Brushes.White, X, Y) End Sub
The OnPaint method uses graphics methods to center the string on the control. They’re the same methods we used in the example of the user-drawn control, earlier in this chapter. The drawing methods are discussed in detail in Chapter 14.
The code makes use of the currentState variable, which can take on two values: Active and Inactive. These two values are members of the State enumeration, which is shown next:
Public Enum State
Active
Inactive
End Enum
The control can be in two states. In the Active state, it behaves as described. In the Inactive state, the control turns gray and doesn’t respond to the movement of the mouse. In addition, its caption becomes “Resume” and the user can switch between states by clicking the control. The control’s click event handler is shown next:
Private Sub RoundButton_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Click If currentState = State.Active Then
currentState = State.Inactive Me.BackColor = Color.Silver currentCaption = “Resume”
Else
currentState = State.Active currentCaption = “Play”
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
424 Chapter 9 BUILDING CUSTOM WINDOWS CONTROLS
End If
Me.Invalidate()
End Sub
The code changes the control’s state and, when the control is switched to the Inactive state, it fills it with a gray shade. To restore the control to its Active state, the user must click the control again.
The test form of the project shows how the RoundButton control behaves on a form. You can use the techniques described in this section to make a series of round controls to emulate the look of VCR controls. When the mouse hovers over the control, you can display the icon of the button (Play, Pause, Resume, and so on). When the mouse moves outside the area of the control, you can display the same icon with washed-out colors. Or you can place a nice colored dot on the control, which will be green when the button is pressed and red when it’s released.
The control raises two events to notify the application that its state has changed. The two event names must be declared outside any procedure with the following statements:
Public Event NowPlaying()
Public Event NowPausing()
The two events are raised from within the MouseEnter and MouseLeave event handlers with the following statements:
RaiseEvent NowPlaying()
RaiseEvent NowPaused()
To test these events, switch to the test form and enter the following statements in the two event handlers of the RoundButton control. They’re two simple statements that display the control’s current status on the form’s title bar. They simply demonstrate how to capture the changes in the control’s status and use it in the host application to control other activities:
Private Sub RoundButton1_NowPlaying() Handles RoundButton1.NowPlaying
Me.Text = “Playing...”
End Sub
Private Sub RoundButton1_NowPausing() Handles RoundButton1.NowPausing
Me.Text = “Paused...”
End Sub
In Chapter 14, you’ll learn more about shapes and paths, and you may wish to experiment with other oddly shaped controls. How about a progress indicator control that looks like a thermometer?
Building Owner-Drawn Controls
In this section, I’ll show a couple of examples that demonstrate how to customize existing controls. You’re not going to build new custom controls in this section; actually, you’ll hook custom code into certain events of a control to direct the rendering of the control. Some of the .NET Windows controls can be customized far more than it is possible through their properties. These are the listlike controls (menus, ListBox controls), and they allow you to supply your own code for drawing each item. Using this technique, you can create a menu with a separate font for each menu item, a ListBox control with alternating background colors, and so on. You can even put bitmaps on the
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |