Microsoft Visual FoxPro 6. 0 Programmer's Guide 1998

While Visual FoxPro still supports standard procedural programming, new extensions to the language give you the power and flexibility of object-oriented programming.

Object-oriented design and object-oriented programming represent a change in focus from standard procedural programming. Instead of thinking about program flow from the first line of code to the last line of code, you need to think about creating objects: self-contained components of an application that have private functionality as well as functionality that you can expose to the user.

This chapter discusses:

Understanding Objects in Visual FoxPro

In Visual FoxPro, forms and controls are objects that you include in your applications. You manipulate these objects through their properties, events, and methods.

The object-oriented Visual FoxPro language extensions provide you with a great deal of control over the objects in your applications. These extensions also make it easier to create and maintain libraries of reusable code, giving you:

Object-oriented programming is largely a way of packaging code so that it can be reused and maintained more easily. The primary package is called a class.

Classes and Objects:

The Building Blocks of Applications

Classes and objects are closely related, but they are not the same. A class contains information about how an object should look and behave. A class is the blueprint or schematic of an object. The electrical schematic and design layout of a telephone, for example, would approximate a class. The object, or an instance of the class, would be a telephone.

The class determines the characteristics of the object.

Objects Have Properties

An object has certain properties, or attributes. For example, a phone is a certain color and size. When you put a phone in your office, it has a certain position on your desk. The receiver can be on or off the hook.

Objects you create in Visual FoxPro also have properties that are determined by the class the object is based on. These properties can be set at design time or at run time.

For example, some of the properties that a check box can have are listed in the following table:

Property Description
Caption The descriptive text beside the check box.
Enabled Specifies whether the check box can be chosen by a user.
ForeColor The color of the caption text.
Left The position of the left side of the check box.
MousePointer How the mouse pointer looks when over the check box.
Top The position of the top of the check box.
Visible Specifies whether the check box is visible.

Objects Have Associated Events and Methods

Each object recognizes and can respond to certain actions called events. An event is a specific and predetermined activity, initiated by either a user or the system. Events, in most cases, are generated by user interaction. For example, with a phone, an event is triggered when a user takes the receiver off the hook. Events are also triggered when the user presses the buttons to make a call.

In Visual FoxPro, user actions that trigger events include clicks, mouse moves, and key presses. Initializing an object and encountering a line of code that causes an error are system-initiated events.

Methods are procedures that are associated with an object. Methods are different from normal Visual FoxPro procedures: methods are inextricably bound with an object and are called differently than normal Visual FoxPro procedures are called.

Events can have methods associated with them. For example, if you write method code for the Click event, that code is executed when the Click event occurs. Methods can also exist independently of any events. These methods must be explicitly called in code.

The event set, while extensive, is fixed. You can t create new events. The method set, however, is infinitely extendible.

The following table lists some of the events associated with a check box:

Event Description
Click User clicks the check box.
GotFocus User selects the check box by clicking it or tabbing to it.
LostFocus User selects another control.

The following table lists some of the methods associated with a check box:

Method Description
Refresh The value of the check box is updated to reflect any changes that may have occurred to the underlying data source.
SetFocus The focus is set to the check box just as though the user had pressed the TAB key until the check box was selected.

See Chapter 4, Understanding the Event Model, for a discussion of the order in which events occur.

Understanding Classes in Visual FoxPro

All of the properties, events, and methods for an object are specified in the class definition. In addition, classes have the following characteristics that make them especially useful for creating reusable, easily maintained code:

Hiding Unnecessary Complexity

When you include a phone in your office, you probably don t care how the phone internally receives a call, initiates or terminates connections to electronic switchboards, or translates key presses into electronic signals. All you need to know is that you can lift the receiver, dial the appropriate numbers, and talk to the person you want to talk to. The complexity of making that connection is hidden. The benefit of being able to ignore the inner details of an object so you can focus on the aspects of the object you need to use is called abstraction.

Internal complexity can be hidden.

Encapsulation, which involves packaging method and property code together in an object, contributes to abstraction. For example, the properties that determine the items in a list box and the code that executes when you choose an item in the list can be encapsulated in a single control that you add to a form.

Leveraging the Power of Existing Classes

A subclass can have all the functionality of an existing class, plus any additional controls or functionality you want to give it. If your class is a basic telephone, you can have subclasses that have all the functionality of the original telephone and any specialized features you want to give them.

Subclassing allows you to reuse code.

Subclassing is one way to decrease the amount of code you have to write. Start with the definition of an object that is close to what you want, and customize it.

Streamlining Code Maintenance

With inheritance, if you make a change to a class, that change is reflected in all subclasses based on the class. This automatic update saves you time and effort. For example, if a phone manufacturer wanted to change from dial to push-button style phones, it would save a lot of work to be able to make the change to the master schematic and have all previously manufactured phones based on that master schematic automatically inherit this new feature, rather than having to add the new feature to all the existing phones individually.

Inheritance makes maintaining your code easy.

Inheritance doesn t work with hardware, but you do have this capability in software. If you discover a bug in your class, instead of having to go to each subclass and change the code, you fix it once in the class and the change propagates throughout all subclasses of the class.

The Visual FoxPro Class Hierarchy

When you are creating user-defined classes, it helps to understand the Visual FoxPro class hierarchy.

The Visual FoxPro class hierarchy

Containers and Non-Containers

The two primary types of Visual FoxPro classes, and by extension Visual FoxPro objects, are container classes and control classes.

Container and Control Classes

Container Classes

Containers can contain other objects and allow access to the objects contained within them. For example, if you create a container class that consists of two list boxes and two command buttons, and then add an object based on this class to a form, each individual object can be manipulated at run time and design time. You can easily change the positions of the list boxes or the captions of the command buttons. You can also add objects to the control at design time; for example, you can add labels to identify the list boxes.

The following table lists what each container class can contain:

Container Can contain
Command button groups Command buttons
Container Any controls
Control Any controls
Custom Any controls, page frame, container, custom
Form sets Forms, toolbars
Forms Page frames, any controls, containers, custom
Grid columns Headers and any objects except form sets, forms, toolbars, timers, and other columns
Grids Grid columns
Option button groups Option buttons
Page frames Pages
Pages Any controls, containers, custom
Project Files, servers
Toolbars Any controls, page frame, container

Control Classes

Control classes are more completely encapsulated than container classes are, but can be less flexible for that reason. Control classes do not have an AddObject method.

Matching the Class to the Task

You want to be able to use classes in many different contexts. Smart planning will enable you to most effectively decide what classes to design and what functionality to include in the class.

Deciding When to Create Classes

You could create a class for every control and every form you might ever use, but this isn t the most effective way to design your applications. You ll likely end up with multiple classes that do much the same thing but must be maintained separately.

Encapsulate Generic Functionality

You can create a control class for generic functionality. For example, command buttons that allow a user to move the record pointer in a table, a button to close a form, and a help button, can all be saved as classes and added to forms any time you want the forms to have this functionality.

You can expose properties and methods on a class so that the user can integrate them into the particular data environment of a form or form set.

Provide a Consistent Application Look and Feel

You can create form set, form, and control classes with a distinctive appearance so that all the components of your application have the same look. For example, you could add graphics and specific color patterns to a form class and use that as a template for all forms you create. You could create a text box class with a distinctive appearance, such as a shadowed effect, and use this class throughout your application any time you want to add a text box.

Deciding What Type of Class to Create

Visual FoxPro allows you to create several different kinds of classes, each with its own characteristics. You specify the type of class you want to create in the New Class dialog box or in the AS clause in the CREATE CLASS command.

The Visual FoxPro Base Classes

You can create subclasses of most of the Visual FoxPro base classes in the Class Designer.

Visual FoxPro Base Classes

ActiveDoc Custom Label PageFrame
CheckBox EditBox Line ProjectHook
Column* Form ListBox Separator
CommandButton FormSet OLEBoundControl Shape
CommandGroup Grid OLEContainerControl Spinner
ComboBox Header* OptionButton* TextBox
Container Hyperlink Object OptionGroup Timer
Control Image Page* ToolBar

* These classes are an integral part of a parent container and cannot be subclassed in the Class Designer.

All Visual FoxPro base classes recognize the following minimum set of events:

Event Description
Init Occurs when the object is created.
Destroy Occurs when the object is released from memory.
Error Occurs whenever an error occurs in event or method procedures of the class.

All Visual FoxPro base classes have the following minimum set of properties:

Property Description
Class What type of class it is.
BaseClass The base class it was derived from, such as Form, Commandbutton, Custom, and so on.
ClassLibrary The class library the class is stored in.
ParentClass The class that the current class was derived from. If the class was derived directly from a Visual FoxPro base class, the ParentClass property is the same as the BaseClass property.

Extending the Visual FoxPro Base Classes

You can subclass these classes to set your own default control properties. For example, if you want the default names of controls you add to forms in your applications to automatically reflect your naming conventions, you can create classes based on the Visual FoxPro base classes to do this. You can create form classes with a customized look or behavior to serve as templates for all the forms you create.

You could also subclass the Visual FoxPro base classes to create controls with encapsulated functionality. If you want a button to release forms when the button is clicked, you can create a class based on the Visual FoxPro command button class, set the caption property to Quit and include the following command in the Click event:

THISFORM.Release

You can add this new button to any form in your application.

Customized command button added to a form

Creating Controls with Multiple Components

Your subclasses aren t limited to single base classes. You can add multiple controls into a single container class definition. Many of the classes in the Visual FoxPro sample class library fall into this category. For example, the VCR class in Buttons.vcx, located in the Visual Studio \Samples\Vfp98\Classes directory, contains four command buttons for navigating the records in a table.

Creating Non-Visual Classes

A class based on the Visual FoxPro custom class doesn t have a run-time visual element. You can create methods and properties for your custom class using the Class Designer environment. For example, you could create a custom class named StrMethods and include a number of methods to manipulate character strings. You could add this class to a form with an edit box and call the methods as needed. If you had a method called WordCount, you could call it when needed:

THISFORM.txtCount.Value = ; THISFORM.StrMethods.WordCount(THISFORM.edtText.Value)

Non-visual classes (like the custom control and the timer control) have a visual representation only at design time in the Form Designer. Set the picture property of the custom class to the .bmp file you want displayed in the Form Designer when the custom class is added to a form.

Creating Classes

You can create new classes in the Class Designer and you can see how each object will appear to the user as you design it.

To create a new class

The New Class dialog box lets you specify what to call the new class, the class to base the new class on, and the library to store it in.

Creating a new class

Modifying a Class Definition

Once you have created a class, you can modify it. Changes made to a class affect all the subclasses and all the objects based on this class. You can add an enhancement to a class or fix a bug in the class, and all the subclasses and objects based on the class will inherit the change.

To modify a class in the Project Manager

  1. Select the class you want to modify.

  2. Choose Modify.

    The Class Designer opens.

You can also modify a visual class definition with the MODIFY CLASS command.

Important   Don t change the Name property of a class if the class is already being used in any other application components. Otherwise, Visual FoxPro will not be able to locate the class when needed.

Subclassing a Class Definition

You can create a subclass of a user-defined class in one of two ways.

To create a subclass of a user-defined class

  1. In the New Class dialog box, click the dialog button to the right of the Based On box.

  2. In the Open dialog box, choose the class you want to base the new class on.

    -or-

Using the Class Designer

When you specify what class your new class is based on and the library to store the class in, the Class Designer opens.

Class Designer

The Class Designer provides the same interface that the Form Designer does, allowing you to see and edit the properties of your class in the Properties window. Code editing windows allow you to write code to be executed when events occur or methods are called.

Adding Objects to a Control or Container Class

If you base the new class on the control or container class, you can add controls to it the same way you add controls in the Form Designer: choose the control button on the Form Controls toolbar and drag to size in the Class Designer.

No matter what type of class you base the new class on, you can set properties and write method code. You can also create new properties and methods for the class.

Adding Properties and Methods to a Class

You can add as many new properties and methods to the new class as you want. Properties hold values; methods hold procedural code to be run when you call the method.

Creating New Properties and Methods

When you create new properties and methods for classes, the properties and methods are scoped to the class, not to individual components in the class.

To add a new property to a class

  1. From the Class menu, choose New Property.

  2. In the New Property dialog box, type the name of the property.

  3. Specify the visibility: Public, Protected, or Hidden.

    A Public property can be accessed anywhere in your application. Protected and Hidden properties and methods are discussed in Protecting and Hiding Class Members later in this chapter.

    New Property dialog box

  4. Choose Add.

    You can also include a description of the property that will be displayed at the bottom of the Properties window in the Class Designer and in the Form Designer when the control is added to a form.

Troubleshooting   When you add a property to a class that can be set by a user of the class, the user could enter an invalid setting for your property that could cause run-time errors. You need to explicitly document the valid settings for the property. If your property can be set to 0, 1, or 2, for example, say so in the Description box of the New Property dialog box. You might also want to verify the value of the property in code that references it.

To create an array property

The array property is read-only at design time and is displayed in the Properties window in italics. The array property can be managed and redimensioned at run time. For an example of using an array property, see Managing Multiple Instances of a Form in Chapter 9, Creating Forms.

To add a new method to a class

  1. From the Class menu, choose New Method.

  2. In the New Method dialog box, type the name of the method.

  3. Specify the visibility: Public, Protected, or Hidden.

  4. Select the Access check box to create an Access method, select the Assign check box to create an Assign method, or select both check boxes to create Access and Assign methods.

Access and Assign methods let you execute code when the value of a property is queried or when you attempt to change the property s value.

The code in an Access method is executed when the value of a property is queried, typically by using the property in an object reference, storing the value of the property to a variable, or displaying the value of property with a question mark (?).

The code in an Assign method is executed when you attempt to change the value of a property, typically by using the STORE or = command to assign a new value to the property.

For more information about Access and Assign methods, see Access and Assign Methods.

You can also include a description of the method.

Protecting and Hiding Class Members

Properties and methods in a class definition are Public by default: code in other classes or procedures can set the properties or call the methods. Properties and methods that you designate as Protected can be accessed only by other methods in the class definition or in subclasses of the class. Properties and methods designated as Hidden can be accessed only by other members in the class definition. Subclasses of the class cannot see or reference hidden members.

To ensure correct functioning in some classes, you need to prevent users from programmatically changing the properties or calling the method from outside the class.

The following example illustrates using protected properties and methods in a class.

The stopwatch class included in Samples.vcx, in the Visual Studio \Samples\Vfp98\Classes directory, includes a timer and five labels to display the elapsed time:

The stopwatch class in Samples.vcx

The Stopwatch class contains labels and a timer.

Property Settings for the Stopwatch Class

Control Property Setting
lblSeconds Caption 00
lblColon1 Caption :
lblMinutes Caption 00
lblColon2 Caption :
lblHours Caption 00
tmrSWatch Interval 1000

This class also has three protected properties, nSec, nMin, and nHour, and one protected method, UpdateDisplay. The other three custom methods in the class, Start, Stop, and Reset, are not protected.

Tip   Choose Class Info on the Class menu to see the visibility of all properties and methods of a class.

The protected properties are used in internal calculations in the UpdateDisplay method and the Timer event. The UpdateDisplay method sets the captions of the labels to reflect the elapsed time.

The UpdateDisplay Method

Code Comments

cSecDisplay = ALLTRIM(STR(THIS.nSec)) cMinDisplay = ALLTRIM(STR(THIS.nMin)) cHourDisplay = ALLTRIM(STR(THIS.nHour))

Convert the numeric properties to Character type for display in the label captions.

THIS.lblSeconds.Caption = ;

 IIF(THIS.nSec < 10, ;   "0" ,"") + cSecDisplay THIS.lblMinutes.Caption = ; IIF(THIS.nMin < 10, ;   "0", "") + cMinDisplay THIS.lblHours.Caption = ; IIF(THIS.nHour < 10, ;   "0", "") + cHourDisplay

Set the label captions, retaining the leading 0 if the value of the numeric property is less than 10.

The following table lists the code in the tmrSWatch.Timer event:

The Timer Event

Code Comments

THIS.Parent.nSec = THIS.Parent.nSec + 1

IF THIS.Parent.nSec = 60 THIS.Parent.nSec = 0 THIS.Parent.nMin = ; THIS.Parent.nMin + 1 ENDIF

Increment the nSec property every time the timer event fires: every second.

If nSec has reached 60, reset it to 0 and increment the nMin property.

IF THIS.Parent.nMin = 60

  THIS.Parent.nMin = 0 THIS.Parent.nHour = ; THIS.Parent.nHour + 1 ENDIF THIS.Parent.UpdateDisplay

If nMin has reached 60, reset it to 0 and increment the nHour property.

Call the UpdateDisplay method when the new property values are set.

The stopwatch class has three methods that are not protected: Start, Stop, and Reset. A user can call these methods directly to control the stopwatch.

The Start method contains the following line of code:

THIS.tmrSWatch.Enabled = .T.

The Stop method contains the following line of code:

THIS.tmrSWatch.Enabled = .F.

The Reset method sets the protected properties to zero and calls the protected method:

THIS.nSec = 0 THIS.nMin = 0 THIS.nHour = 0 THIS.UpdateDisplay

The user cannot directly set these properties or call this method, but code in the Reset method can.

Specifying the Default Value for a Property

When you create a new property, the default setting is false (.F.). To specify a different default setting for a property, use the Properties window. In the Other tab, click on your property and set it to the desired value. This will be the initial property setting when the class is added to a form or form set.

You can also set any of the base class properties in the Class Designer. When an object based on the class is added to the form, the object reflects your property settings rather than the Visual FoxPro base class property settings.

Tip   If you want to make the default setting of a property an empty string, select the setting in the Property Editing box and press the BACKSPACE key.

Specifying Design Time Appearance

You can specify the toolbar icon and the container icon for your class in the Class Info dialog box.

To set a toolbar icon for a class

  1. In the Class Designer, choose Class Info from the Class menu.

  2. In the Class Info dialog box, type the name and path of the .BMP file in the Toolbar icon box.

    Tip   The bitmap (.bmp file) for the toolbar icon is 15 by 16 pixels. If the picture is larger or smaller, it is sized to 15 by 16 pixels and might not look the way you want it to.

The toolbar icon you specify is displayed in the Form Controls toolbar when you populate the toolbar with the classes in your class library.

You can also specify the icon to be displayed for the class in the Project Manager and Class Browser by setting the container icon.

To set a container icon for a class

  1. In the Class Designer, choose Class Info from the Class menu.

  2. In the Container icon box, type the name and path of the .bmp file to be displayed on the button in the Form Controls toolbar.

Using Class Library Files

Every visually designed class is stored in a class library with a .vcx file extension.

Creating a Class Library

You can create a class library in one of three ways.

To create a class library

Copying and Removing Class Library Classes

Once you add a class library to a project, you can easily copy classes from one library to another or simply remove classes from libraries.

To copy a class from one library to another

  1. Make sure both libraries are in a project (not necessarily the same project).

  2. In the Project Manager, select the Classes tab.

  3. Click the plus sign (+) to the left of the class library that the class is now in.

  4. Drag the class from the original library and drop it in the new library.

    Tip   For convenience and speed, you might want to keep a class and all the subclasses based on it in one class library. If you have a class that contains elements from many different class libraries, these libraries must all be open, so it will take a little longer to initially load your class at run time and at design time.

To remove a class from a library

To change the name of a class in a class library, use the RENAME CLASS command. Remember, however, that when you change the name of a class, forms that contain the class and subclasses in other .vcx files continue to reference the old name and will no longer function correctly.

Visual FoxPro includes a Class Browser to facilitate using and managing classes and class libraries. For more information, see Class Browser window.

Adding Classes to Forms

You can drag a class from the Project Manager to the Form Designer or to the Class Designer. You can also register your classes so that they can be displayed directly on the Form Controls toolbar in the Class Designer or Form Designer and added to containers the same way the standard controls are added.

To register a class library

  1. From the Tools menu, choose Options.

  2. In the Options dialog box, choose the Controls tab.

  3. Select Visual Class Libraries and choose Add.

  4. In the Open dialog box, choose a class library to add to the registry and choose Open.

  5. Choose Set as Default if you want the class library to be available in the Form Controls toolbar in future sessions of Visual FoxPro.

You can also add your class library to the Form Controls toolbar by choosing Add in the submenu of the View Classes button. To make these classes available in the Form Controls toolbar in future sessions of Visual FoxPro, you still need to set the default in the Options dialog box.

Overriding Default Property Settings

When you add objects based on a user-defined class to a form, you can change the settings of all the properties of the class that are not protected, overriding the default settings. If you change the class properties in the Class Designer later, the settings in the object on the form are not affected. If you have not changed a property setting in the form and you change the property setting in the class, the change will take effect in the object as well.

For example, a user could add an object based on your class to a form and change the BackColor property from white to red. If you change the BackColor property of the class to green, the object on the user s form will still have a background color of red. If, on the other hand, the user did not change the BackColor property of the object and you changed the background color of the class to green, the BackColor property of the object on the form would inherit the change and also be green.

Calling Parent Class Method Code

An object or class based on another class automatically inherits the functionality of the original. However, you can easily override the inherited method code. For example, you can write new code for the Click event of a class after you subclass it or after you add an object based on the class to a container. In both cases, the new code is executed at run time; the original code is not executed.

More frequently, however, you want to add functionality to the new class or object while keeping the original functionality. In fact, one of the key decisions you have to make in object-oriented programming is what functionality to include at the class level, at the subclass level, and at the object level. You can optimize your class design by using the DODEFAULT( ) function or scope resolution operator (::) to add code at different levels in the class or container hierarchy.

Adding Functionality to Subclasses

You can call the parent class code from a subclass by using the DODEFAULT( ) function.

For example, cmdOK is a command button class stored in Buttons.vcx, located in the Visual Studio \Samples\Vfp98\Classes directory. The code associated with the Click event of cmdOk releases the form the button is on. CmdCancel is a subclass of cmdOk in the same class library. To add functionality to cmdCancel to discard changes, for example, you could add the following code to the Click event:

IF USED( ) AND CURSORGETPROP("Buffering") != 1   TABLEREVERT(.T.) ENDIF DODEFAULT( )

Because changes are written to a buffered table by default when the table is closed, you don t need to add TABLEUPDATE( ) code to cmdOk. The additional code in cmdCancel reverts changes to the table before calling the code in cmdOk, the ParentClass, to release the form.

Class and Container Hierarchies

The class hierarchy and the container are two separate entities. Visual FoxPro looks for event code up through the class hierarchy, whereas objects are referenced in the container hierarchy. The following section, Referencing Objects in the Container Hierarchy, discusses container hierarchies. Later in this chapter, class hierarchies are explained in the section Calling Event Code up the Class Hierarchy.

Referencing Objects in the Container Hierarchy

To manipulate an object, you need to identify it in relation to the container hierarchy. For example, to manipulate a control on a form in a form set, you need to reference the form set, the form, and then the control.

You can compare the referencing of an object within its container hierarchy to giving Visual FoxPro an address to your object. When you describe the location of a house to someone outside your immediate frame of reference, you need to indicate the country, the state or region, the city, the street, or just the street number of the house, depending on how far they are from you. Otherwise, there could be some confusion.

The following illustration shows a possible container nesting situation.

Nested containers

To disable the control in the grid column, you need to provide the following address:

Formset.Form.PageFrame.Page.; Grid.Column.Control.Enabled = .F.

The ActiveForm property of the application object (_VFP) allows you to manipulate the active form even if you don t know the name of the form. For example, the following line of code changes the background color of the active form, no matter what form set it belongs to:

_VFP.ActiveForm.BackColor = RGB(255,255,255)

Similarly, the ActiveControl property allows you to manipulate the active control on the active form. For example, the following expression entered in the Watch window displays the name of the active control on a form as you interactively choose the various controls:

_VFP.ActiveForm.ActiveControl.Name

Relative Referencing

When you are referencing objects from within the container hierarchy (for example, in the Click event of a command button on a form in a form set), you can use some shortcuts to identify the object you want to manipulate. The following table lists properties or keywords that make it easier to reference an object from within the object hierarchy:

Property or keyword Reference
Parent The immediate container of the object.
THIS The object.
THISFORM The form that contains the object.
THISFORMSET The form set that contains the object.

Note   You can use THIS, THISFORM, and THISFORMSET only in method or event code.

The following table provides examples of using THISFORMSET, THISFORM, THIS, and Parent to set object properties:

Command Where to include the command

THISFORMSET.frm1.cmd1.Caption = "OK"

In the event or method code of any controls on any form in the form set.

THISFORM.cmd1.Caption = "OK"

In the event or method code of any control on the same form that cmd1 is on.

THIS.Caption = "OK"

In the event or method code of the control whose caption you want to change.

THIS.Parent.BackColor = RGB(192,0,0)

In the event or method code of a control on a form. The command changes the background color of the form to dark red.

Setting Properties

You can set the properties of an object at run time or design time.

To set a property

For the property settings in the preceding examples, frmPhoneLog is the highest level container object. If frmPhoneLog were contained in a form set, you would also need to include the form set in the parent path:

frsContacts.frmPhoneLog.txtDate.Value = DATE( )

Setting Multiple Properties

The WITH ... ENDWITH structure simplifies setting multiple properties. For example, to set multiple properties of a column in a grid in a form in a form set, you could use the following syntax:

WITH THISFORMSET.frmForm1.grdGrid1.grcColumn1 .Width = 5 .Resizable = .F. .ForeColor = RGB(0,0,0) .BackColor = RGB(255,255,255) .SelectOnEntry = .T. ENDWITH

Calling Methods

Once an object has been created, you can call the methods of that object from anywhere in your application.

To call a method

The following statements call methods to display a form and set the focus to a text box:

frsFormSet.frmForm1.Show frsFormSet.frmForm1.txtGetText1.SetFocus

Methods that return values and are used in expressions must end in open and closed parentheses. For example, the following statement sets the caption of a form to the value returned from the user-defined method GetNewCaption:

Form1.Caption = Form1.GetNewCaption( )

Note   Parameters passed to methods must be included in parentheses after the method name; for example, Form1.Show(nStyle). passes nStyle to Form1 s Show method code.

Responding to Events

The code you include in an event procedure is executed when the event takes place. For example, the code you include in the Click event procedure of a command button is executed when the user clicks the command button.

You can programmatically cause Click, DblClick, MouseMove, and DragDrop events with the MOUSE command, or use the ERROR command to generate Error events and the KEYBOARD command to generate KeyPress events. You cannot programmatically cause any other events to occur, but you can call the procedure associated with the event. For example, the following statement causes the code in the Activate event of frmPhoneLog to be executed, but it doesn t activate the form:

frmPhoneLog.Activate

If you do want to activate the form, use the Show method of the form. Calling the Show method causes the form to be displayed and activated, at which point the code in the Activate event is also executed:

frmPhoneLog.Show

Defining Classes Programmatically

You can define classes visually in the Class Designer and the Form Designer or programmatically in .PRG files. This section describes how to write class definitions. For information about the specific commands, functions, and operators, see Help. For more information about forms, see Chapter 9, Creating Forms.

In a program file, you can have program code prior to the class definitions, but not after the class definitions, in the same way that program code cannot come after procedures in a program. The basic shell for class creation has this syntax:

DEFINE CLASS ClassName1 AS ParentClass [OLEPUBLIC]

[[PROTECTED | HIDDEN PropertyName1, PropertyName2 ...]

[Object.]PropertyName = eExpression ...]

[ADD OBJECT [PROTECTED] ObjectName AS ClassName2 [NOINIT]

[WITH cPropertylist]]...

[[PROTECTED | HIDDEN] FUNCTION | PROCEDURE Name[_ACCESS | _ASSIGN]

[NODEFAULT]

cStatements

[ENDFUNC | ENDPROC]]...

ENDDEFINE

Protecting and Hiding Class Members

You can protect or hide properties and methods in a class definition with the PROTECTED and HIDDEN keywords of the DEFINE CLASS command.

For example, if you create a class to hold employee information, and you don t want users to be able to change the hire date, you can protect the HireDate property. If users need to find out when an employee was hired, you can include a method to return the hire date.

DEFINE CLASS employee AS CUSTOM PROTECTED HireDate First_Name = "" Last_Name = "" Address = "" HireDate = { - - } PROCEDURE GetHireDate RETURN This.HireDate ENDPROC ENDDEFINE

Creating Objects from Classes

When you have saved a visual class, you can create an object based on it with the CREATEOBJECT( ) function. The following example demonstrates running a form saved as a class definition in the class library file Forms.vcx:

Creating and Showing a Form Object Whose Class Was Designed in the Form Designer

Code Comments

SET CLASSLIB TO Forms ADDITIVE

Set the class library to the .vcx file that the form definition was saved in. The ADDITIVE keyword prevents this command from closing any other class libraries that happened to be open.

frmTest = CREATEOBJECT("TestForm")

This code assumes that the name of the form class saved in the class library is TestForm.

frmTest.Show

Display the form.

Adding Objects to a Container Class

You can use the ADD OBJECT clause in the DEFINE CLASS command or the AddObject method to add objects to a container.

For example, the following class definition is based on a form. The ADD OBJECT command adds two command buttons to the form:

DEFINE CLASS myform AS FORM ADD OBJECT cmdOK AS COMMANDBUTTON ADD OBJECT PROTECTED cmdCancel AS COMMANDBUTTON ENDDEFINE

Use the AddObject method to add objects to a container after the container object has been created. For example, the following lines of code create a form object and add two command buttons to it:

frmMessage = CREATEOBJECT("FORM") frmMessage.AddObject("txt1", "TEXTBOX") frmMessage.AddObject("txt2", "TEXTBOX")

You can also use the AddObject method in the method code of a class. For example, the following class definition uses AddObject in the code associated with the Init event to add a control to a grid column.

DEFINE CLASS mygrid AS GRID ColumnCount = 3 PROCEDURE Init THIS.Column2.AddObject("cboClient", "COMBOBOX") THIS.Column2.CurrentControl = "cboClient" ENDPROC ENDDEFINE

Adding and Creating Classes in Method Code

You can programmatically add objects to a container with the AddObject method. You can also create objects with the CREATEOBJECT( ) function in the Load, Init, or any other method of the class.

When you add an object with the AddObject method, the object becomes a member of the container. The Parent property of the added object refers to the container. When an object based on the container or control class is released from memory, the added object is also released.

When you create an object with the CREATEOBJECT( ) function, the object is scoped to a property of the class or a variable in the method that calls this function. The parent property of the object is undefined.

Assigning Method and Event Code

In addition to writing code for the methods and events of an object, you can extend the set of methods in subclasses of Visual FoxPro base classes. Here are the rules for writing event code and methods:

Calling Event Code up the Class Hierarchy

When you create a class, the class automatically inherits all the properties, methods, and events of the parent class. If code is written for an event in the parent class, that code is executed when the event occurs with respect to an object based on the subclass. You can, however, overwrite the parent class code by writing code for the event in the subclass.

To explicitly call the event code in a parent class when the subclass has code written for the same event, use the DODEFAULT( ) function.

For example, you could have a class named cmdBottom based on the command button base class that has the following code in the Click event:

GO BOTTOM THISFORM.Refresh

When you add an object based on this class to a form, named, for example, cmdBottom1, you might decide that you also want to display a message for the user so that he or she knows that the record pointer is at the bottom of the table. You could add the following code to the Click event of the object to display the message:

WAIT WINDOW "At the Bottom of the Table" TIMEOUT 1

When you run the form, however, the message is displayed, but the record pointer doesn t move because the code in the Click event of the parent class is never executed. To make sure the code in the Click event of the parent class is also executed, include the following lines of code in the Click event procedure of the object:

DODEFAULT( ) WAIT WINDOW "At the Bottom of the Table" TIMEOUT 1

Note   You can use the ACLASS( ) function to determine all the classes in an object s class hierarchy.

Preventing Base Class Code from Executing

Sometimes you ll want to prevent the base class default behavior from taking place in an event or method. You can do this by including the NODEFAULT keyword in the method code you write. For example, the following program uses the NODEFAULT keyword in the KeyPress event of a text box to prevent the typed characters from being displayed in the text box:

frmKeyExample = CREATEOBJECT("test") frmKeyExample.Show READ EVENTS DEFINE CLASS test AS FORM ADD OBJECT text1 AS TEXTBOX PROCEDURE text1.KeyPress   PARAMETERS nKeyCode, nShiftAltCtrl   NODEFAULT   IF BETWEEN(nKeyCode, 65, 122) && between 'A' and 'z'    This.Value = ALLTRIM(This.Value) + "*"    ACTIVATE SCREEN      && send output to main Visual FoxPro window    ?? CHR(nKeyCode)   ENDIF ENDPROC PROCEDURE Destroy   CLEAR EVENTS ENDPROC ENDDEFINE

Creating a Set of Table Navigation Buttons

A common feature of many applications is a series of navigation buttons that allow users to move through a table. These typically include buttons to move the record pointer to the next or prior record in the table, as well as to the top or bottom record in the table.

Table navigation buttons

Designing the Navigation Buttons

Each of the buttons will have some characteristics and functionality in common, so it is a good idea to create a navigation button class. Then the individual buttons can easily derive this common appearance and functionality. This parent class is the Navbutton class defined later in this section.

Once the parent class is defined, the following subclasses define the functionality and appearance specific to each of the four navigation buttons: navTop, navPrior, navNext, navBottom.

Finally, a container class, vcr, is created and each of the navigation buttons is added to the container class. The container can be added to a form or a toolbar to provide table navigation functionality.

NAVBUTTON Class Definition

To create Navbutton, save the following six class definitions (Navbutton, navTop, navBottom, navPrior, navNext, and vcr) to a program file such as Navclass.prg.

Definition of the Generic Navigation Commandbutton Class

Code Comments

DEFINE CLASS Navbutton AS COMMANDBUTTON Height = 25 Width = 25

  TableAlias = ""

Define the parent class of the navigation buttons.

Give the class some dimensions.

Include a custom property, TableAlias, to hold the name of the alias to navigate through.

PROCEDURE Click IF NOT EMPTY(This.TableAlias)   SELECT (This.TableAlias) ENDIF ENDPROC

If TableAlias has been set, this parent class procedure selects the alias before the actual navigation code in the subclasses is executed. Otherwise, assume that the user wants to navigate through the table in the currently selected work area.

PROCEDURE RefreshForm _SCREEN.ActiveForm.Refresh ENDPROC

Using _SCREEN.ActiveForm.Refresh instead of THISFORM.Refresh allows you to add the class to a form or a toolbar and have it function equally well.

ENDDEFINE

End the class definition.

The specific navigation buttons are all based on the Navbutton class. The following code defines the Top button for the set of navigation buttons. The remaining three navigation buttons are defined in the following table. The four class definitions are similar, so only the first one has extensive comments.

Definition of the Top Navigation Button Class

Code Comments

DEFINE CLASS navTop AS Navbutton Caption = "|<"

Define the Top navigation button class and set the Caption property.

PROCEDURE Click

Create method code to be executed when the Click event for the control occurs.

  DODEFAULT( ) GO TOP THIS.RefreshForm

Call the Click event code in the parent class, Navbutton, so that the appropriate alias can be selected if the TableAlias property has been set.

Include the code to set the record pointer to the first record in the table: GO TOP.

Call the RefreshForm method in the parent class. It is not necessary to use the scope resolution operator (::) in this case because there is no method in the subclass with the same name as the method in the parent class. On the other hand, both the parent and the subclass have method code for the Click event.

ENDPROC

End the Click procedure.

ENDDEFINE

End the class definition.

The other navigation buttons have similar class definitions.

Definition of the Other Navigation Button Classes

Code Comments

DEFINE CLASS navNext AS Navbutton Caption = ">"

Define the Next navigation button class and set the Caption property.

PROCEDURE Click DODEFAULT( ) SKIP 1 IF EOF( )   GO BOTTOM ENDIF THIS.RefreshForm ENDPROC ENDDEFINE

Include the code to set the record pointer to the next record in the table.

End the class definition.

DEFINE CLASS navPrior AS Navbutton Caption = "<"

Define the Prior navigation button class and set the Caption property.

PROCEDURE Click DODEFAULT( ) SKIP 1 IF BOF( )   GO TOP ENDIF THIS.RefreshForm ENDPROC ENDDEFINE

Include the code to set the record pointer to the previous record in the table.

End the class definition.

DEFINE CLASS navBottom AS Navbutton Caption = ">|"

Define the Bottom navigation button class and set the Caption property.

PROCEDURE Click DODEFAULT( ) GO BOTTOM THIS.RefreshForm ENDPROC ENDDEFINE

Include the code to set the record pointer to the bottom record in the table.

End the class definition.

The following class definition contains all four navigation buttons so that they can be added as a unit to a form. The class also includes a method to set the TableAlias property of the buttons.

Definition of a Table Navigation Control Class

Code Comments

DEFINE CLASS vcr AS CONTAINER   Height = 25   Width = 100   Left = 3   Top = 3

Begin the class definition. The Height property is set to the same height as the command buttons it will contain.

   ADD OBJECT cmdTop AS navTop ;      WITH Left = 0   ADD OBJECT cmdPrior AS navPrior ;      WITH Left = 25   ADD OBJECT cmdNext AS navNext ;      WITH Left = 50   ADD OBJECT cmdBot AS navBottom ;      WITH Left = 75

Add the navigation buttons.

PROCEDURE SetTable(cTableAlias)   IF TYPE("cTableAlias") = 'C'      THIS.cmdTop.TableAlias = ;         cTableAlias      THIS.cmdPrior.TableAlias = ;         cTableAlias      THIS.cmdNext.TableAlias = ;         cTableAlias      THIS.cmdBot.TableAlias = ;         cTableAlias   ENDIF ENDPROC

This method is used to set the TableAlias property of the buttons. TableAlias is defined in the parent class Navbutton.

You could also use the SetAll method to set this property:

IF TYPE ("cTableAlias") = 'C'

This.SetAll("TableAlias", "cTableAlias")

ENDIF

However, this would cause an error if an object were ever added to the class that did not have a TableAlias property.

ENDDEFINE

End class definition.

Once you have defined the class, you can subclass it or add it to a form.

Creating a Subclass Based on the New Class

You can also create subclasses based on vcr that have additional buttons such as Search, Edit, Save, and Quit. For example, vcr2 includes a Quit button:

Table navigation buttons with a button to close the form

Definition of a Table Navigation Control Subclass

Code Comments

DEFINE CLASS vcr2 AS vcr

ADD OBJECT cmdQuit AS COMMANDBUTTON WITH ;   Caption = "Quit",;   Height = 25, ;   Width = 50 Width = THIS.Width + THIS.cmdQuit.Width cmdQuit.Left = THIS.Width - ;   THIS.cmdQuit.Width

Define a class based on vcr and add a command button to it.

PROCEDURE cmdQuit.CLICK

   RELEASE THISFORM ENDPROC

When the user clicks cmdQuit, this code releases the form.

ENDDEFINE

End class definition.

Vcr2 has everything that vcr does, plus the new command button, and you don t have to rewrite any of the existing code.

Changes to VCR Reflected in the Subclass

Because of inheritance, changes to the parent class are reflected in all subclasses based on the parent. For example, you could let the user know that the bottom of the table has been reached by changing the IF EOF( ) statement in navNext.Click to the following:

IF EOF( )   GO BOTTOM   SET MESSAGE TO "Bottom of the table" ELSE   SET MESSAGE TO ENDIF

You could let the user know that the top of the table has been reached by changing the IF BOF( ) statement in navPrior.Click to the following:

IF BOF()   GO TOP   SET MESSAGE TO "Top of the table" ELSE   SET MESSAGE TO ENDIF

If these changes are made to the navNext and navPrior classes, they will also apply automatically to the appropriate buttons in vcr and vcr2.

Adding VCR to a Form Class

Once vcr is defined as a control, the control can be added in the definition of a container. For example, the following code added to Navclass.prg defines a form with added navigation buttons:

DEFINE CLASS NavForm AS Form   ADD OBJECT oVCR AS vcr ENDDEFINE

Running the Form Containing VCR

Once the form subclass is defined, you can display it easily with the appropriate commands.

To display the form

  1. Load the class definition:

    SET PROCEDURE TO navclass ADDITIVE

  2. Create an object based on the navform class:

    frmTest = CREATEOBJECT("navform")

  3. Invoke the Show method of the form:

    frmTest.Show

If you don t call the SetTable method of oVCR (the VCR object in NavForm) when the user clicks the navigation buttons, the record pointer moves in the table in the currently selected work area. You can call the SetTable method to specify what table to move through.

frmTest.oVCR.SetTable("customer")

Note   When the user closes the form, frmTest is set to a null value (.NULL.). To release the object variable from memory, use the RELEASE command. Object variables created in program files are released from memory when the program is completed.

Defining a Grid Control

A grid contains columns, which in turn can contain headers and any other control. The default control contained in a column is a text box, so that the default functionality of the grid approximates a Browse window. However, the underlying architecture of the grid opens it up to endless extensibility.

The following example creates a form that contains a Grid object with two columns. The second column contains a check box to display the values in a logical field in a table.

Grid control with a check box in one column

Definition of a Grid Class with a Check Box in a Grid Column

Code Comments

DEFINE CLASS grdProducts AS Grid   Left = 24   Top = 10   Width = 295   Height = 210   Visible = .T.   RowHeight = 28   ColumnCount = 2

Start the class definition and set properties that determine the grid appearance.

When you set the ColumnCount property to 2, you add two columns to the grid. Each column contains a header with the name Header1. In addition, each column has an independent group of properties that determines its appearance and behavior.

Column1.ControlSource ="prod_name" Column2.ControlSource ="discontinu"

When you set the ControlSource of a column, the column displays that field s values for all the records in the table.

Discontinu is a logical field.

Column2.Sparse = .F.

Column2 will contain the check box. Set the column s Sparse property to .F. so that the check box will be visible in all rows, not just in the selected cell.

Procedure Init   THIS.Column1.Width = 175   THIS.Column2.Width = 68   THIS.Column1.Header1.Caption = ;      "Product Name"   THIS.Column2.Header1.Caption = ;      "Discontinued"   THIS.Column2.AddObject("chk1", ;      "checkbox")   THIS.Column2.CurrentControl = ;      "chk1"   THIS.Column2.chk1.Visible = .T.   THIS.Column2.chk1.Caption = "" ENDPROC

Set column widths and header captions.

The AddObject method allows you to add an object to a container in this case, a check box named chk1.

Set the CurrentControl of the column to the check box so that the check box will be displayed.

Make sure that the check box is visible.

Set the caption to an empty string so that the default caption chk1 won t be displayed.

ENDDEFINE

End of the class definition.

The following class definition is the form that contains the grid. Both class definitions can be included in the same program file.

Definition of a Form Class that Contains the Grid Class

Code Comments

DEFINE CLASS GridForm AS FORM   Width = 330   Height = 250   Caption = "Grid Example"   ADD OBJECT grid1 AS grdProducts

Create a form class and add an object, based on the grid class, to it.

PROCEDURE Destroy   CLEAR EVENTS ENDPROC ENDDEFINE

The program that creates an object based on this class will use READ EVENTS. Including CLEAR EVENTS in the Destroy event of the form allows the program to finish running when the user closes the form.

End of the class definition.

The following program opens the table with the fields to be displayed in the grid columns, creates an object based on the GridForm class, and issues the READ EVENTS command:

CLOSE DATABASE OPEN DATABASE (HOME(2) + "data\testdata.dbc") USE products frmTest= CREATEOBJECT("GridForm") frmTest.Show READ EVENTS

This program can be included in the same file with the class definitions if it comes at the beginning of the file. You could also use the SET PROCEDURE TO command to specify the program with the class definitions and include this code in a separate program.

Creating Object References

Instead of making a copy of an object, you can create a reference to the object. A reference takes less memory than an additional object, can easily be passed between procedures, and can aid in writing generic code.

Returning a Reference to an Object

Sometimes, you might want to manipulate an object by means of one or more references to the object. For example, the following program defines a class, creates an object based on the class, and returns a reference to the object:

*--NEWINV.PRG *--Returns a reference to a new invoice form. frmInv = CREATEOBJECT("InvoiceForm") RETURN frmInv DEFINE CLASS InvoiceForm AS FORM   ADD OBJECT txtCompany AS TEXTBOX   * code to set properties, add other objects, and so on ENDDEFINE

The following program establishes a reference to the object created in Newinv.prg. The reference variable can be manipulated in exactly the same way as the object variable can:

frmInvoice = NewInv() && store the object reference to a variable frmInvoice.SHOW

You can also create a reference to an object on a form, as in the following example:

txtCustName = frmInvoice.txtCompany txtCustName.Value = "Fox User"

Tip   Once you ve created an object, you can use the DISPLAY OBJECTS command to display the object s class hierarchy, property settings, contained objects, and available methods and events. You can fill an array with the properties (not the property settings), events, methods, and contained objects of an object with the AMEMBERS( ) function.

Releasing Objects and References from Memory

If a reference to an object exists, releasing the object does not clear the object from memory. For example, the following command releases frmInvoice:, the original object:

RELEASE frmInvoice

However, because a reference to an object belonging to frmInvoice still exists, the object is not released from memory until txtCustName is released with the following command:

RELEASE txtCustName

Checking to See if an Object Exists

You can use the TYPE( ), ISNULL( ), and VARTYPE( ) functions to determine if an object exists. For example, the following lines of code check to see whether an object named oConnection exists:

IF TYPE("oConnection") = "O" AND NOT ISNULL(oConnection)   * Object exists ELSE   * Object does not exist ENDIF

Note   ISNULL( ) is necessary because .NULL. is stored to the form object variable when a user closes a form, but the type of the variable remains O .

Creating Arrays of Members

You can define members of classes as arrays. In the following example, choices is an array of controls:

DEFINE CLASS MoverListBox AS CONTAINER DIMENSION choices[3] ADD OBJECT lstFromListBox AS LISTBOX ADD OBJECT lstToListBox AS LISTBOX ADD OBJECT choices[1] AS COMMANDBUTTON ADD OBJECT choices[2] AS COMMANDBUTTON ADD OBJECT choices[3] AS CHECKBOX PROCEDURE choices.CLICK   PARAMETER nIndex   DO CASE      CASE nIndex = 1         * code      CASE nIndex = 2         * code      CASE nIndex = 3         * code   ENDCASE ENDPROC ENDDEFINE

When the user clicks a control in an array of controls, Visual FoxPro passes the index number of the control to the Click event procedure. In this procedure, you can use a CASE statement to execute different code depending on which button was clicked.

Creating Arrays of Objects

You can also create arrays of objects. For example, MyArray holds five command buttons:

DIMENSION MyArray[5] FOR x = 1 TO 5   MyArray[x] = CREATEOBJECT("COMMANDBUTTON") ENDFOR

There are some considerations to keep in mind with arrays of objects:

Using Objects to Store Data

In object-oriented languages, a class offers a useful and convenient vehicle for storing data and procedures related to an entity. For example, you could define a customer class to hold information about a customer as well as a method to calculate the customer s age:

DEFINE CLASS customer AS CUSTOM   LastName = ""   FirstName = ""   Birthday = { - - }   PROCEDURE Age      IF !EMPTY(THIS.Birthday)         RETURN YEAR(DATE()) - YEAR(THIS.Birthday)      ELSE         RETURN 0      ENDIF   ENDPROC ENDDEFINE

However, data stored in objects based on the customer class are stored only in memory. If this data were in a table, the table would be stored on disk. If you had more than one customer to keep track of, the table would give you access to all of the Visual FoxPro database management commands and functions. As a result, you could quickly locate information, sort it, group it, perform calculations on it, create reports and queries based on it, and so on.

Storing and manipulating data in databases and tables is what Visual FoxPro does best. There are times, however, when you ll want to store data in objects. Usually, the data will be significant only while your application is running and it will pertain to a single entity.

For example, in an application that includes a security system, you would typically have a table of users who have access to the application. The table would include user identification, password, and access level. Once a user has logged on, you won t need all the information in the table. All you need is information about the current user, and this information can be easily stored and manipulated in an object. The following class definition, for example, initiates a logon when an object based on the class is created:

DEFINE CLASS NewUser AS CUSTOM   PROTECTED LogonTime, AccessLevel   UserId = ""   PassWord = ""   LogonTime = { - - : : }   AccessLevel = 0   PROCEDURE Init      DO FORM LOGON WITH ; && assuming you have created this form         This.UserId, ;         This.PassWord, ;         This.AccessLevel      This.LogonTime = DATETIME( )   ENDPROC * Create methods to return protected property values.   PROCEDURE GetLogonTime      RETURN This.LogonTime   ENDPROC   PROCEDURE GetAccessLevel      RETURN This.AccessLevel   ENDPROC ENDDEFINE

In the main program of your application, you could create an object based on the NewUserclass:

oUser = CREATEOBJECT('NewUser') oUser.Logon

Throughout your application, when you need information about the current user, you can get it from the oUser object. For example:

IF oUser.GetAccessLevel( ) >= 4   DO ADMIN.MPR ENDIF

Integrating Objects and Data

In most applications, you can best utilize the power of Visual FoxPro by integrating objects and data. Most Visual FoxPro classes have properties and methods that allow you to integrate the power of a relational database manager and a full object-oriented system.

Properties for Integrating Visual FoxPro Classes and Database Data

Class Data properties
Grid RecordSource, ChildOrder, LinkMaster
All other controls ControlSource
List box and combo box ControlSource, RowSource
Form and form set DataSession

Because these data properties can be changed at design or run time, you can create generic controls with encapsulated functionality that operates on diverse data.

For more information about integrating data and objects, see Chapter 9, Creating Forms, and Chapter 10, Using Controls,

Категории