0% found this document useful (0 votes)
40 views134 pages

Foxpro

The document provides an overview of programming in Visual FoxPro, covering fundamental concepts such as data types, data storage, and basic programming commands. It explains how to create and manipulate programs, use procedures and functions, and implement object-oriented programming. Additionally, it discusses controlling program flow through conditional branching and looping, as well as accessing APIs and creating customized quit routines.

Uploaded by

iniafbolivia666
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views134 pages

Foxpro

The document provides an overview of programming in Visual FoxPro, covering fundamental concepts such as data types, data storage, and basic programming commands. It explains how to create and manipulate programs, use procedures and functions, and implement object-oriented programming. Additionally, it discusses controlling program flow through conditional branching and looping, as well as accessing APIs and creating customized quit routines.

Uploaded by

iniafbolivia666
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 134

g

c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Pro gramming in Visual FoxPro
Send Feedback

You can create applications and programs by learning about and using Visual FoxPro's programming lang uage and capabilities.

In This Section
Basic Programming Concepts

Pro vides an overview of programming fundamentals necessary to work in Visual FoxPro, including data storage, data types,
containers, operators, commands, and controllin g program flow.

Working with Programs

Introduces how to create and work with Visual FoxPro programs, which are text files contain ing instructions using the Visual
FoxPro language.

Working with Procedures and Functio ns

Introduces how to call native functions as well as user-defined functions and procedures, provides an overview and aspects of
user-defined functions and procedures, and how to create functions and procedures.

Passing Data to Parameters

Discusses ways and how to pass data to parameters.

Object-Oriented Programming

Discusses how you can create self-contained application componen ts that respond to user actions and to the system and which
can be easily maintained and reused.

Accessing APIs

Discusses how you can extend an application by tak ing advantage of external libraries such as Microsoft ActiveX controls or
dynamic-link libraries (DLLs).

How to: Create Quit Routin es

Describes how to create customized quit routines when users quit your application, Visual FoxPro, o r Microsoft Windows.

Related Sections
Using Visual FoxPro

Pro vides an overview of Visual FoxPro featu res, describes concepts and productivity tools for developing, programming, and
managing high-performance database applications and componen ts.

Developin g Visual FoxPro Applications

Explains concepts about how to develop Visual FoxPro applicatio ns, instru ctions fo r creating databases and the user interface,
and other tasks need ed to create Visual FoxPro applications.
Development Productivity Tools

Discusses the develo per tools for application develo pment within the Visual FoxPro application and the Visual FoxPro
language.

Walkthroughs

Pro vides common scenarios and step -by-step guides on how to create different types of applications and components.

757ae176-3377-4bdf-87fa-477ec7425023 Pro gramming in Visual FoxPro

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Basic Programming Concepts
See Also Send Feedback

When you write a program, you can store data and manipulate it with a series of instructions. Data and data storage containers are the
basic building blocks in pro grams, and you use commands, functions, and operato rs to manipulate data and data storage containers.

Storing Data
The data that you work with can include amounts of time, money, and countable items, as well as dates, names, description s, and so
on. Each piece of data is a certain type: it belongs to a category of data that you manip ulate in similar ways. You could work directly
with this data without storing it, but you would lose most of the flexibility and power of Visual FoxPro. Visual FoxPro provides
numerous storage containers to extend your ability to easily manipulate data.

Data types determine how data is stored and how it can be used. You can multiply two numbers together, but you can't multiply
characters. You can print characters in uppercase, but you can't print numbers in uppercase. Some of th e primary data types in Visual
FoxPro are listed in the fo llowing table.

Data Types
Type Examples
Numeric 123 3.1415 – 7
Character "Test String" "123" "01/01/98"
Logical .T. .F.
Date {^1998-01-01}

DateTime {^1998-01-01 12:30:00 p }

Data Containers

Data containers allow you to perform the same operations on multiple pieces of data. For example, yo u add the hours an employee
has worked, multiply them by the hourly wage, and then deduct the taxes to determine the amount of pay the employee has earned.
You'll have to perform these operations for every employee and every pay period. If y ou store this information in containers, and
perform the operations on the containers, you can just replace the o ld data with new data and run the same program again. This table
lists some of the main containers for data in Visual FoxPro.

Type Description
Single elements of data stored in your computer's
Variables RAM (Random Access Memory).
Mu ltiple rows of predetermined fields, each of
Table
which can contain a predefined piece of data.
Records
Tables are saved to disk.
Arrays Mu ltiple elements of data stored in RAM.

Manipulating Data
Containers and data types give you the building blocks you need to manipulate data. The final pieces are operators, functions, and
commands.

Using Operators

Operators tie data to gether. Here are th e most common o perators in Visual FoxPro.

Valid Data
Operator Example Result
Types
Prints .T. if the
value stored in the
= All ?n = 7
variable n is 7, .F.
otherwise
Numeric, ? "Fox" +
+ Character, Prints "FoxPro"
Date, DateTime "Pro"
! or NOT Logical ? !.T. Prints .F.
?5 * 5
*, / Numeric Prints 25 Prints 5
? 25 / 5
Note:
A question mark (?) in front of an expression causes a new line character and the results of the expression to be printed in the active
output window, which is usually the main Visual FoxPro window.

Remember that you must use the same type of data with any one op erator. The following statements store two numeric pieces of data
to two variables. The variables have been given names that start with n so we can tell at a g lance that they contain numeric data, bu t
you could name them with any combination of alphanumeric characters and underscores.

nFirst = 123

nSecond = 45

The following statements store two pieces of character data to two variables. The variables have been given names that start with c to
indicate that they contain character data.

cFirst = "123"

cSecond = "4 5"

The following two operations, addition and concatenation, yield d ifferent results because the type of data in the variables is different.

? n First + nSecond

? cFirst + cSecond

Output

168

12345
Because cFirst is character data and nSecond is numeric data, you get a data type mismatch error if you try the following command :

? cFirst + nSecond

You can avoid this problem by using co nversion functions. For example, STR( ) returns the character equiv alent of a numeric value
and VAL( ) returns the numeric equ ivalent o f a character string of numbers. These functions and LTRIM( ), which removes leading
spaces, enable you to perform th e following operations:

? cFirst + LTRIM(STR(nSecond))

? VAL(cFirst) + nSecond

Output

12345

168

Using Commands

A command causes a certain action to be performed. Each command has a specific syntax, which indicates what must be included in
order for the command to work. There are also op tional clauses associated with commands that allow you to specify in more detail
what you want.

For example, the USE command allows you to open and close tab les.

USE Syntax Description


USE Closes the table in the current work area.
Opens the CUSTOMER table in the current
USE
work area, closing any table that was already
customer
open in the work area.
USE Opens the CUSTOMER table in the next
customer IN available work area.
0
USE
customer IN
Opens the CUSTOMER table in the next
0;
available work area and assigns th e work area an
alias o f mycust .
ALIAS
mycust

The following table sh ows some examples of commands.

Command Description
DELETE Marks specified records in a table for deletion.

REPLACE Replaces the value stored in record field with a


new value.
Positio ns the record pointer to a sp ecific location
Go
in the table.

Controlling Program Flow


Visual FoxPro includes a special catego ry of commands that "wrap around" other commands and fu nctions, determin ing when and
how often the o ther commands and functio ns are executed. These commands allow condition al branching and looping, two very
powerful programming tools. The following program illu strates conditional branches and loops. These concepts are described in
more detail after the example.

Suppose that you h ad 10,000 employees and wanted to give everybody making $30,000 or more a 3 percent raise, and everybody
making under $30,000 a 6 percent raise. The following sample program accomplishes this task.

This program assumes that a table with a numeric field n amed salary is open in the current work area. For information about work
areas, see "Using Multiple Tables" in Working with Tables .

Sample Program to Increase Employee Salaries


Code Comments
The code between SCAN and ENDSCAN is
executed as many times as there are records in
SCAN the table. Each time the code is executed, the
record pointer moves to the next record in the
table.
IF salary >=
For each record, if the salary is greater than or
30000.00
equal to 30,000, replace this value with a new
salary that is 3% higher.
REPLACE
salary WITH ;
The semicolon (;) after WITH indicates that
the command is continued on the next line.
salary * 1.03
ELSE
For each record, if the salary is not greater than
REPLACE or equal to 30,000, replace this value with a
salary WITH ;
new salary that is 6% higher.
salary * 1.06
End of the co nditional IF statement.
ENDIF
End of the co de that is executed for each
ENDSCAN record in the table.

This example uses both con ditional branching and loopin g commands to control the flow of the program.

Conditional Branching

Conditional branching allows you to test conditions and then, depending on the results of that test, perform different operations.
There are two co mmands in Visual FoxPro that allow conditional branch ing:

 IF ... ELSE ... ENDIF

 DO CASE ... ENDCASE

The code between the initial statement and the ENDIF or ENDCASE statement is executed only if a logical condition evaluates to
true (.T.). In the example pro gram, the IF command is used to d istinguish between two states: either the salary is $30,000 or more, or
it isn't. Different actions are taken depending on the state.

In the following ex ample, if the value stored in the variable nWaterTemp is less than 100, no action is taken:

Copy Code
* set a logical variable to true if a condition is met.
IF nWaterTemp >= 100
lBoiling = .T.
ENDIF
Note:
An asterisk at the beginning of a line in a pro gram indicates that the line is a comment. Comments help the programmer remember
what each segment of code is designed to do, but are ignored by Visu al FoxPro.

If there are several possible conditions to check for, a DO CASE ... ENDCASE block can b e more efficien t and easier to keep track
of than multiple IF statements.

Looping

Looping allows you to execute one or more lines of code as many times as you need to. There are th ree commands in Visual FoxPro
that allow looping:

 DO WHILE ... ENDDO

 FOR ... ENDFOR

 FOR EACH ... ENDFOR

 SCAN ... ENDSCAN

Use SCAN when y ou are performing a series of actions for each record in a table, as in the example program just described. The
SCAN loop enables you to write the code once and have it executed for each record as the record pointer moves through the table.

Use FOR when you know how many times the section of code needs to be executed. For example, you kn ow there are a specific
number of fields in a table. Because the Visual FoxPro function FCOUNT( ) returns this n umber, you can u se a FOR loop to print the
names of all the fields in the table:

Copy Code
FOR nCnt = 1 TO FCOUNT( )
? FIELD(nCnt)
ENDFOR

Use DO WHILE when you want to execute a section of code as long as a certain condition is met. You might not know how many
times the code will h ave to execute, but you know wh en it should stop executing. For example, let's assume you have a table with
people's names and initials, and you want to use th e initials to look people up. You would have a problem the first time you tried to
add a person who had the same initials as someone else already in your table.

To solve the problem, you could add a number to the in itials. For example, Michael Suyama's identification code co uld be MS. The
next person with the same initials, Margaret Sun, would be MS1. If you then added Michelle Smith to the table, her identification
code would be MS2. A DO WHILE loop enables you to find the right number to append to the initials.

Sample Program with DO WHILE to Generate a Unique ID


Code Comments
nHere =
Save the location o f the record.
RECNO()
cInitials =
LEFT
Get the person's initials from the first letters of
(firstname,1)
the firstname an d lastname fields.
+;
Establish a variable to hold the number to be
LEFT
added to the end of a person's initials if
(lastname,1)
necessary.
nSuffix = 0
LOCATE
FOR See if there is another person in th e table with
person_id = the same initials.
cInitials
If another record in the table has a person_id
value that is the same as cInitials , the FOUND
DO WHILE ( ) function returns true (.T.) and the code in
FOUND( ) the DO WHILE loop executes. If no match is
found, the next line of code to be executed is
the line following ENDDO.
nSuffix =
nSuffix + 1

cInitials = ;
Prepare a fresh suffix and append it to the end
LEFT of the initials.
(cInitials,2);

+ ALLTRIM
(STR
(nSuffix))
CONTINUE cau ses the last LOCATE
command to be evaluated again. The program
checks to see if the new value in cInitials
already exists in the person_id field of another
record. If so, FOUND( ) will still retu rn .T.
CONTINUE
and the code in the DO WHILE loop will
execute again. If the new value in cInitials is
indeed unique, FOUND( ) will return .F. and
program execution continues with the line of
code following ENDDO.
ENDDO End of the DO WHILE loop.
GOTO nHere

REPLACE Return to the record and store the unique


person_id identification code in the person_id field.
WITH
cInitials

Because you don't know beforehand how many times y ou'll find matching identification codes already in use, you use the DO
WHILE loop.

See Also
Concepts

Object-Oriented Programming
Working with Tables (Visual FoxPro)
SCAN ... ENDSCAN Command
FOR ... ENDFOR Comman d
DO WHILE ... ENDDO Command
IF ... ENDIF Command
DO CASE ... ENDCASE Command
GETDIR( ) Function
USE Command

31a12801 -9343-425b-88cc-c79fa473a4 52 Basic Programming Concepts

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Working with Programs
Send Feedback

Pro gram files contain code for executing a series of instructions. Storing code in a program (.prg) file offers benefits such as the
following:
 You can create and save programs to run later instead of running them immediately.

 You can edit programs in Visual FoxPro editin g windows and fo rmat code blocks or entire program files.

 You can edit and run programs multip le times.

 You can run programs from menus, forms, and toolbars.

 You can use programs to run other prog rams.

When your pro gram is part of a project, you can also search for and replace code references and text and view definitions of code
elements found in searches in the current program file. For more information, see How to: Search For Code References an d How to:
View Code Definitions .

In This Section
How to: Create Programs

Describes how to create a Visual FoxPro program.

How to: Edit Programs

Describes how to ed it programs after you create them.

How to: Format Code in Programs

Describes how you can set formatting options and apply them to code in programs.

How to: Save Programs

Describes how to save the programs after you create and edit them.

How to: Run Programs

Describes how to run programs.

Related Sections
Working with Projects

Describes using projects as a way to develop large applications.

Pro gramming in Visual FoxPro

Describes how understanding object -oriented prog ramming techniques and the ev ent-driven model can maximize your
programming productivity and enable you to access the full power of Visual FoxPro.

Language Reference (Visual FoxPro)

Contains descriptions of language elements in Visual FoxPro.

Development Productivity Tools

Describes Visual FoxPro developer tools that you can use for application develop ment within the FoxPro application and the
FoxPro language.

502440d4-5037-4ef9 -a68f-a0fbe58843e3 Working with Programs

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Create Programs
See Also Send Feedback

You can create a standalone program, a program as part of a project, or programmatically.

Note:
After creating a program, make sure you save it. If you try to close an unsaved or mod ified program, Visual FoxPro prompts you to
save the program or discard ch anges.

To create a standalone program

1. On the File menu, click New.

2. In the New dialog box, click Pro gram, and then New File.

3. In the editing window, type the code for the program.

To create a progr am in a project

1. Open the project for y our application in the Pro ject Manager.

2. In the Pro ject Manager, expand the Code node.

3. Click Pro grams, then New.

4. In the editing window, type the code for the program.

To create a progr am programmatically

 In the Command window, use the MODIFY COMMAND to open an editin g window.

See Also
Concepts

How to: Edit Programs


How to: Save Programs
Working with Programs
Pro ject Manager Window
MODIFY COMMAND Command
Command Window (Visual FoxPro)

9e43c0bc-b112-4936-a2a1 -21187b4dd139 How to: Create Programs

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Edit Programs
See Also Send Feedback

After creating a program, y ou can make changes to it o r an existing program.


Note:
After editing a program, make sure you save it.

To edit a standalone progr am

1. On the File menu, click Open.

2. In the Open dialog box, choo se Pro gram in the Files of type list to show only program files.

3. Click the program you want to modify, and then OK.

To edit a program in a project

1. Open the project for y our application in the Pro ject Manager.

2. In the Pro ject Manager, expand the Code node, and then the Pro grams node.

3. In the Pro grams node, select the program you want, and click Mo dify.

To edit a program programmatically

 In the Command window, perform one of the following:

 Use the MODIFY COMMAND with the name of the program (.prg) file to open an editing windo w for the program. For
example:

Copy Code
MODIFY COMMAND MyProgram
 Use the MODIFY COMMAND with a q uestion mark (?) to d isplay the Open dialog box so you can browse for and
select a program file. For examp le:

Copy Code
MODIFY COMMAND ?

See Also
Concepts

How to: Save Programs


How to: Run Programs
Working with Programs
Pro ject Manager Window
MODIFY COMMAND Command
Command Window (Visual FoxPro)

7fc7f4ab -8a00 -4b03-9617-57251a631c26 How to: Edit Programs

c
d
e
f
g Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Format Code in Programs
See Also Send Feedback

You can format specific blocks of code o r the entire program file by setting the options you want in the Beautify Options dialog box
and then apply the formatting options you chose. After formatting the code using the Beautify tool, you can make any additional
chan ges in the formatting of th e code.

To set code formatting options


1. Open the program file.

2. To format a specific b lock of code, select the code you want to format.

Note:
To format the entire program, do not select any code.
3. On the Tools menu, click Beautify .

4. In the Beautify Options dialog box, select the formatting options you want.

The formatting process uses the top line in th e block selected for determin ing the base indentatio n level.

To apply formatting options to code

 In the Beautify Options dialog box, click Run.

See Also
Concepts

How to: Edit Programs


How to: Save Programs
Working with Programs
Beautify Options Dialog Box

e13a68df-8473-4df6 -b331-b600b218f37e How to: Format Code in Programs

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Save Programs
See Also Send Feedback

After you create or modify a pro gram, save your changes.

To save a program

 On the File menu, click Save.

Visual FoxPro saves programs with the .prg file name extension. After you save your program, you can run o r modify it.

Note:
If you save a program that does not have a name, Visual FoxPro displays the Save As dialog box so you can specify a name for the
program. If you save a program created in th e Pro ject Manager, Visual FoxPro adds the program to the project.

See Also
Concepts

How to: Edit Programs


How to: Run Programs
Working with Programs

27468426-b91b-4472-bcb4-c99b4c517ea5 How to: Save Programs

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Run Programs
See Also Send Feedback

After you save a program, you can run it.

To run a standalone program

1. On the Pro gram menu, click Do.

2. In the Do dialog box, browse for and select the program you want.

3. Click Do.

To run a progr am from a project

1. Open the project for y our application in the Pro ject Manager.

2. In the Pro ject Manager, expand the Code node, and then the Pro grams node.

3. In the Pro grams node, select the program you want, and click Run .

To run a progr am programmatically

 In the Command window, perform one of the following:

 Use the DO co mmand with the name of the program (.prg) file to run the program. Fo r example:

Copy Code
DO MyProgram
 Use the DO co mmand with a question mark (?) to display the Do dialog box so you can browse for and select a program
file. For example:

Copy Code
DO ?

See Also
Concepts

How to: Edit Programs


Working with Programs
DO Command
Command Window (Visual FoxPro)
Pro ject Manager Window

25b81956-c293-42dd-812b-3cac4e9 38c66 How to: Run Programs

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Working with Procedures and Functio ns
Send Feedback
Visual FoxPro includes a wide range of native functions that y ou can use to perform data manipu lation or other operations. Functions
in Visual FoxPro perform operations on data and return results with a specific type. You can also create procedures and functions to
store code that performs frequen tly or commonly used routines in your programs.

In This Section
User-Defined Procedu res and Fu nctions

Introduces procedures and functions that you can define and create in Visual Fox Pro .

Parameters in Procedures and Functions

Describes how data passes to procedures and functions for processing.

How to: Create Procedures and Functions

Explains how to create procedures and functio ns.

How to: Call Procedures and Functions

Explains how to call native functions as well as user-defined functions and procedures.

Verifying Data Passed to Procedures and Functions

Describes ways to verify that correct data passes to pro ced ures and function s.

Returning Data from Procedures and Functions

Describes how to return data from procedu res and functions.

Reference
Functions

Lists functions available in Visual FoxPro.

Related Sections
Passing Data to Parameters

Describes how data passes to parameters by reference or by v alue.

Working with Programs

Introduces how to create and work with Visual FoxPro programs.

Pro gramming in Visual FoxPro

Describes aspects of programming, such as basic programming concepts, working with programs, object-oriented
programming, and optimizing application s, in Visual FoxPro.

a6d6b28b -6366-406f-a7ea -3df9d870a770 Working with Procedures and Functio ns

c
d
e
f
g Visual Basic
c
d
e
f
g C#
c
d
e
f
g Visual C++
g
c
d
e
f J#
c
d
e
f
g JScript
Visual FoxPro 9.0 SP2
User-Defined Procedu res and Fu nctions
See Also Send Feedback

Defining commonly and frequently used routines and operations as sep arate procedures and functions can reduce program size and
complexity, making code easier to read and maintain. Fo r example, you need to mak e changes only once in the procedure or function
instead of multiple times throughout your program. Procedures and functions make it possible for you to keep commonly used cod e
in a single location so you can call it from different parts of your application.

Conventio nally, a procedure contains code that performs an operation, while a function con tains code that performs operations and
returns a specific value. Most, if not all, native Visual FoxPro functio ns return values. In Visual FoxPro, both procedures and
functions can return values. When you create procedures an d fun ctions, you can choose whether to follow the conven tion of
returning a value only fro m functions.

For example, the following lines of code illustrate the b asic form of a procedure and function:

Copy Code
PROCEDURE myProcedure
* Insert procedure co de.
ENDPROC

FUNCTION myFunction
* Insert function code.
RETURN myFuncReturnVal ue
ENDFUNC

In their basic forms, procedures and functions might not seem useful or different from each other. However, procedures and functions
can also accept and process data that the calling program passes to them through parameters, which you can include as part of
procedure and function definitions and calls. Data that passes to procedures and functions are sometimes referred to as "arguments".
Pro cedu res and functions also differ in the way that programs pass data to them by default. For more information, see Parameters in
Pro cedu res and Functions.

Functions that yo u create in Visual Fo xPro are sometimes called user-defined functions (UDFs). You can include procedures o r
functions with other normal executable code in a program (.prg) file or standalone in a separate .prg file.

Note:
If you include procedures and functions with other code, they must exist at the end of the .prg file following all other normal code.
You cannot include normal executable program code following procedures and functions in a .prg file. Only other user-defined
procedures, functions, and class definitions can follow the first PROCEDURE or FUNCTION statement in the file.

See Also
Concepts

How to: Create Procedures and Functions


How to: Call Procedures and Functions
Working with Procedures and Functio ns

f8dde7e9 -6ba8-4f65-a797-8cbbcde1f8 9d User-Defined Procedu res and Fu nctions

c
d
e
f
g Visual Basic
c C#
d
e
f
g
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Parameters in Procedures and Functions
See Also Send Feedback

When a pro gram calls a procedure or function, it can pass data to the procedure or function for processing. However, when you
create a pro ced ure or function that performs o peratio ns on data that passes to it from the calling program, the procedure or function
must contain parameters in its definition to handle the data. The followin g sections contain info rmation about working with
parameters:

 Defining Parameters in Pro ced ures and Functions

 Passing Data to Procedures and Functions

Defining Parameters in Procedures and Functions


When a pro gram passes data to a procedure or function, the parameters in the procedure or function handles that data so the
procedure or function can perform operations on the data. When you want to create procedures and functions that p rocess data that
the calling program passes to them, you n eed to include parameters in th e procedure and function definitions.

The following lines of code illustrate the basic format for including parameters in procedure definition:

Copy Code
PROCEDURE myProcedure
LPARAMETERS Par1, Par2, Par3, ...
* Insert procedure co de.
ENDPROC

-OR-

Copy Code
PROCEDURE myProcedure( Par1, Par2, Par3 , ...)
* Insert procedure cod e.
ENDPROC

The first procedure includes an LPARAMETERS statement that can contain one or more parameters. The second procedure lists the
same parameters enclosed by parentheses (()) immediately following the procedure name. Using the LPARAMETERS statement or
enclosing th e parameter list in parentheses defines the parameters with local scope for the procedure. You can also use the
PARAMETERS keyword instead of LPARAMETERS to accept privately scoped parameters. You can pass multiple values to a
procedure or function by separating the values with commas.

For example, the following examples show procedure definitions th at includ e parameters. The first procedure includes an
LPARAMETERS statement and two parameters, myPar1 an d myPar2. The second procedure lists the same parameters enclo sed b y
parentheses (()) immediately following the p rocedure name. Both procedures add the value in myPar2 to myPar1 an d assign the
result to myPar1 . By default, data passes to procedures by reference, so the new value of myPar1 replaces its original v alue.

Copy Code
PROCEDURE myProcedure
LPARAMETERS myPar1, m yPar2
myPar1 = myPar1 + myP ar2
ENDPROC

-OR-

Copy Code
PROCEDURE myProcedure(my Par1, myPar2)
myPar1 = myPar1 + myPa r2
ENDPROC

You can include parameters similarly in a function definition. For more in formation, see PROCEDURE Command , FUNCTION
Command , LPARAMETERS Command, and PARAMETERS Command.

Passing Data to Procedures and Functions


You can pass data, or sp ecifically, "arguments", from yo ur program to p rocedures and functions in different ways, depending on the
following:

 Whether you want to pass data by reference or by value. For more information, see Passing Data to Parameters.
 How you call the procedure or function . For more information, see How to: Call Procedures and Functions .

For example, wh en you call a procedure with the DO co mmand, you can pass data using the WITH clause and a parameter list. In
the followin g example, the variables myVar an d myVar2 co ntain the values 4 and 5. When you call the procedure myProcedure using
the DO co mmand, the parameter list in th e WITH clause passes the variables to the procedure:

Copy Code
myVar = 4
myVar2 = 5
DO myProcedure WITH myVa r, myVar2

By default, variables and array s pass to procedures by reference. Therefore, changes made in the procedure to passed variables and
arrays are p assed back to the calling program. For example, sup pose the procedure increments the value in myVar by the v alue in
myVar2 . The modified value of myVar becomes the new value of myVar when the procedure returns control to the calling program.

Alternatively, if you want to use the DO co mmand but wan t to pass data by value, enclose each parameter with parentheses (()) as
sho wn in the following example:

Copy Code
DO myProcedure WITH (myV ar), (myVar2)

When you call a function, y ou can pass data using a parameter list enclosed in parentheses (()) as shown in the follo wing line of
code:

Copy Code
myFunction(myVar, myVar2 )

By default, variables and array s pass to user-defined functions by value. Therefore, changes made in the fu nction to passed variables
and arrays are not passed back to the callin g pro gram. However, you can pass variab les and arrays by reference by prefacing
variables and arrays with the at sign (@) as shown in the following line of code:

Copy Code
myFunction(@ var1, @var2, ...)

The following table su mmarizes the ways you can pass variab les to procedures and functions in the example.

Procedure or function call Comments


DO myProcedu re WITH Calls a procedure and passes
var1, var2, ... variables by reference.
DO myProcedu re WITH Calls a procedure and passes
(var1), (var2), ... variables by value.
Calls a function and passes
myFunction(var1 , var2, ...)
variables by value.
myFunction(@var1, @var2, Calls a function and passes
...) variables by reference.

See Also
Concepts

User-Defined Procedu res and Fu nctions


Verifying Data Passed to Procedures and Functions
How to: Create Procedures and Functions
Working with Procedures and Functio ns

6ac4 f04d -e703-4950-97d7 -5abeac6 2e50a Parameters in Procedures and Functions

g
c
d
e
f Visual Basic
c
d
e
f
g C#
g
c
d
e
f Visual C++
c
d
e
f
g J#
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Create Procedures and Functions
See Also Send Feedback

You can create p rocedures and functions programmatically.

To create a procedure

1. Begin the procedure definition with the PROCEDURE co mmand and the procedure name.

2. To define parameters, on the second line of the procedure definition, include an LPARAMETERS or PARAMETERS
statement with a list of parameters.

-OR-

On the same line as the PROCEDURE statement and immediately following the procedure name, include a parameter list
enclosed in parentheses.

3. On the following lines, include the code statements you want to execute in the procedure.

4. End the proced ure definition with the ENDPROC keyword.

For example, the following lines of code show a basic example of a procedure:

Copy Code
PROCEDURE myProcedure
LPARAMETERS myPar1, m yPar2
myPar1 = myPar1 + myP ar2
ENDPROC

-OR-

Copy Code
PROCEDURE myProcedure(my Par1, myPar2)
myPar1 = myPar1 + myPa r2
ENDPROC

By default, values pass to procedures by reference. Therefore, ch anges made to the passed values in the procedure are passed b ack to
the calling program.

For more info rmation, see PROCEDURE Command, PARAMETERS Command, and LPARAMETERS Command.

To create a function

1. Begin the functio n definition with the FUNCTION co mmand and the function name.

2. To define parameters, on the second line of the procedure definition, include an LPARAMETERS or PARAMETERS
statement with a list of parameters.

-OR-

On the same line as the FUNCTION statement and immediately following the function name, include a parameter list
enclosed in parentheses.

3. On the following lines, include the code statements you want to execute in the function.

4. Include a RETURN statement when you want to return a value from the function and contro l of code execution to the calling
program.

5. End the proced ure definition with the ENDFUNC keyword.


For example, the following lines of code show a basic example of a function:

Copy Code
FUNCTION myFunction
LPARAMETERS myPar1, my Par2
myFuncReturnValue = my Par1 + myPar2
RETURN myFuncReturnVal ue
ENDFUNC

-OR-

Copy Code
FUNCTION myFunction(myPa r1, myPar2)
myFuncReturnValue = my Par1 + myPar2
RETURN myFuncReturnVal ue
ENDFUNC

By default, values pass to user-defined functions by value. Therefore, changes made to the passed values in the function are not
passed back to the calling program.

For more info rmation, see FUNCTION Command, PARAMETERS Command , and LPARAMETERS Command.

See Also
Concepts

How to: Call Procedures and Functions


Passing Data to Parameters
Returning Data from Procedures and Functions
User-Defined Procedu res and Fu nctions
Working with Procedures and Functio ns

864b609a-6e86 -41d8-a04f-ccb1 da701f7a How to: Create Procedures and Functions

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Call Procedures and Functions
See Also Send Feedback

You can call native Visual FoxPro functions, user-defined functions, and procedures in different ways. In addition, you can call user-
defined functions (UDFs) the same way you call procedures. You can call p rocedures that you create in a program (.prg) file as if
they were standalone programs or as functions if your procedures return values you want to use.

Tip:
If you include procedures and user-defined functions in a separate program (.prg) file, you can open those files using the SET
PROCEDURE command. For example, suppose you have a file called ProcFile.prg. The following line of code opens the file:
Copy Code
SET PROCEDURE TO ProcFil e.prg

To call a Visual FoxPro or user -defined function

 Call the function without storing the return value.

-OR-

 Call the function and assign the return value to a variable.

-OR-
 Include the fun ction call within another command or function.

Some functions also accept data as arguments that are passed from the calling program. For more information, see Passing Data to
Parameters an d Parameters in Procedures and Functions .

In the following ex ample, the first line of code calls the DATE( ) function, which retu rns the current system date, with out performing
any operations with the return value. The second line of code stores the return valu e to a variable named dToday . The third line of
code includes the function in another command and sends the return value to the currently active output wind ow. The fou rth line of
code includes the function in another function and p asses the return valu e to the outer functio n, which returns the day of the week.

Copy Code
DATE( )
dToday = DATE( )
? DATE( )
DOW(DATE( ))

For more info rmation, see Returning Data from Procedures and Functions.

To call a procedure

 Use the DO co mmand followed by the proced ure name.

In the following ex ample, the DO co mmand calls procedures named myProc1 and myProc2. The first line o f code calls myProc1
withou t arguments. The second line of code includes the WITH clause in the DO co mmand to pass a list of arguments to myProc2.

Copy Code
DO myProc1
var1=4
var2=5
DO myProc2 WITH (var1, v ar2)

For more info rmation, see DO Command.

See Also
Concepts

User-Defined Procedu res and Fu nctions


How to: Create Procedures and Functions
Working with Procedures and Functio ns

a7cb 5777-83ab-4c2b-80e5 -9bdeb92c2162 How to: Call Procedures and Functions

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Verifying Data Passed to Procedures and Functions
See Also Send Feedback

When passing data or "arguments" to parameters in procedures and functions, it is recommended that you verify that the data that
procedures and functions receive is as expected. You can use the TYPE( ) an d PARAMETERS( ) functions to verify the type and
number of arguments passed to procedures and functions.

Verifying Data Type Passed to Parameters


You can use the TYPE( ) function to verify that data passed to parameters has the correct type. In the following example, the
function accepts a date value through the parameter dDate. The function retu rns a date th at is 14 days later than the date that was
passed:
Copy Code
FUNCTION plus2weeks( dDa te )
PARAMETERS dDate
RETURN dDate + 14
ENDFUNC

The parameter in the function requires a value with Date type. The following version of the function includes code that uses the
TYPE( ) function to make sure that the passed value has the correct type:

Copy Code
FUNCTION plus2weeks( dDa te )
IF TYPE("dDate") = "D "
RETURN dDate + 14
ELSE
MESSAGEBOX( "Funct ion requires a date valu e." )
RETURN { - - } && Return an emp ty date.
ENDIF
ENDFUNC

Verifying the Correct Number of Arguments


When a pro gram passes more arguments than th e procedure or function expects, Visual FoxPro generates an error message. When a
program passes fewer arguments than the procedure or function ex pects, the remaining parameters are initialized to False (.F.).

For example, suppose you include two parameters in a procedure definition, but you call the procedure with three arguments, Visual
FoxPro generates an error message. However, if you call the procedure with only one arg ument, the remaining parameter is
initialized to False (.F.). However, there is no way to know whether the argument for the last parameter was truly omitted or merely
evaluated to .F. Therefore, the following example code uses the PARAMETERS( ) function to check for the appropriate number of
arguments:

Copy Code
FUNCTION SaveValue( cSto reTo, cNewVal, lIsInTabl e )
IF PARAMETERS( ) < 3
MESSAGEBOX( "Too f ew parameters passed." )
RETURN .F.
ENDIF
IF lIsInTable
REPLACE (cStoreTo) WITH (cNewVal)
ELSE
&cStoreTo = cNewVa l
ENDIF
RETURN .T.
ENDFUNC

See Also
Concepts

Parameters in Procedures and Functions


How to: Create Procedures and Functions
Working with Procedures and Functio ns

9f0bfc38-ccca-4c38 -ac38 -d6c6c55b7127 Verifying Data Passed to Procedures and Functions

c
d
e
f
g Visual Basic
c C#
d
e
f
g
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Returning Data from Procedures and Functions
See Also Send Feedback

Conventio nally, functions return values to the calling program. However, in Visual FoxPro, you can return values from pro ced ures
and functions. When procedures and functions do not include explicit RETURN statements that return a specified value, Visual
FoxPro includes an implicit RETURN statement that returns a default value of True (.T.) automatically. Generally, you want to use
the RETURN co mmand to return a specified valu e from functions, for example, as a processing result or to indicate wheth er the
function operation succeeded.

Note:
The RETURN co mmand also returns control over code execution to the calling program. For more information, see RETURN
Command .

In the following ex ample, suppose you pass a date to the following functio n. The function returns a date that is 14 days later th an the
date that was passed :

Copy Code
FUNCTION plus2weeks
PARAMETERS dDate
RETURN dDate + 14
ENDFUNC

You can then assign the return value from the function to a variable as shown in the following line of co de:

Copy Code
dDeadLine = plus2weeks(D ATE())

Assigning Return Values from Procedures and Functions


You can assign values returned from procedures and functio ns ex plicitly, fo r example, to a variable, b y using the equal sign (=)
operator or pass the return value directly, for example, to another function.

In the following ex ample, suppose the function myFunc returns a specific value. The first line of code assig ns the retu rn value from
myFunc to a variable named myVar. The second line of code passes th e return value from myFunc directly to a Visual FoxPro STR
( ) function, whose return value is then displayed to the current active output wind ow using the ? co mmand:

Copy Code
myVar = myFunc( )
? STR( myFunc( ) )

See Also
Concepts

How to: Create Procedures and Functions


How to: Call Procedures and Functions
Working with Procedures and Functio ns

276a7534 -30de-47af-a0f7 -99ac7bebcc4a Returning Data from Procedures and Functions

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Passing Data to Parameters
See Also Send Feedback

You can pass data, such as variables and array elements, as "arg uments" to parameters by referen ce or by value. Passing data by
reference saves changes made to data and passes those changes back to the calling program. Passing data by value passes a copy of
the data for processing, leaving the original data intact.

By default, data passes to procedures by reference and to user-defined functions (UDFs) by value. However, you can change the
default protocols for passing data through parameters, although Visual FoxPro alway s passes objects by reference.
Note:
When passing entire arrays to parameters, you must pass them by reference. If you d o not p ass arrays by reference, only the first
element is passed. Therefore, individual array elements are always passed by value.

See Also
Concepts

How to: Pass Data to Parameters b y Reference


How to: Pass Data to Parameters b y Value
Parameters in Procedures and Functions
Pro gramming in Visual FoxPro

9937ae10-df44-461f-a7db -64ba43000ca6 Passing Data to Parameters

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Pass Data to Parameters b y Reference
See Also Send Feedback

You can pass data to p arameters by reference throughout a program or at specific locations.

To pass parameter s by reference throughout a program

 Precede code where you want to pass data to parameters by reference with the following line of code:

Copy Code
SET UDFPARMS TO REFERENC E

For more info rmation, see SET UDFPARMS Command.

To pass parameter s by reference at specific locations

 Preface the variable or array name with an at sign (@) as shown in the following example:

Copy Code
myFunc(@var1, var2)

See Also
Concepts

How to: Pass Data to Parameters b y Value


Passing Data to Parameters

dfbfc824-4d4a-442f-8ecc-12b55a64edbd How to: Pass Data to Parameters b y Reference

c
d
e
f
g Visual Basic
c C#
d
e
f
g
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Pass Data to Parameters b y Value
See Also Send Feedback
You can pass parameters by value throughout a program or at specific locations.

To pass parameter s by value throughout a program

 Precede code where you want to pass data to parameters by value with the following line of code:

Copy Code
SET UDFPARMS TO VALUE

Note:
Using SET UDFPARMS TO VALUE does not affect the WITH clause in the DO co mmand, which, by default, passes arguments to
parameters by reference.

For more info rmation, see SET UDFPARMS Command.

To pass parameter s by value at specific locations

 Enclose the variable or array name with parentheses (()) as shown in the following example:

Copy Code
DO myProcedure WITH (myV ar), (myVar2)

See Also
Concepts

How to: Pass Data to Parameters b y Reference


Passing Data to Parameters

bf0701fc-8b8e-4187-b33a-f0d1b3afcd06 How to: Pass Data to Parameters b y Value

c
d
e
f
g Visual Basic
c C#
d
e
f
g
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Object-Oriented Programming
Send Feedback

While Visual FoxPro supports standard pro ced ural programming, it also includes the p ower and flexibility of o bject -oriented
programming. Object -oriented design and object-oriented prog ramming represent a change in focus from standard procedural
programming. Instead of thinking about prog ram flow from the first line of co de to the last line of code, think about creatin g objects.
You can create and manipulate objects as self-contained components o f an application and use them to provide public functionality
that you can expose to users as well as private.

In This Section
Working with Classes in Visual FoxPro

Introduces classes in Visu al FoxPro and how to use them to create ob jects.

Working with Objects in Visual Fox Pro

Introduces objects in Visual Fo xPro and how to create an d use them.

Understanding the Event Model


Introduces events and how you can use them to perform operations when the system or user p erforms an action.

Related Sections
Pro gramming in Visual FoxPro

Describes aspects of programming, such as basic programming concepts, working with programs, object-oriented
programming, and optimizing application s, in Visual FoxPro.

Working with Programs

Introduces how to create and work with Visual FoxPro programs.

Optimizing Applicatio ns

Describes ways to optimize your stable application's performance by makin g it smaller and faster.

Accessing APIs

Describes how to ex tend Visual FoxPro if your application h as requirements that cannot be met by the built in features by
taking advantage of external libraries such as Microsoft ActiveX con trols or dynamic-link libraries (DLLs).

925ef3b 8-48dc-4ea1 -9112-a7afc2d916 1e Object-Oriented Programming

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Working with Classes in Visual FoxPro
Send Feedback

Visual FoxPro includes th e cap ability to work with classes as part o f providing the features of object-oriented prog ramming. Wh en
you design an d create a class, you are building a template so you can create objects from that class. Visual FoxPro includes designers
and other tools for creating and managing classes.

In This Section
Classes in Visual FoxPro

Pro vides an overview of classes in Visual FoxPro and discusses the benefits that classes provide.

Base Classes in Visual FoxPro

Pro vides a list of the base classes provided in Visual FoxPro.

Subclasses in Visual FoxPro

Pro vides an overview of subclasses in Visual FoxPro and provides possible uses for them.

Considerations for Creating Classes

Contains information on best practices for creating classes.

How to: Create Classes and Subclasses

Describes how to create classes and subclasses usin g the Visual FoxPro Class Designer or programmatically.
How to: Implement Strong Typing for Class, Ob ject, and Variable Code

Describes how to implement strong typing so that you h ave more control over code and can make IntelliSense available for
certain Visual FoxPro elements.

How to: Modify Classes

Describes how to modify a class using the Class Designer and when it is in a project.

How to: Add Properties to Classes

Describes how you can add custom properties to a class.

How to: Create Access and Assign Methods

Describes how you can create new Access and Assign Methods for p roperties.

How to: Add Methods to Classes

Describes how you can add custom methods to a class.

How to: Add Code to Methods and Events

Describes how to ad d custom code to a method or event.

How to: Modify Class and Class Member Attributes

Describes how to ad d or ed it th e description for classes and attributes for cu stom properties and methods.

How to: Remove Properties and Methods from Classes

Describes how to remove custom properties and metho ds from a class.

How to: Specify Design-Time Appearance for Classes

Describes how you can specify the appearance of non -visual classes in design -time.

How to: Add Classes to Visual FoxPro Tools

Describes how to ad d custom classes to the Visu al FoxPro Toolbox and Form Controls toolbar an d how to register a class
library.

Access and Assign Metho ds

Pro vides an overview about Access and Assign methods th at you can u se to execute code when querying or attempting to
chan ge the value of a property.

Pro tecting and Hidin g Class Members

Pro vides an overview about designating properties and methods as hidden or protected.

Overriding Default Property Settings

Pro vides an overview about overriding the default setting of a property for a user-defined class.

Overriding and Calling Paren t Class Code

Pro vides an overview about how to call or override parent class code.

Related Sections
Working with Objects in Visual Fox Pro

Introduces objects in Visual Fo xPro and how to create an d use them.

Understanding the Event Model

Introduces events and how you can use them to perform operations when the system or user p erforms an action.

Object-Oriented Programming

Discusses how you can create self-contained application componen ts that respond to user actions and to the system and which
can be easily maintained and reused.

Pro gramming in Visual FoxPro

Describes how understanding object -oriented prog ramming techniques and the ev ent-driven model can maximize your
programming productivity.

7f106091 -a2c8 -42aa-a8b5-dbeecb1f95 02 Working with Classes in Visual FoxPro

c
d
e
f
g Visual Basic
c C#
d
e
f
g
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Classes in Visual FoxPro
See Also Send Feedback

Classes define properties, metho ds, and events, which are characteristics and functionality that objects po ssess and that you can use
to manipulate objects. Classes can also contain other objects or data members such as variables. When an object, or instance, is
created from a class, it co ntains the properties, metho ds, events, and any o ther objects or members as defined by the class.

The properties that a class defines specify characteristics for an object of that class. For example, the CommandButton class has a
Name prop erty, wh ich defines the name of the command button as o pposed to the Caption prop erty, wh ich defines the text that the
command butto n displays to the user.

The methods of a class define and store procedure code that runs when you call the method for an object of that class. For example,
the CommandButton class has a Move method, which moves the command bu tton to coordinates that you specify.

The events of a class define code that executes when the system or user performs actions that trigger the events for an object of that
class. For examp le, the CommandButton class contains a Click ev ent, which is a procedure that you can use to define cod e that
executes when the user clicks the command button.

Classes can also contain other objects, for example, a Form class can contain a control object, such as a command butto n. You can
also specify data members, such as variables, as p art of a class.

The following sections provide more information about Visual Fo xPro classes:

 Benefits of Using Classes

 Types of Visual FoxPro Classes

For more info rmation about objects in Visual FoxPro, see Working with Objects in Visual Fox Pro .

Benefits of Using Classes


Classes provide the following features that make it possible for you to create reusable and more maintainable code:

 Encapsulation
Encapsulation, which includes packaging property and method code into an object, hides unnecessary complexity and h elps
contribute to abstraction. Abstractio n makes it possible for you to focus on aspects of the object that you want or need to use
instead of the low-level details.

For example, wh en a person uses a computer, the person usually does not want to know how it operates, such as how it
processes data or maintains files. The person wants to accomplish tasks, such as write a letter, and does not need to know how
those tasks are performed.

Lik ewise, a list box class encapsulates properties controlling how items display in the list box and functionality determining
the actions performed when choosing items in the list box into a single control.

 Subclass creation

For more info rmation, see Subclasses in Visual FoxPro.

 Inheritance

For more info rmation, see Subclasses in Visual FoxPro.

These features help you create and maintain code more easily and quickly.

Types of Visual FoxPro Classes


Visual FoxPro classes, and by extension, objects, fall into two primary types: container classes and control classes. Classes can also
be visual or non -visual.

Container Classes and Control Classes

Containers can consist of other objects, such as controls, and prov ide access to the objects they contain. Contro l classes are more
encapsulated than con tainer classes; however, for that reason, they can be less flexible. Control classes do not have an AddObject
Method.

For example, suppose you create a container class that consists of two list boxes and two command buttons. You then add an object
based on the container class to a form. You can manipulate each object in the container at d esign time and run time; for example, y ou
can ch ange the positions of the list b oxes or the captions of the command bu ttons. Yo u can also add other objects to the con tainer at
design time; for example, you can add labels to identify the list boxes.

The following table lists examples of objects that can exist in co ntainer classes.

Container Can contain


Headers and any objects except fo rm sets,
Column
forms, toolbars, timers, and other colu mns
CommandGroup Command buttons
Container Any controls
Control Any controls
Any controls, data environment, page
Custom
frame, container, custom
DataEnvironment Cursors, relations, and cursor adap ters
FormSet Forms, toolbars
Page frames, data environment, any
Form
controls, containers, custom
Grid Columns
OptionGroup Option buttons
PageFrame Pages
Page Any controls, containers, custom
Project Files, servers
Toolbar Any controls, page frame, co ntainer

Visual and Non-Visual Classes

In Visual FoxPro, objects and controls created fro m visual classes display a visual element at design time and run time. Objects and
controls based on non-visual classes, such as the Custom class and Timer co ntrol, display a visual element only at design time but
not at run time.

See Also
Concepts

Base Classes in Visual FoxPro


Considerations for Creating Classes
How to: Create Classes and Subclasses
Working with Classes in Visual FoxPro

5d464956-a8de-419c-b09d-1b4dc2efefe6 Classes in Visual FoxPro

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Base Classes in Visual FoxPro
See Also Send Feedback

Visual FoxPro provides a default set of classes, or base classes, that you can use immediately to provide basic functionality in you r
application. Th e following table lists the base classes in Visual FoxPro, though no t all base classes are available in the Class Designer
or for creating subclasses.

CheckBox Collection Column* ComboBox


Command Button Command Group Container Contro l
Cursor CursorAdapter Custom DataEnvironment
EditBox Emp ty * Exception Form
FormSet Grid Header* Hyperlink
Image Label Lin e ListBox
OLE Bound OLE Container Option Button Option Group
Page PageFrame Pro jectHook Relation
Session
ReportListener Separator Shape
Object
Spinner TextBox Timer ToolBar
XMLAdapter XMLField XMLTable

* Not available for subclass creation

All Visual FoxPro base classes except the Emp ty class recog nize the following minimum set of events:

 Init Event
 Destroy Event

 Error Event

All Visual FoxPro base classes except the Emp ty class have th e following minimum set of properties:

 Class Property

 BaseClass Prop erty

 ClassLibrary Property

 ParentClass Property

See Also
Concepts

Classes in Visual FoxPro


Considerations for Creating Classes
How to: Create Classes and Subclasses
Working with Classes in Visual FoxPro

3da59d80 -71ab -4ed9 -92fe-803d6b5fd96f Base Classes in Visual FoxPro

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Subclasses in Visual FoxPro
See Also Send Feedback

You can create a n ew class or a subclass from most of the Visual FoxPro base classes or other existing classes. A subclass can
include some or all the functionality of the original, or parent, class, plus any additional characteristics, such as custom default
properties, or functionality that y ou want to include to customize the new class.

Creating and using subclasses offer the benefits of reusability by helping to decrease the amount of code you need to write, and
inheritance, which saves time and effort updatin g classes when you make changes to a parent class. When you modify a parent class,
the changes you make propagate to all su bclasses that inherit from th e parent class.

For example, suppose you have a command button class. You can create a subclass from the command button class that co ntains all
the standard prop erties, meth ods, and events for a command b utton plus additional properties or functionality you want to include,
such as displaying the comman d button with a certain color or size or performing action s such as displaying a specific message when
clicked.

Subclasses are not limited to a single class. For example, you can add multiple controls to a container class definition, such as a form
class. Many of the classes in the Visual FoxPro sample class library fall into this category. For more information, see Sample Class
Lib raries.

See Also
Concepts

Considerations for Creating Classes


How to: Create Classes and Subclasses
Working with Classes in Visual FoxPro

a79660c6-2b22-4286-8215-fc5fcf053925 Subclasses in Visual FoxPro


g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Considerations for Creating Classes
See Also Send Feedback

There are many different contexts for creating and using classes and subclasses. However, using strategic planning, you can
determine more effectively wh ich classes you need to design and the type of functionality to include in those classes. When creating
classes, remember the following considerations.

 Be selective when creating classes.

Though you can create a class for every control and form you might want to use, this strategy might not be the most effective
way to design your application. The result might be that you have many classes that perform the same task but need to be
maintained separately.

 Create and use control classes for encapsulating generic functionality.

You can provide generic functionality in your application creating control classes. For example, you can create command
buttons that users click to move record pointers in tables, clo se forms, or open a Help file and save them as classes so you can
add the controls to forms.

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

 Determine the functionality yo u want to include for classes at the class level, subclass level, and object level in advan ce.

When you create subclasses and objects from the classes y ou create, you can include additional properties, methods, an d events
in those subclasses, and by extension, objects created from those classes. You can also choo se to override default property
values as well as method and event code as specified by th e original class.

 Pro vide a consistent look and feel for your application.

You can create form, fo rm set, and control classes with a distinctive appearance so that all th e componen ts of your application
have the same look. For example, you can add graphics and specific color patterns to a form class and use that class as a
template for all forms you create. You can create a text box class with a distinctive appearance, such as a shad owed effect, and
use this class th roughout yo ur application any time you want to add a text box.

See Also
Concepts

Classes in Visual FoxPro


How to: Create Classes and Subclasses
Working with Classes in Visual FoxPro

501e2002 -afdd -4a21 -874c-02431ef46a56 Considerations for Creating Classes

c
d
e
f
g Visual Basic
c C#
d
e
f
g
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Create Classes and Subclasses
See Also Send Feedback
You can create classes an d subclasses using the Visual FoxPro Class Designer or pro grammatically. When you use the Class
Designer to create classes, you can view th e class as you design it.

Tip:
For convenience and speed, you might wan t to keep a class and all its subclasses in o ne class library. If you h ave a class that contains
elements from different class libraries, these libraries must all be open , so it might take longer to initially load the class at design time
and run time.

To create a class or subclass

1. On the File menu, choose New.

2. In the New dialog box, choo se Class, and then click New File.

The New Class dialog box opens.

3. In the Class Name box of the New Class dialog box, type the name of the class.

4. In the Based On box, select th e name of a Visual FoxPro base class.

Tip:
To create a user-defined class, choose Custom as the base class. When yo u choose the Custom base class, the class you create is a
non-visual class, which displays a v isual element at design time but not at run time. For more information, see Custom Object an d
How to: Specify Design-Time Appearance for Classes.

-OR-

Click the ellipsis (...) button to select a visual class lib rary (.vcx) file.

5. In the Sto re In box, type the name of the class library file for sto ring the class.

6. Click OK.

The Class Desig ner opens and displays the class.

7. When you are finish ed with creating the class, save the class.

The class is sav ed in a Visual FoxPro visual class library (.vcx ) file.

Visual FoxPro stores classes you create using the Class Designer in visual class library (.vcx) files. These classes include visual and
non-visual classes.

For more info rmation about base classes in Visual FoxPro, see Base Classes in Visual FoxPro . For more information about the Class
Designer, see Class Designer.

You can also add classes and subclasses to an existing class library. For more information, see How to: Add Classes and Subclasses
to Class Libraries.

To create classes or subclasses in a project

1. Open the project for y our application.

2. In the Project Manager, choose the Classes tab, and click New.

The New Class dialog box opens so you can specify information for the new class or subclass.

3. Follow the steps fo r creating a class o r subclass.

For more info rmation, see Pro ject Manager Window.


To create classes and subclasses programmatically

 Use the CREATE CLASS co mmand or DEFINE CLASS co mmand.

The CREATE CLASS co mmand opens the Class Designer, while the DEFINE CLASS co mmand is for programmatic use. You can
also create and add properties and methods and add code to respo nd to even ts for the class by using the DEFINE CLASS co mmand.

Note:
If you store class definitions in a program (.prg) file when you u se DEFINE CLASS, you can precede, but n ot follow, class
definitions with program code. This is similar to not followin g pro cedu res with program code in a program.

For more info rmation, see CREATE CLASS Command an d DEFINE CLASS Co mmand.

See Also
Concepts

Classes in Visual FoxPro


How to: Modify Classes
How to: Add Properties to Classes
How to: Add Methods to Classes
Working with Classes in Visual FoxPro

1aca0e8 a-9e0b-4e00-a434-0bbc081f328d How to: Create Classes and Subclasses

c
d
e
f
g Visual Basic
c C#
d
e
f
g
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Implement Strong Typing for Class, Ob ject, and Variable Code
See Also Send Feedback

To gain more control ov er your code, make coding easier and less vulnerable to errors, an d make IntelliSense functionality available
for visual objects, class references, ActiveX controls, COM servers, and user-defined code elements, use strong typing. OLEPUBLIC
type libraries also use strong typing.

Note:
Visual FoxPro is not a strongly typed language and does not require that you d eclare variables with a specific data typ es. Visual
FoxPro does not enforce strong typing at design time or run time.

For more info rmation, see IntelliSense Support in Visual FoxPro.

To implement strong typing

 For objects, method parameters, and values, use the AS clause in the DEFINE CLASS co mmand.

-OR-

 For parameter and variable declarations, use the AS clause in following commands:

 FUNCTION Command

 LOCAL Command

 LPARAMETERS Command

 PARAMETERS Command
 PROCEDURE Command

 PUBLIC Command

When you use the AS clause in code, IntelliSense displays a drop -down list of available types, including types from the following
sou rces:

 Visual FoxPro object base classes.

 Visual FoxPro data types.

The following example uses the AS clause in the DEFINE CLASS co mmand to implement strong typing for the custom
OLEPUBLIC class and th e method MyMethod:

Copy Code
DEFINE CLASS MyClass1 AS Custom OLEPUBLIC
FUNCTION MyMethod (My Param1 AS integer, MyPar am2 AS string) AS integ er
RETURN MyParam1
ENDFUNCTION
ENDDEFINE

The following example uses the AS clause in the LOCAL, PUBLIC, LPARAMETERS, PARAMETERS , and FUNCTION
commands to implement strong typing:

Copy Code
LOCAL oExcel AS "excel.a pplication"
oExcel = CREATEOBJECT("e xcel.application")
oExcel. && Displays a list of members.

PUBLIC ARRAY MyArray[2] AS _form OF ffc\_base


LPARAMETERS MyParam1 AS String OF _Base.vcx
PARAMETERS MyParam1 AS C ustom OF MyBase.vcx
FUNCTION MyFunction AS C ustom

See Also
Concepts

Considerations for Creating Classes


How to: Create Classes and Subclasses
How to: Modify Classes
Working with Classes in Visual FoxPro

21d951a7 -46de-46cc-a5f1 -32421bcef366 How to: Implement Strong Typing for Class, Ob ject, and Variable Code

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Modify Classes
See Also Send Feedback

After you create a class, you can make changes to the class. Changes that you make to the class propagate to all subclasses and
objects based on th e class. For example, suppose you add an enhancement to a class or fix a b ug in the class. All the subclasses and
objects based on th e class inh erit the change.

Caution:
If the class is being used in any other application components, do not change the Name prop erty of the class. Otherwise, Visual
FoxPro will not be able to locate the class when it is needed.

You can modify classes by opening th e Class Designer through th e Visual FoxPro IDE, the Class Browser, the Project Manager if the
class is part of a project, or programmatically.

To modify a class

1. On the File menu, choose Open.

2. In the Files of type box in the Open dialog box, select the class library you want to open, and click OK .

An Open dialog box appears for you to select a class from th e class library you opened.

3. In the Class Name list of the Open dialog box, select a class, an d click Open .

The class you selected op ens in the Class Desig ner.

-OR-

4. In the Class Browser, open th e class library you want.

For information about openin g class libraries, see How to: Open Class Lib raries .

5. In the class list, right-click the class and choose Modify.

The class you selected op ens in the Class Desig ner.

To modify a class in a project

1. Open the project containing the class you want.

2. In the Project Manager, select the class you want, and click Modify.

The class you selected op ens in the Class Desig ner.

You can also modify classes in visual class library (.vcx) files using the MODIFY CLASS co mmand to open the Class Desig ner.

For example, typing the followin g line in the Command window o pens the class MyClass, which is stored in the class library
My ClassLibrary, in the Class Designer so you can modify it:

Copy Code
MODIFY CLASS MyClass OF MyClassLibrary

For more info rmation, see MODIFY CLASS Command.

See Also
Concepts

Classes in Visual FoxPro


How to: Add Properties to Classes
How to: Add Methods to Classes
Working with Classes in Visual FoxPro

5a02a7f1 -54c4-427f-8e96-a9d50f8 4e180 How to: Modify Classes

c
d
e
f
g Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Add Properties to Classes
See Also Send Feedback
When you create a class, you can add custom properties to the class. For more info rmation about properties, see Classes in Visual
FoxPro .

Note:
When you create custom properties for classes, the properties apply to the class, not to individual components in the class.

You can add properties to classes usin g the Visual FoxPro IDE or programmatically.

To add a property to a class

1. Open the class in the Class Desig ner.

When the class opens in the Class Desig ner, the Class menu app ears.

2. On the Class menu, choose New Property .

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

4. In the Visibility box, choose the visibility level for the property.

5. To create an Access method, select Access Method. To create an Assign method, select Assign method. To create both
Access and Assign methods, select both boxes.

6. To specify a default value other than False (.F.) for the property, include a different default value in the Default Value box.

Tip:
To set the default value of a property an empty string (""), click in the Default Value box and press the SPACE key.
7. To specify a description to display for the property in the Properties window, include a descriptio n in the Description box.

Tip:
You can document valid property values in the Description box.
8. Click Add.

9. Continue ad ding properties, or if you are finished, click Close.

Note:
Pro perties in subclasses inherit the d efault property values that you specify unless you reset the default valu es to those of the parent
class. When you add a p roperty that can be set by th e u ser, the user might enter an invalid property value that can cause run -time
errors. It is recommen ded that you include code in your ap plication that validates values entered for the property or that you
document the valid property values.

After you add the property, it appears in the Properties window at the end of the properties list along with any default value that you
specified. You can change values for the property in the Pro perties Window (Visual FoxPro).

For more info rmation about opening classes, see How to: Modify Classes . For more information about visibility levels for prop erties,
see Pro tecting and Hidin g Class Members. For more information, see Access and Assign Metho ds an d How to: Create Access and
Assign Methods .

To add properties to classes programmatically

 Use the DEFINE CLASS co mmand.

At ru n time, you can add properties to o bjects by using the ADDPROPERTY( ) function or the object's AddProperty
method.

For more info rmation, see DEFINE CLASS Co mmand, ADDPROPERTY( ) Function , and AddProperty Method .

Array Properties
You can create and add array properties to a class. Array properties are arrays that you can add to the class as properties. An array
property is read-only at design time and appears in italic in the Properties window; however, you can manipulate and redimension an
array property at run time. For examp le, you can create an array property for a form to store object variables associated with each
instance of a form. For an example of using an array property, see How to: Manage Multiple Instances of a Form . For information
about limits on the number of elements in arrays, see Visual FoxPro System Capacities.

To create an array prope rty

1. Follow the steps fo r adding a property to a class.

2. In the Name box of the New Property dialog box, type the name, size, and dimen sion of the array.

For example, specifying myArrayProperty[10,2] creates an array property n amed myArrayProperty with ten rows and two columns.

See Also
Concepts

How to: Add Methods to Classes


Working with Classes in Visual FoxPro

7acd caad-69f9-4ce1 -8a4b -7e2150329c20 How to: Add Properties to Classes

c
d
e
f
g Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Create Access and Assign Methods
See Also Send Feedback

You can create Access and Assign methods for new custom pro perties, native Visual FoxPro properties, or existing custom
properties. You can create them when adding or editing custom properties. For more information about Access and Assign methods,
see Access and Assign Metho ds. For information about addin g custom properties to forms, form sets, and classes, see How to: Add
Pro perties and Methods to a Form an d How to: Add Properties to Classes.

You can create Access and Assign methods interactively in the Form Designer or Class Designer. To create Access and Assign
methods for p roperties of forms and form sets, use the Form Designer. To create Access and Assign methods for properties of classes
for contro ls and other objects, use th e Class Designer. You can also create Access and Assign methods programmatically.

To create an Access or Assign method when adding a new property

1. In the New Property dialog box, select the Access Method box, the Assign Method box, or both.

2. When you are finish ed creating the property, click Add .

When you create an Access or Assign method, the new metho d is added to the end of the properties list in the Properties window and
appears with the suffix, _access or _assign.

For more info rmation, see New Property Dialog Box.

To create an Access or Assign method for a native Visual FoxPro property

1. If you are in the Form Designer, on the Form menu, choose New Method.

-OR-

If you are in the Class Desig ner, on the Class menu, choose New Method.

2. In the Name box of the New Method dialog box, type the name of the native Visual FoxPro property followed with the suffix
_ACCESS or _ASSIGN.

3. When you are finish ed creating the method, click Add.

For more info rmation, see New Method Dialog Box

To create an Access or Assign method for existing custom properties

1. If you are in the Form Designer, on the Form menu, choose Edit Property/Method.

-OR-

If you are in the Class Desig ner, on the Class menu, choose Edit Property/Method.

2. In the Edit Property/Method dialog box, select the property you want.

3. Select the Access Method box, the Assign Method box, or both.

4. Click Apply, and then Close.

For more info rmation, see Edit Property/Method Dialog Box.

When you create an Access or Assign method for an existing custom prop erty, the new method is added to the end of the pro perties
list in the Properties window and appears with the suffix, _access or _assign .

To create Acce ss and Assign methods programmatically

 Use the DEFINE CLASS co mmand and inclu de the PROCEDURE clause.

Note:
In Assign methods, you must include a PARAMETERS or LPARAMETERS statement so th at when you attempt to assign a valu e
to a property at run time, Visual FoxPro can accept the value and pass it to the Assign method.

For more info rmation, see DEFINE CLASS Co mmand.

For example, the following code creates a class named MyClass with Access and Assign methods called MyProperty_ACCESS and
My Pro perty_ASSIGN for the custom property MyProperty. MyProperty_ACCESS responds to queries on the value of MyProperty,
while MyProperty_ASSIGN responds to changes in the value of MyProperty.

Note:
The Assign method includes an LPARAMETERS statement so it can accept the value that is passed to it.
Copy Code
DEFINE CLASS MyClass AS Custom
MyProperty = 100

PROCEDURE MyProperty_ ACCESS


WAIT WINDOW 'This is the Access method';
+ ' ' + PROGRA M( )
RETURN THIS.MyProp erty
ENDPROC

PROCEDURE MyProperty_ ASSIGN


LPARAMETERS tAssig n
WAIT WINDOW 'This is the Assign method';
+ ' ' + PROGRA M( )
ENDPROC
ENDDEFINE

The following code example creates a Form class named frmMyForm with an Assign method called Left_ASSIGN for the form's
native Left prop erty. Left_ASSIGN performs simp le validation on the property value and runs when an attempt is made to assign a
value to the pro perty. If y ou attempt to change the Left prop erty to a negative value, the Assign method displays a message an d
leaves the value unchan ged. If you attempt to change the Left prop erty to a nonnegative value, the method sets the property to the
specified value.

Note:
The Assign method includes an LPARAMETERS statement so it can accept the value that is passed to it.
Copy Code
DEFINE CLASS frmMyForm A S Form
PROCEDURE Left_ASSIGN
LPARAMETERS tAssig n
DO CASE
CASE tAssign < 0 && Value passed is neg ative.
WAIT WINDOW 'Value must be greater t han 0'
OTHERWISE && V alue passed is not negat ive.
THIS.Left = tAssign
ENDCASE
ENDPROC
ENDDEFINE

Creating THIS_ACCESS Methods


You can create THIS_ACCESS methods from the Form Designer, Class Designer, or programmatically.

To create a THIS_ACCESS method

1. On the Form menu in the Form Designer or on the Class Men u in the Class Desig ner, choose New Method.

2. In the New Method dialog box, type THIS_ACCESS.

3. Click Add.

When created, the THIS_ACCESS method appears in the Properties window. To add code to the method, double-click the
method in the Prop erties window.

To create THIS_ACCESS methods programmatically

 Use the DEFINE CLASS co mmand and inclu de the THIS_ACCESS keyword.

For more info rmation, see DEFINE CLASS Co mmand.

The following code example creates a Form class named My Form with a THIS_ACCESS method, which contains an
LPARAMETER statement with an object member name and some code to execute. The first line of code creates a form named
oTempForm using the CREATEOBJECT( ) function. The second lin e of code attempts to assign a value to the form's Caption
property. This action executes the THIS_ACCESS method and passes the name of the Caption prop erty to the method. The
THIS_ACCESS method displays the name of the object member, or 'Cap tion' in this ex ample, using the questio n mark (?)
command, and then returns an object referen ce for the form.

The th ird line attempts to display the value of the form's Caption prop erty usin g the ? co mmand. This action executes
THIS_ACCESS ag ain, passes the name of the Caption prop erty to the method, displays 'Caption ', and return s an object reference
for the form. The value of the Caption prop erty, 'abc', is then finally displayed .

Copy Code
oTempForm = CREATEOBJECT ('MyForm')
oTempForm.Caption = 'abc '
? oTempForm.Caption

DEFINE CLASS MyForm AS F orm


PROCEDURE THIS_ACCESS
LPARAMETER cMember Name

IF cMemberName = ' caption'


? cMemberName
ENDIF
RETURN THIS
ENDPROC
ENDDEFINE

For more info rmation, see DEFINE CLASS Co mmand.


See Also
Concepts

How to: Add Properties to Classes


Working with Classes in Visual FoxPro

9c764956 -8eec -4728-aee5 -a2e1 2126921e How to: Create Access and Assign Methods

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Add Methods to Classes
See Also Send Feedback

After you create a class, you can create and add custom methods to the class. When you add methods to classes, you are creatin g a
procedure or function in the class definition. For more information about methods, see Classes in Visual FoxPro .

Note:
When you create custom methods for classes, the methods are scoped to the class, not to individual components in the class. If you
create a method that h as the same name as an event in the class d efinition, the code in the meth od executes when the event occurs.

You can add methods to classes using the Visual FoxPro IDE or prog rammatically. When you ad d a method, you can specify the
level of visibility for the method. For more information about visibility levels for methods, see Pro tecting and Hidin g Class
Members.

To add a method to a class

1. Open the class in the Class Designer.

For more info rmation about opening classes, see How to: Modify Classes .

When the class opens in the Class Designer, the Class menu app ears.

2. On the Class menu, choose New Method .

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

4. In the Visibility box, choose the visibility level for the method.

5. To specify a description for the method when the method ap pears in th e Pro perties window, include a description in the
Description box.

6. Click Add.

7. Continue ad ding methods, or if you are finished, click Close.

After you add the method, it appears in the Properties window at the end of the properties list. Fo r information about adding code to
methods, see How to: Add Code to Methods and Events.

To add methods to classes programmatically

 Use the DEFINE CLASS co mmand and inclu de the FUNCTION clause when you create a class.

For more info rmation, see DEFINE CLASS Co mmand.


See Also
Concepts

How to: Add Properties to Classes


Working with Classes in Visual FoxPro

42da71f3-2511 -4ce4 -9f6c-0a5faf55fb9b How to: Add Methods to Classes

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Add Code to Methods and Events
See Also Send Feedback

You can add cod e for methods that you add to classes or class events using the Class Designer or p rogrammatically.

To add code for a method or event

1. Open the class in the Class Desig ner.

For more info rmation about opening classes, see How to: Modify Classes .

2. On the Visual FoxPro toolbar, click Properties Window.

3. In the properties list of the Properties window, double-click the method or event y ou want to add code for to open a co de
window.

Note:
Custom methods appear at the end of the properties list.
4. In the code window, add code for the method or event.

5. When you are finish ed adding code, close the code window.

For more info rmation, see Pro perties Window (Visual FoxPro) an d Code Window.

To add code to methods and events programmatically

 Use the DEFINE CLASS co mmand and inclu de the FUNCTION or PROCEDURE clause.

For more info rmation, see DEFINE CLASS Co mmand.

See Also
Concepts

Classes in Visual FoxPro


Understanding the Event Model
Working with Classes in Visual FoxPro

7cf6b1a7 -728c-44cd-bafd -a8180576eedc How to: Add Code to Methods and Events

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c
d
e
f
g Visual C++
c
d
e
f
g J#
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Modify Class and Class Member Attributes
See Also Send Feedback

After you create classes, you can add or edit their descriptions using the Class Designer or Class Bro wser. By using the Class
Browser, you do not need to open each class. You can also modify attributes for custom properties and methods.

To modify a class description

1. Open the class in the Class Desig ner.

For more info rmation about opening classes, see How to: Modify Classes .

When the class opens in the Class Desig ner, the Class menu app ears.

2. On the Class menu, choose Class Info .

3. In the Class Info dialog box, choo se the Class tab.

4. Make changes to the description in the Description box.

5. When you are finish ed making changes, click OK.

To modify a class description without opening each class

1. Open the class library in the Class Browser.

For more info rmation about opening class libraries, see How to: Open Class Lib raries.

2. In the class list of the Class Browser, select the class you want to change the description for.

3. In bo ttom -left corner of the Class Browser, type the text for the class description.

If no memb er is selected in the memb er list of the Class Browser, the bottom-right corner of the Class Browser displays the class and
timestamp information fo r the selected class.

Modifying Custom Property and Method Attributes


You can edit the attributes, such as the visibility level and description, fo r custom prop erties and methods using the Visual FoxPro
IDE, the Project Manager when the class is part of a project, or in the Class Browser.

Caution:
Use caution when editing attributes, such as the visibility level, fo r custom prop erties and methods. Chang es yo u make might affect
code that references tho se properties and metho ds.

To modify attributes for a custom property or method

1. Open the class in the Class Desig ner.

For more info rmation about opening classes, see How to: Modify Classes .

When the class opens in the Class Desig ner, the Class menu app ears.

2. On the Class menu, choose Edit Property/Method.

3. When you are finish ed making changes, click Apply.

You can also right-click the property or method in the prop erties list of the Properties window and choose Edit Property/Method.
To modify attributes for a custom property and method without opening each class

1. Open the class library in the Class Browser.

For more info rmation about opening class libraries,, see How to: Open Class Lib raries .

2. In the member list of the Class Browser, select a method or property.

3. In the bottom -right corner of the Class Browser, type the text for the prop erty or method description.

Note:
For member properties and methods, the bottom -right corner displays a description you can edit. However, for object members and
instances of classes, the botto m-right corner displays read -only informatio n for the class and base class of the object member,
including the visibility level, member names, and property values.

See Also
Concepts

How to: Add Code to Methods and Events


Working with Classes in Visual FoxPro

4ac9 bd95-3cdb-4bb1-8219-1703be84c963 How to: Modify Class and Class Member Attributes

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Remove Properties and Methods from Classes
See Also Send Feedback

You can remove custom properties and methods from classes.

Caution:
Use caution when removing properties and metho ds from classes. Chang es yo u make affect code that references those properties and
methods.

To remove a custom property or method

1. Open the class in the Class Designer.

For more info rmation about opening classes, see How to: Modify Classes .

When the class opens in the Class Designer, the Class menu app ears.

2. On the Class menu, choose Edit Property/Method.

3. In the Pro perty/Method Information list, select the property or metho d you wan t to remove, and click Remove.

See Also
Concepts

Classes in Visual FoxPro


Working with Classes in Visual FoxPro

d4c1791e-2e23-4863-aca5 -00e807d75dd1 How to: Remove Properties and Methods from Classes
g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Specify Design-Time Appearance for Classes
See Also Send Feedback

In Visual FoxPro, objects and controls created fro m visual classes display a visual element at design time and run time. However,
objects and controls based on non-visual classes, such as the Custom class and Timer co ntrol, display a visual element at design
time but not at run time.

At design time, Visual FoxPro displays objects created from non -visual classes with a default graph ic. However, you can ch ange the
default graphic so that you can disting uish one non -visual class from another at design time. However, objects created from non-
visual classes do not display these graphics at run time.

You can also specify toolbar and container icons that appear for classes in the Visual FoxPro IDE. Yo u can specify icons that appear
in the Forms Control toolbar and Toolbox after you add classes to them. You can also specify container icons that appear in the
Pro ject Manager and Class Browser.

To specify a visual element for a non-visual class

1. Open the class in the Class Desig ner.

For more info rmation about opening classes, see How to: Modify Classes .

2. On the Visual FoxPro toolbar, click Properties Window.

3. In the Properties window, sp ecify an image file, such as a bitmap (.bmp) file, for the Picture prop erty.

4. Save the class.

You can specify a toolbar icon for a class. After you add the class to the Form Controls toolbar or the Toolbox, the icon for the class
appears on the toolbar or in the Toolbox.

To specify a toolbar icon for a class

1. Open the class in the Class Desig ner.

For more info rmation about opening classes, see How to: Modify Classes .

When the class opens in the Class Desig ner, the Class menu app ears.

2. On the Class menu, choose Class Info .

3. In the Toolbar icon box in the Class Info dialog box, type the name an d path of the icon (.ico) or bitmap (.bmp) file.

-OR-

Click the ellipsis (...) button to browse for an .ico or .bmp file.

4. Click OK an d sav e the class.

Note:
The bitmap (.bmp file) for a toolbar ico n is 15 by 16 pixels. If the pictu re is larger or smaller, it is sized to 15 by 16 pixels and might
not look the way you want it to.

You can specify a container icon for a class. The icon for the class appears in containers such as the Project Manager and Class
Browser. In the Class Browser, the icon for the class app ears next to the class in the class list and next to the type box when the class
is selected. By default, the container icon and toolbar icon for the class are the same as those for the parent class.

To specify a container icon for a class

1. Open the class in the Class Designer.

For more info rmation about opening classes, see How to: Modify Classes .

When the class opens in the Class Desig ner, the Class menu app ears.

2. On the Class menu, choose Class Info .

3. In the Container icon box of the Class Info dialog box, type the name and path of the ico n (.ico) or bitmap (.b mp) file.

-OR-

Click the ellipsis (...) button to browse for an .ico or .bmp file.

4. Click OK an d sav e the class.

You can also specify the container icon in the Class Browser by right-clicking the class in the class list, choosin g Container icon ,
selecting an .ico or .bmp file, and clicking OK .

Tip:
If you click Cancel instead of OK , Visual FoxPro displays a message prompting whether you want to reset the icon to the default,
which is the icon Visual FoxPro uses for its base classes. If you want the ico n to match its base class, choose Yes.

The new icon replaces the previous icon in the class list. The icon that appears next to the class list refreshes when yo u select the
class in the class list.

Note:
If the previous icon for the container and toolbar are the same, then the new icon replaces both the container and toolbar icon.
Otherwise, if the p revious toolbar icon differed from the container icon, only the container icon changes.

See Also
Concepts

Classes in Visual FoxPro


How to: Create Classes and Subclasses
Working with Classes in Visual FoxPro

4f8c439 b-02c7 -412a-8294 -67dac2346335 How to: Specify Design-Time Appearance for Classes

c
d
e
f
g Visual Basic
c C#
d
e
f
g
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Add Classes to Visual FoxPro Tools
See Also Send Feedback

Typically, you can add ob jects to forms by dragging classes from the Toolbox or add ing them from the Form Controls toolbar.
However, Visu al FoxPro does not add custom classes to the Toolbo x or the Fo rm Controls toolbar automatically.

To add a class to the Toolbox

1. On the Tools menu, choose Toolbox.


2. Right -click the Toolbox an d choose Add Class Library .

3. In the Category box in the Add Class Library dialog box, type or choose the category you want to add the class to.

4. In the Class Library box, type the name of the class library.

-OR-

Click the ellipsis (...) button to select a class library.

Visual FoxPro adds the class to the end of category you chose in the Too lbox.

For more info rmation, see Toolbox (Visual FoxPro) an d How to: Customize the Too lbox .

To add a class to the Form Controls toolbar

1. Open a form.

2. On the View menu, choose Form Controls Toolbar .

3. On the Form Controls toolbar, click View Classes , and then choose Add .

4. In the Open dialog box, select a class library, and then click Open .

The class appears on the Form Controls toolbar.

When you add class libraries to the Form Controls toolbar, they appear registered in the Controls tab of th e Option s dialog box. If
you want the class to appear in the Forms Control toolb ar in future sessions of Visual FoxPro, click Set As Default in the Controls
tab of the Options dialog box.

Tip:
You can register the class library so that when y ou choose View Classes on the Form Controls toolbar, the class library appears in the
list of class libraries you can choose.

To register a class library

1. On the Tools menu, choose Options.

2. In the Options dialog box, choo se the Controls tab.

3. On the Controls tab, choose Visual class libraries, and then click Add.

4. In the Open dialog box, select a class library, and then click Open .

5. To make the class library available on the Form Controls toolbar fo r future sessions of Visu al FoxPro, click Set As Default.

6. Click OK.

See Also
Concepts

Working with Classes in Visual FoxPro

5f30ae6a-ba67 -441c-9f93 -494f91e33f47 How to: Add Classes to Visual FoxPro Tools

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c
d
e
f
g J#
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Access and Assign Metho ds
See Also Send Feedback

Visual FoxPro su pports Access and Assign methods, which are user-defined procedures or function s that have the same name as a
class property and have the suffix _ACCESS or _ASSIGN ap pended to the procedure or fu nction name. You can use Access and
Assign methods to execute code when querying th e value of a property o r attempting to change the property's value. Visual FoxPro
executes Access and Assign methods only when querying or changing property values at run time, not design time. You can create
Access and Assign methods separately and independently of each other.

Access and Assign methods provide the following benefits:

 You can create a p ublic interface for a class or object that sep arates the interface from the implementation.

 You can easily implement property validatio n.

 You can easily protect properties in subclassed ActiveX con trols.

Visual FoxPro executes code in an Access method when querying the valu e of a property, typ ically by using the property in an object
reference, storing the property value to a variable, or displaying the property value with the question mark (?) command.

Visual FoxPro executes code in an Assign method when you attempt to change the pro perty value, typ ically by using the STORE
command or = operator to assign a new value to the pro perty.

Note:
You can create Access and Assign methods for most native Visual FoxPro p roperties. You can create Assign metho ds for properties
that are read -only; however, the meth od never ex ecu tes. Visual FoxPro does not support the Assign method for the Value prop erty
for contro ls nor does it support Access and Assign metho ds for native properties, events, or methods of Activ eX controls. However,
Visual FoxPro su pports Access and Assign methods for properties, events, and methods of the Visual FoxPro OLE Co ntainer in
which an ActiveX control is contained.
Note:
Access and Assign methods for member arrays do no t fire when accessing the array using a native array function such as ASCAN().
Note:
The Assign method will fire for certain native pro perties when their value is queried and not changed. These inclu de dimensio nal
properties such as Top , Left, Height, Width as well as a few others like Visible. This is due to how Visual FoxPro handles these
properties internally.

Visual FoxPro treats Access an d Assign methods as Protected at run time, so they cannot be accessed outside of th e class definition.
However, when you are in th e Class Designer, Visual FoxPro treats these Access and Assign methods in a special way. When you
drop an object onto a container, such as a command button onto a form, Visual FoxPro usually marks Protected methods of such
objects as read-only and not modifiable in the designer. However, you can edit Access and Assign methods of such objects in the
Class Designer.

THIS_ACCESS Methods
You can create THIS_ACCESS methods to execute code when changing the value for an object member or querying the object
member. The THIS_ACCESS method must always return an object reference; otherwise, Visual FoxPro generates an error.
Typically, the method returns the object reference, THIS. The THIS_ACCESS method must also in clude a parameter to accept the
name of the object member that is changed or queried.

Note:
THIS_ACCESS is not in tended as a global replacement for Access and Assign method s. It only provides information ab out the
object member that is accessed or queried. Unlike an Access or Assign method, THIS_ACCESS does not provide contro l over
values returned to specific object members.

See Also
Concepts
How to: Create Access and Assign Methods
Working with Classes in Visual FoxPro

0f0717bb -ec5c-4d09-a80d -0afb194 66c4b Access and Assign Metho ds

c
d
e
f
g Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Pro tecting and Hidin g Class Members
See Also Send Feedback

When you create and add p roperties and methods to a class in the Class Designer, you can specify one of the following levels of
visibility for the property or method: Public, Protected, or Hidden. When you create a class using the DEFINE CLASS co mmand,
you can designate properties and methods as Hidden or Protected u sing the PROTECTED an d HIDDEN keywords.

By default, properties and methods in a class definition are Public, which means code in oth er classes or procedures can set those
properties or call those methods. However, certain classes migh t need to restrict users from changing its properties or calling its
methods from outside the class. You can designate the properties and methods that you add to a class as Protected, which restricts
access to members of the class and su bclasses. You can also designate properties and method s as Hidden, which restricts access to
only members of the class.

For example, suppose you create a class that stores employee informatio n, and you do not want p ermit users to change the hire date
for the employee. You can desig nate the hire date as Protected, and instead, provide a method that returns the hire date so that users
can view the hire date if they need to. The following code example creates the Employee class u sing the DEFINE CLASS co mmand
and designates the HireDate property as Protected using the PROTECTED keyword and contains the method GetHireDate that
returns the hire date:

Copy Code
DEFINE CLASS Employee AS CUSTOM
PROTECTED HireDate
First_Name = ""
Last_Name = ""
Address = ""
HireDate = { - - }

PROCEDURE GetHireDate
RETURN This.HireDa te
ENDPROC
ENDDEFINE

For more info rmation, see DEFINE CLASS Co mmand.

The Visual FoxPro sample, Display a Stop Watch Sample, also illustrates the use of protected properties and methods in a class.

See Also
Concepts

Classes in Visual FoxPro


How to: Add Properties to Classes
How to: Add Methods to Classes
Working with Classes in Visual FoxPro

de1e2c7e-15b3 -4579-a28f-6ce3 c799db88 Pro tecting and Hidin g Class Members

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c
d
e
f
g Visual C++
c
d
e
f
g J#
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Overriding Default Property Settings
See Also Send Feedback

For a user-defined class, you can change the default v alues for prop erties that are not marked as Protected when you ad d objects
based on that class to a form. Th is action overrides the default values of those properties as defined by the class. If you later change
the default values fo r properties in the class, for example, using the Class Designer, the values of those properties for the object on
the form are not affected.

However, if you do no t change the default property value when you add the object to the form and you change the default property
value in the class, the property value of the object chan ges to match the new default value.

For example, suppose you add a command button based on a user-defined class to a form and changes the BackColo r prop erty from
white to red. If you change the d efault value of the BackColo r prop erty in the user-defined class to green, the back color of the
command butto n on th e form remains red. However, if you do not change the back color of the command button and yo u change the
default value color of the BackColo r prop erty in the class to green, the back color of the command b utton on the form inherits the
chan ge and is set to green.

See Also
Concepts

Overriding and Calling Paren t Class Code


Working with Classes in Visual FoxPro

99cb7aab -d67f-4715-a3b7 -bda2a08b1e39 Overriding Default Property Settings

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Overriding and Calling Paren t Class Code
See Also Send Feedback

When you create a class, the class inherits all the properties, methods, and events of the parent class automatically . For example, if
code exists for an event in the parent class, that code executes wh en the event occurs for an object based on a subclass created from
the parent class.

The following sections describe how yo u can override or execute method or event cod e from the p arent class:

 Overriding Parent Class Code

 Calling Parent Class Code

Overriding Parent Class Code


Usually, you want to add fu nctionality to a new class or the object created from that class in addition to th e original functionality.
However, y ou can override the method or event code inherited from th e parent. For example, supp ose y ou create a subclass or add an
object based on the subclass to a container, such as a form. You can write new code for the Click ev ent of the class to override the
even t code in the parent class. In both cases, the n ew code, not the original co de, is executed at run time.

You can also prevent the default behavior of the base class from occurring in a sub class's meth od or event. To prevent base class
behavior, include the NODEFAULT keyword in the method or event code that you add.

For example, the following program u ses the NODEFAULT keyword in a tex t box's KeyPress ev ent to prevent the typed characters
from displaying in the text box:
Copy Code
frmKeyExample = CREATEOB JECT("test")
frmKeyExample.Show
READ EVENTS
DEFINE CLASS myForm AS F ORM
ADD OBJECT text1 AS T EXTBOX
PROCEDURE text1.KeyPr ess
PARAMETERS nKeyCod e, nShiftAltCtrl
NODEFAULT
IF BETWEEN(nKeyCod e, 65, 122) && Between ' A' and 'z'
This.Value = AL LTRIM(This.Value) + "*"
ACTIVATE SCREEN && Send output to main Visual FoxPro wind ow.
?? CHR(nKeyCode )
ENDIF
ENDPROC
PROCEDURE Destroy
CLEAR EVENTS
ENDPROC
ENDDEFINE

Calling Parent Class Code


You can optimize class design by adding and executing code at different levels in the class or container hierarchy.

To execute method or event code in the parent class in additio n to code for the same meth od or event in the subclass, precede the
sub class's meth od or event code with the DODEFAULT( ) function or the scope resolution operator (::).

Tip:
When you use the DODEFAULT( ) function, you do not need to know the name of the paren t class. However, to determine all the
classes in an ob ject's class hierarchy, use the ACLASS( ) function. For more information, see ACLASS( ) Function.

For example, suppose you have a class named cmdGoBottom based on the CommandButton class that has the following code in its
Click ev ent:

Copy Code
GO BOTTOM
THISFORM.Refresh

This cod e moves the tab le record pointer to the bottom of the table. When you create a command bu tton, for example,
cmdGoBottom1, based on the cmdGoBotto m class an d add it to a form, you might decide to execute the code in parent class's Click
even t and display a message indicatin g that the table record pointer is positioned at the b ottom of the table. Suppose you add only the
following line of code to cmdGoBottom1's Click ev ent to display the message, "At the Bottom of th e Table":

Copy Code
WAIT WINDOW "At the Bott om of the Table" TIMEOUT 1

When you run the form, the message disp lays; however, the record pointer does not move because the code in cmdGoBottom1 's
Click ev ent overrides that of the parent class. To make sure that the code in the parent class's Click ev ent also executes, include the
following lines of code instead in cmdGoBottom1's Click ev ent:

Copy Code
DODEFAULT( )
WAIT WINDOW "At the Bott om of the Table" TIMEOUT 1

The following lines of code in the cmdGoBottom1's Click ev ent show how to accomplish the same task usin g the scope resolution
operator (::) and the name of the parent class:

Copy Code
cmdGoBottom::Click()
WAIT WINDOW "At the Bott om of the Table" TIMEOUT 1

As another example, the Buttons.vcx visual class library in the Visual FoxPro ...\Samples\Classes d irectory contains two command
button classes: cmdOK and cmdCancel. Suppose a command button created from the cmdOK class exists on a form. The code in the
Click ev ent of the command button releases the form when yo u click the button. However, the cmdCancel command button class is a
sub class of the cmdOK class. Suppose you wanted to discard chang es made to a table when you click a command button created
from the cmdCancel class. You can add functionality to the Click ev ent of the cmdCancel class that calls the method code in the
cmdOK class by using the following sample code:

Copy Code
IF USED( ) AND CURSORGET PROP("Buffering") != 1
TABLEREVERT(.T.)
ENDIF
DODEFAULT( )

The code added to the cmdCancel class reverts ch anges to the tab le using th e TABLEREVERT( ) function before it uses the
DODEFAULT( ) function to call the code in cmdOK class to release the form.

Note:
You do not need to add the TABLEUPDATE( ) function to the cmdOK class because changes are written to a buffered table by
default when the tab le closes.

For more info rmation, see DODEFAULT( ) Functio n an d :: Scope Resolution Operator .

See Also
Concepts

Overriding Default Property Settings


Working with Classes in Visual FoxPro

6d73089a-af9c-469f-aca4-842ac7d08932 Overriding and Calling Paren t Class Code

c
d
e
f
g Visual Basic
c C#
d
e
f
g
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Managing Classes and Class Libraries
Send Feedback

Visual FoxPro uses stored definitions of classes in class library files. You can perform tasks such as create class libraries, add classes
and subclasses, copy and rename classes, redefine parent class relationships, an d remove classes from class libraries.

Visual FoxPro provides several means for managing classes and class libraries. However, u sing the Class Browser to manage classes
updates projects and forms as well as class libraries. Changes that you make in the Class Browser propagate through every class
library (.vcx) and form (.scx) file that is op en in the Class Browser.

In This Section
Operating the Class Browser

Describes working with the Class Browser.

How to: Create Class Libraries (Visual FoxPro)

Describes the methods for creating class libraries.

How to: Open Class Lib raries

Describes how to open class libraries.

How to: Add Classes and Subclasses to Class Libraries

Describes how to ad d new classes and subclasses to existing class libraries.


How to: Rename Classes in Class Libraries

Describes the methods to ren ame a class within a class library.

How to: Copy Classes Between Class Libraries

Describes the process to copy a class from one class library to another class library.

How to: Redefine Parent Class Relation ships

Describes the method to change the parent class o f a class.

How to: Remove Classes from Class Libraries

Describes how to remove a class from a class library.

How to: View Type Library In formation

Describes how to view type library information.

Related Sections
Object-Oriented Programming

Discusses how you can create self-contained application componen ts that respond to user actions and to the system and which
can be easily maintains and reused.

fad9d94 6-6168 -4460-bbfd -2ba3ba2bd348 Managing Classes and Class Libraries

c
d
e
f
g Visual Basic
c C#
d
e
f
g
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Operating the Class Browser
Send Feedback

The Class Browser makes it possible for you to manage classes and class libraries.

In This Section
How to: Run the Class Browser

Explains how to open and run the Class Browser.

How to: Customize the Class Browser

Explains how to customize the Class Browser.

How to: View Class Hierarchies

Explains how to view class hierarchies.

How to: Filter the Class Browser Class List

Explains how to filter th e classes displayed in the Class Browser.


How to: View Class Definition Code

Explains how to view class defin ition code.

Related Sections
Managing Classes and Class Libraries

Describes how to manage the classes that you create.

Working with Classes in Visual FoxPro

Introduces classes in Visu al FoxPro and how to use them to create ob jects.

122bfed b-7376 -43f3-b16e-8696d9300ea6 Operating the Class Browser

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Run the Class Browser
See Also Send Feedback

You can run multiple instances o f the Class Browser at the same time.

To run the Class Browser

 On the Tools menu, choose Class Browser.

For more info rmation, see Class Browser Window an d Class Browser Buttons .

To run the Class Browser programmatically

 In the Command window, use the DO co mmand with the _BROWSER system variable, which specifies the name of the class
browser application as shown in the following line of code:

Copy Code
DO (_BROWSER)

For more info rmation, see _BROWSER System Variable.

When run ning the Class Browser using the DO co mmand, you can use the following additio nal parameters and syntax :

Copy Code
DO (_BROWSER) [WITH [ tcFileName][, tcDefaultClass [.member]][ , tlListBox][, tcClassType ][, tnWindowState]]

The following table describes the optional parameters you can use when runnin g the Class Browser using the DO co mmand.

Parameter Description
The name of the .vcx, .scx, .olb, .tlb, .pjx,
or .exe file to open in the Class Browser.
tcFileName
For more info rmation, see File Extensions
and File Types.
Specifies the class to select by default in
the .vcx file.
If no default class is specified, the class
tcDefaultClass library is selected. If a class member is
[.member] specified, the class member appears selected
in the member list of the Class Browser.

Specifies whether to display the classes and


members in list boxes rather than using tree-
view controls. To display list boxes, specify
tlListBox
True (.T.).

Default: False (.F.)


Specifies the initial type filter for the classes
displayed in the Class Browser. To change
the filter in the Class Browser, choose
tcClassType another value in the type list of the Class
Browser.

Default: No filter.
Specifies the state of the Class Browser
window when opened.
tnWindowState
0 - Normal (Default) 1 - Minimized 2 –
Maximized
Specifies whether to open the Component
Gallery instead of the Class Browser. To
open the Component Gallery, specify True
tlGallery
(.T.).

Default: False (.F.)

For example, you can run the Class Browser with a specific visual class library (.vcx) file or an object reference. You can also
include the class name to be initially selected. The following line of code opens the Class Browser, the Buttons.vcx class library, and
selects the VCR class:

Copy Code
DO (_BROWSER) WITH HOME( 2) + 'Classes\Buttons.vc x', 'VCR'

As another example, you can run the Class Browser and specify to select the cmdOK object from the Print_Report class in the
Samples.vcx class library, display the forms and members in Samples.vcx in list boxes, filter the classes displayed using the Form
class, and open the Class Browser window as max imized:

Copy Code
DO (_BROWSER) WITH "Samp les.vcx", "Print_Report. cmdOK", .T., "form", 2

See Also
Concepts

How to: Customize the Class Browser


How to: View Class Hierarchies
How to: Filter the Class Browser Class List
How to: View Class Definition Code
Operating the Class Browser
Managing Classes and Class Libraries

4d6d1f82 -039c-4386-b739 -67650d795e21 How to: Run the Class Browser

c
d
e
f
g Visual Basic
c
d
e
f
g C#
g
c
d
e
f Visual C++
c
d
e
f
g J#
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Customize the Class Browser
See Also Send Feedback

You can customize the Class Browser by changing the values for its properties and using its methods and events. You can perform
additio nal operations, such as specifying default class libraries to open in the Class Browser, using Class Browser methods. For more
information, see Class Browser Properties, Class Browser Methods, and Class Browser Object Members

When you open the Class Browser, the public variable, _oBrowser, is automatically created. You can use th is variable to reference or
manipulate the Class Browser as you can any form object.

To set properties for the Class Browser

 In the Command window, use the followin g syntax to set Class Bro wser pro perties that you want to change:

Copy Code
_oBrowser. Property = newValue

For example, after opening the Class Browser, you can use the following lines of code to set the Caption prop erty of the Class
Browser to "My Class Browser" and the Left prop erty to 10:

Copy Code
_OBROWSER.Caption = "My Class Browser"
_OBROWSER.Left = 10

To specify the default class library to open in the Class Browser

1. Open the class library in the Class Browser.

2. In the class list of the Class Browser, select the class library.

3. In the Command window, type the following co de:

Copy Code
_oBrowser.SetDefaultFile

This resets any previously specified default libraries.

You can specify class libraries to open by default in addition to the default library.

To specify additional libraries to ope n with the Class Browser

1. In the Class Browser, click th e View Additional File button.

2. In the class list of the Class Browser, select the class library.

3. In the Command window, type the following co de:

Copy Code
_oBrowser.SetDefaultFile (.T.)

To remove c lass librar ies from the Class Browser list

1. In the class list of the Class Browser, select the class library.

2. In the Command window, type the following co de:

Copy Code
_oBrowser.ResetDefaultFi le
To remove all libraries from the Class Browser list

 In the Command window, type the following co de:

Copy Code
_oBrowser.ResetDefaultFi le(.T.)

See Also
Concepts

Class Browser Window


How to: View Class Hierarchies
How to: Filter the Class Browser Class List
How to: View Class Definition Code
Operating the Class Browser
Managing Classes and Class Libraries

afc75739 -4829-4b5d -ae1b -99e28c909b1a How to: Customize the Class Browser

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: View Class Hierarchies
See Also Send Feedback

You can view the hierarchy in a class library, user-defined members in a class, and inheritance of members between related classes
using the Class Browser.

To vie w class members and hierarc hies

1. In the Class Browser, open th e class library you want to view.

For information about openin g the Class Browser, see How to: Run the Class Browser.

2. In the class list of the Class Browser, select the class you want.

When a class is selected, an icon for the class appears next to th e type list, which appears above the class list. Any user-defined class
members that exist appear in the member list. Subclasses appear indented beneath parent classes when Hierarchical mode is selected
on the Class Browser shortcut menu.

When a class is selected, you can view its parent class if available.

To vie w the parent class

 Right -click the class, and on the shortcut menu, choose Select ParentClass .

The parent class appears selected.

If a chevron (<<) appears next to a class, its parent class is lo cated in a class library (.vcx) that is not displayed in the class list. If you
choose Select ParentClass on the class shortcut menu, the class library containing the parent class is added to the class list, and the
parent class is selected.

You can view multiple class libraries or form files by opening another file in the current Class Browser wind ow or by open ing
another Class Browser windo w. You can also open the same file in several Class Browser windows.

See Also
Concepts

Class Browser Window


How to: Filter the Class Browser Class List
How to: View Class Definition Code
Operating the Class Browser
Managing Classes and Class Libraries

60a1f38 d-aaee-439b-b57d-acec3c796030 How to: View Class Hierarchies

c
d
e
f
g Visual Basic
c C#
d
e
f
g
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Filter the Class Browser Class List
See Also Send Feedback

You can display a sp ecific set of classes by specifying a class type, class name, or a filter in the Class Browser.

To filter the class list

1. In the Class Browser, open th e class library you want.

For information about openin g the Class Browser, see How to: Run the Class Browser.

2. In the type box, select a class from the list, type the name of a class, or type a single filter or filters separated by commas,
which act as logical OR operators.

Note:
A class needs to match on ly one filter for inclusion in the class list.

The classes that match the class, type, or filter you sp ecified appear in the class list. The filters you specify are added to the
type list.

The ty pe list keeps a histo ry of the types an d filters you selected only for the current instance of the Class Browser. The list is not
saved after you close the Class Browser.

Note:
Hierarchical mode is selected by default on the Class Browser shortcut menu. When Hierarchical mode is selected, Visual FoxPro
evaluates parent classes. If a parent class matches the filter, its child classes are evaluated. If the parent class does not match the
filter, its child classes are not evaluated and do no t appear in the list, even if the child matches the filter.

You can expand your search for classes to include a specific character string in the name or description.

To search by class name and de scription text

1. In the Class Browser, open th e class library you want.

2. In the Class Browser, click th e Find button.

3. In the Look for box of the Find Class dialog box, type a string of tex t that y ou want to search for.

4. Click Find.

Classes that contain the string in its name or description appear in the class list.

Note:
When Hierarchical mode is selected, only the matching parent classes and their associated matching subclasses appear in the list.
The following table of filter operators and expressions describes wildcard characters yo u can combine with the characters in a class
name to create a filter in the Class Browser.

Filter contains Description


+ cTargetName Name must start with cTargetName.
Name contains cTargetName.

% cTargetName % For example, to view all classes


containing the string "mover," type
%MOVER% .
Name does NOT contain cTarget .
- cTarget
Takes precedence over other search
filters.
Name contains something similar to
~ cTarget
cTarget .
cTarget * Name contains anything following
cTarget .
An asterisk (*) replaces
an unlimited number of For example, to view all classes
characters. beginning with "VCR," type VCR* .
Name is cTarget.
" cTarget "
If cTarget is not a base class, report
results of class name search.
If cTarget is a base class, report all
cTarget members of the base class regardless
of the name.
Name contains cTarget plus the
specified unk nown characters in the
specified relative positions.

The question mark (?) replaces a


single character. You can u se
[?...]cTarget [?...] question marks in any position and in
any quantity.

For example, to view all classes


starting with MsgBox and some
number, such as MsgBox1, type
MsgBox?.

The following table describes examples that illustrate combinations o f filter expressions sep arated by spaces, which represent the OR
operator.

Use an
If you want this expression like
this
The target is a string that must start with
-%form% +test*
"test" but is NOT a "form" class.
The target is any string that does NOT
c* %test% -%
contain "debug" and starts with "c" OR debug%
contains "test".

The target is any string that does NOT start ~test -debug*
with "debug" and is similar to "test" OR is "myForm"
the string "myform"

See Also
Concepts

Class Browser Window


How to: View Class Hierarchies
How to: View Class Definition Code
Operating the Class Browser
Managing Classes and Class Libraries

68548e59 -811e-4637-af02 -9149ea120a6f How to: Filter the Class Browser Class List

c
d
e
f
g Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: View Class Definition Code
See Also Send Feedback

You can view the code for class defin itions, specific parameters, or parent class code for user-defined methods using the Class
Browser. You can also save class definition code to another class library.

To vie w class definition code

1. In the Class Browser, open th e class library you want.

For information about openin g the Class Browser, see How to: Run the Class Browser.

2. In the class list, select the class you want.

3. In the Class Browser, click th e View Class Code button.

Visual FoxPro displays definition code for th e class in a read -only program (.prg) file. The class definition displayed includes all
property settings and method and event code.

Note:
The code is d isplayed for viewing purposes only. In many cases, yo u can save it to a program and run it directly; h owever, code with
nested containers generate errors. To view type library information, use th e Object Browser Window.

You can use a limited selection of editing command s, such as Find, Copy, and Select All, on the Edit menu.

If parent class code is available for a user-defined method, you can view the parent class code.

To vie w parent class code for a user -defined method

1. In the Class Browser, double-click a class or class member.

The class or class member opens in the Class Desig ner or Form Designer. If no code window is open, on the View menu,
choose Code.

2. On the Visual FoxPro toolbar, click the Edit ParentClass Method button.

See Also
Concepts

Class Browser Window


How to: View Class Hierarchies
How to: Filter the Class Browser Class List
Operating the Class Browser
Managing Classes and Class Libraries

0cb9b66a-0dc2-4feb-b443-75f1fd4a998f How to: View Class Definition Code

c
d
e
f
g Visual Basic
c C#
d
e
f
g
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Create Class Libraries (Visual FoxPro)
See Also Send Feedback

You can create class libraries when you create classes using the Visu al FoxPro IDE or empty class libraries programmatically.

Visual FoxPro stores classes you create using the Class Designer in visual class library (.vcx) files. These classes include visual and
non-visual classes. You can also choose to store class definitions in program (.prg) files wh en using the DEFINE CLASS co mmand
to create classes.

To create a class library when creating a class

1. Create a class using the Visual FoxPro IDE.

2. In the Sto re In box of the New Class dialog box, type the name of the class lib rary.

For more info rmation about creating classes, see How to: Create Classes and Subclasses .

To create class libraries progr ammatically

 Use the CREATE CLASSLIB co mmand to create an empty class library.

-OR-

 Include the OF clause in the CREATE CLASS co mmand when you create a class.

For example, the following line of code uses the CREATE CLASSLIB co mmand to create an empty class library named
My ClassLibrary:

Copy Code
CREATE CLASSLIB MyClassL ibrary

The following line of co de includes th e OF clause in the CREATE CLASS co mmand to specify the name o f the class library that
will store the class MyClass, which is based on the Form class.

Copy Code
CREATE CLASS MyClass OF MyClassLibrary AS Form

For more info rmation, see CREATE CLASSLIB Command .

See Also
Concepts

How to: Add Classes and Subclasses to Class Libraries


Managing Classes and Class Libraries
68d428a3 -9d70-44f5-b775 -48a948a4c3fc How to: Create Class Libraries (Visual FoxPro)

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Open Class Lib raries
See Also Send Feedback

You can open class libraries to view or add classes.

You can open classes using the Class Browser, the Project Manager when the class library is part of a project, or programmatically.

To open a class library

1. On the Tools menu, choose Class Browser.

2. In the Class Browser, click Open .

3. In the Open dialog box, select the class library you want, and click OK .

The class library you selected appears in the class list in th e Class Browser along with any classes it contains.

To open a class library in a project

1. Open the project containing the class library.

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

3. Select the class library you want to open and click Modify .

The class library you selected opens in the Class Browser.

To open and close class libraries programmatically

1. To open class libraries programmatically, use th e SET CLASSLIB co mmand.

-OR-

2. To clo se class libraries programmatically, use the RELEASE CLASSLIB co mmand.

For more info rmation, see SET CLASSLIB Command an d RELEASE CLASSLIB Command .

See Also
Concepts

How to: Modify Classes


How to: Add Classes and Subclasses to Class Libraries
Managing Classes and Class Libraries

e5f12a43 -e821-4082-a9f5 -d0f0fd0a5c1c How to: Open Class Lib raries

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c
d
e
f
g Visual C++
c
d
e
f
g J#
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Add Classes and Subclasses to Class Libraries
See Also Send Feedback

When you create a class or subclass interactively or programmatically, the class is stored in the class library that you specify . If the
class library ex ists, the class is added to the class library.

To add a class to a class library

1. Open the class library in the Class Browser.

For more info rmation about opening class libraries, see How to: Open Class Lib raries.

2. In the class list of the Class Browser, select the class library you want to add a class for.

3. In the Class Browser, click th e New Class button.

The New Class dialog box opens so you can specify information for the new class.

4. Follow the steps fo r creating a class o r subclass. For more information, see How to: Create Classes and Subclasses.

When you finish creating and saving the class, the class appears in the class library displayed in the Class Browser.

To add a subc lass to a class library

1. Open the class library in the Class Browser.

For more info rmation about opening class libraries, see How to: Open Class Lib raries.

2. In the class list of the Class Browser, select the class you want to create a subclass from.

3. In the Class Browser, click th e New Class button.

The New Class dialog box opens so you can specify information for the new class. The class you selected appears by default in
the Based On box.

4. Follow the steps fo r creating a class o r subclass. For more information, see How to: Create Classes and Subclasses.

When you finish creating and saving the subclass, the subclass appears in the class library displayed in the Class Browser.

To add classes to class librarie s programmatically

 Use the ADD CLASS co mmand.

For example, the following line of code adds the class MyClass to MyClassLibrary:

Copy Code
ADD CLASS MyClass TO MyC lassLibrary2

For more info rmation, see ADD CLASS Co mmand.

See Also
Concepts

How to: Add Properties to Classes


How to: Add Methods to Classes
Managing Classes and Class Libraries

617bfc9 6-b2cc-42f1-a8ea-79ca4abd66d7 How to: Add Classes and Subclasses to Class Libraries
g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Rename Classes in Class Libraries
See Also Send Feedback

You can rename classes in class libraries. You can rename classes in class libraries using th e Class Browser, the Project Manager
when the class library is p art of a project, or programmatically.

Caution:
When you rename a class, forms that contain that class and subclasses in other class libraries continue to refer to the origin al name
and will no longer function correctly.
Tip:
If you rename a class using the Class Browser when all associated subclasses and forms are open in the Class Browser, the new name
is automatically referenced in all affected subclasses and forms.

To rename a class in a class library

1. Open the class library in the Class Browser.

For more info rmation about opening class libraries, see How to: Open Class Lib raries.

2. In the class list of the Class Browser, select the class you want rename, and click the Rename button.

3. In the Rename dialog box, type the new name, and click Rename.

The class list in the Class Browser displays the renamed class.

For more info rmation, see Class Browser Window.

To rename a class in a pr oject

1. Open the project containing the class library with the class you wan t to rename.

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

3. Expand the class library containing the class you want to rename.

4. Right -click the class library and choose Rename.

5. In the To: box of the Rename File dialog box, type a new name for the class.

6. Click OK.

To rename classes programmatically

 Use the RENAME CLASS co mmand.

For example, the following line of code changes the name of the class MyClass in the class library MyClassLibrary to YourClass:

Copy Code
RENAME CLASS MyClass OF MyClassLibrary TO YourCl ass

For more info rmation, see RENAME CLASS Command .

See Also
Concepts

Managing Classes and Class Libraries

15038c38 -1669-474f-84e5 -9a384f5 8c4fc How to: Rename Classes in Class Libraries

c
d
e
f
g Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Copy Classes Between Class Libraries
See Also Send Feedback

You can copy classes between class libraries. You can copy classes using Class Browser, the Project Manager when the class
libraries are parts of projects though not necessarily the same project, or programmatically.

To copy a class between class libraries

1. Open the class library containing the class you want to copy in the Class Browser.

For more info rmation about opening class libraries, see How to: Open Class Lib raries.

2. Open the destination class library in another instance of the Class Browser.

3. In the Class Browser co ntaining the source class library, select the class you want to copy.

4. Press and hold the CTRL key while you drag the class icon abo ve the class list to the destination class library.

A plus (+) sign appears above the cursor when you drag the class icon into the destination class library.

Tip:
To move a class from one class library to another, do not press and hold the CTRL key while dragging the class icon.

To copy a class between class libraries in projects

1. Open the project or projects containing the class libraries.

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

3. Expand the class library containing the class you want to copy and the destination class library.

4. Drag the class to the destinatio n library.

The mouse pointer changes into a class library icon wh en you move it over a valid destination library.

To copy classes between class libraries programmatically

 Use the ADD CLASS co mmand with the OF clause.

For example, the following line of code copies the class MyClass from MyClassLibrary1 to MyClassLib rary2.

Copy Code
ADD CLASS MyClass OF MyC lassLibrary1 TO MyClassL ibrary2

For more info rmation, see ADD CLASS Co mmand.

See Also
Concepts

Managing Classes and Class Libraries

d24d5817-319a-41dc-b77e-6a358dbd07bd How to: Copy Classes Between Class Libraries

c
d
e
f
g Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Redefine Parent Class Relation ships
See Also Send Feedback

You can redefine the relationship between a class and its parent class.

Caution:
When you redefine a class, forms that contain that class and subclasses in other class lib raries that do not currently ap pear in the
Class Browser might not function correctly.

To change the parent class of a class

1. Open the class library in the Class Browser.

For more info rmation about opening class libraries, see How to: Open Class Lib raries.

2. In the class list of the Class Browser, select the class you want to redefine.

3. In the Class Browser, click th e Redefine button.

4. In the As list of the Redefine dialog box, select the name of the new parent class.

-OR-

Click the ellipsis (...) button to select a class.

5. Click Redefine.

See Also
Concepts

Managing Classes and Class Libraries

73fb7d78 -d249-4dbb-819e-493cb8ef9f74 How to: Redefine Parent Class Relation ships

c
d
e
f
g Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Remove Classes from Class Libraries
See Also Send Feedback

You can remove classes from class libraries.

Caution:
When you remov e a class from a class library, you delete the class.
You can remove classes from class libraries using the Class Browser, the Project Manager when the class library is part of a pro ject,
or programmatically.

To remove a class from a class library

1. Open the class library in the Class Browser.

For more info rmation about opening class libraries, see How to: Open Class Lib raries.

2. In the class list of the Class Browser, right-click the class you want to remove, and choose Remove.

To remove a class from a project

1. Open the project containing the class library.

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

3. Expand the class library containing the class you want to remove.

4. Select the class you want to remov e and choose Remove.

To remove c lasses from class libraries programmatically

 Use the REMOVE CLASS co mmand.

For example, the following line of code removes a class named MyClass from the class library named MyClassLibrary:

Copy Code
REMOVE CLASS MyClass OF MyClassLibrary.vcx

For more info rmation, see REMOVE CLASS Command .

See Also
Concepts

Managing Classes and Class Libraries

b1892660-bb01-4235-ad64-ded4ec1e7185 How to: Remove Classes from Class Libraries

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: View Type Library In formation
See Also Send Feedback

Type libraries are COM Component definition files that include information about ty pes and objects exposed by an OLE app lication.
A type library can be a standalone binary (.tlb) file, compiled in an application (.exe) file, embedded in an ActiveX control (.ocx), or
included in a dynamic-link library (.dll or DLL) file. DLL files with on e or more ty pe libraries are often compiled as object (.olb)
libraries.

To vie w type library information

1. In the Object Browser Window, choose Open Type Libra ry .

2. In the Open dialog box select the tab that will give you access to the library you want.
Recent History tab lists the most recently opened libraries.

COM libraries tab lists the available libraries and provide a Browse button so yo u can find the library you want.

Current Selection lists any open libraries.

In the Files of type drop -down list in the Open dialog box, choo se Application, *.dll, *.ocx, * .olb, or *.tlb .

3. Select a library and click OK.

The ty pe library informatio n for the selected file is display ed in the Classes & Members list.

See Also
Concepts

Operating the Class Browser


Using the Object Browser

be797e96-7fe7-4ada-b422-3159dafb4e7b How to: View Type Library In formation

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Working with Objects in Visual Fox Pro
Send Feedback

Visual FoxPro provides many way s to work with objects. By using objects you can create objects from classes for more reusable
code, use objects to store data, and create code that is easier to read and reference.

In This Section
Objects in Visual FoxPro

Introduces objects in Visual Fo xPro and how to create an d use them.

Creating Objects from Classes

Describes how to create an object based on a saved visual class.

How to: Add Classes to Forms

Describes how to ad d a class to a form usin g Project Manager.

Adding Objects to a Container Class

Details how to add objects to a container through use of the ADD OBJECT clause in the DEFINE CLASS co mmand or the
AddObject method .

How to: Add Objects to a Control or Contain er Class

Describes how to ad d objects to a class using the Class Designer.

Creating Table Navigation Buttons

Pro vides an explanation of how to design and build table navigation b uttons th rough code.
Defining a Grid Control

Outlines how to define grid control programmatically.

How to: Set Properties

Describes how to set the properties of an object at run time or design time.

Container Hierarchy Object Referencing

Describes how objects are referenced in the container hierarchy and explains the importance of identifying objects in relation
to the container hierarchy.

Object Reference Creation

Explains how to make a reference to an object, an d describes the benefits of creating references over making copies of objects.

Object and Member Arrays

Describes how to create arrays containing objects and to define class members as arrays.

Data Sto rage with Objects

Describes when and how to store data in objects.

How to: Call Methods

Describes how to call the methods of an object from anywhere in an app lication once it has been created.

Object and Data Integration

Contains information on why integrating objects and data is important.

How to: Create Instances of Classes with the Class Browser

Describes how to create a new instance o f a class u sing the Class Browser.

How to: Add Controls to Forms with the Class Browser

Describes how to ad d objects to a form with the Class Browser.

Reference
Objects, Collections, and Classes

Pro vides a list of objects, collections, and classes in Visual FoxPro.

Related Sections
Managing Classes and Class Libraries

Discusses how to create and modify classes and class libraries with in Visual FoxPro.

Working with Classes in Visual FoxPro

Discusses methods to use, modify, and create classes within Visual FoxPro.

f24d7ed c-c175-4d31-bc31 -9bc6fa376aad Working with Objects in Visual Fox Pro


g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Objects in Visual FoxPro
See Also Send Feedback

When an object is created from a class, it exists as an instance of that class. The class describes the data, characteristics, and
functionality for the objects created from that class. Objects in Visual FoxPro can be forms, form sets, controls, and so on. They also
have prop erties and methods, wh ich you can use to manipulate the objects, and th ey can detect and resp ond to events, which are
occu r when certain actions are performed. An o bject's properties, methods, and events are defined by the class it is created from.

You can create o bjects by using the Form Designer or the CREATEOBJECT( ) function. For more information, see Creating
Objects from Classes , Form Designer, or CREATEOBJECT( ) Function .

Features of Objects
Objects possess the following features:

 Object Properties

 Object Methods

 Object Events

Obje ct Properties

An object that you create in Visual FoxPro has properties, or attributes, that pertain specifically to that object. You can set and
modify valu es for these properties, which determine the characteristics for the objects. You can set properties for Visual FoxPro
objects at design time or run time, depending on the p roperty.

For example, a computer has properties that can include the following: color, size, shape, location in a room, o r state. Likewise, in
Visual FoxPro, a check box created from the CheckBox co ntrol class includes the following properties:

 Caption

 Enabled

 Top

 Visible

For more info rmation, see How to: Set Properties for Objects an d How to: Add Properties to Classes.

Obje ct Methods

An object has methods, which contain procedu res for performing a specific task. However, object methods differ from standard
Visual FoxPro procedures in th at object methods are inextricably bound to an object and are called differently compared to standard
Visual FoxPro procedures.

For example, a check box created from the CheckBox co ntrol class includes the following methods:

 Drag

 Mo ve

 ReadExpression
 Refresh

You can include methods in object events or use them independently outside events. When you u se methods outside events, you must
call them explicitly and programmatically. You can also create and extend methods. For more information, see How to: Call Methods
and How to: Add Properties to Classes.

Obje ct Eve nts

An object can detect and respo nd to specific actions called events. An event is a specific and predetermined activity that occurs wh en
the user or sy stem performs an action. In mo st cases, events occur because of user interaction. In Visual Fo xPro, user actio ns that
trig ger events include clicking or moving the mouse and pressing keys. System events include initializing an object and encountering
a line of code that generates an error.

For example, a check box created from the CheckBox co ntrol class includes the following events:

 Mo useEnter

 Mo useUp

 Mo useDown

 RightClick

Events can hav e methods associated with them. For example, when you include method code in a Click ev ent, the code is executed
when the Click ev ent occurs. Though extensive, the set of events available is fixed. You cannot create new events.

For more info rmation, see Events in Visual FoxPro .

See Also
Concepts

Object-Oriented Programming
How to: Create Classes and Subclasses
Manipulating Objects
Working with Classes in Visual FoxPro

1dba2e48-d799-4cf7 -a493 -0573bc6fa534 Objects in Visual FoxPro

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Creating Objects from Classes
See Also Send Feedback

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 Sho wing a Form Object Wh ose Class Was Designed in the Form Designer
Code Comments
Set the class lib rary to the .vcx file that
the form definition was saved in. The
SET CLASSLIB TO
ADDITIVE keyword prevents this
Forms ADDITIVE command fro m closing any oth er class
libraries that happen to be open.

frmTest = This cod e assumes that the name o f the


CREATEOBJECT form class saved in the class library is
("TestForm") TestFo rm.
frmTest.Show Display the form.

See Also
Concepts

Pro tecting and Hidin g Class Members


Adding Objects to a Container Class
SET CLASSLIB Command
CREATEOBJECT( ) Function
Object-Oriented Programming

7722b5b2-9514-4a47 -8fe9 -2e619c589427 Creating Objects from Classes

c
d
e
f
g Visual Basic
c C#
d
e
f
g
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Add Classes to Forms
See Also Send Feedback

You can drag a class from the Pro ject Manager to the Form Designer or to the Class Designer. You can also register yo ur classes so
that they can be displayed directly on th e Form Controls toolbar in the Class Designer or Form Desig ner and add ed to containers the
same way the standard controls are added.

To add a class to a form

1. Fro m the Project Manager window, select a class to add to a form.

2. Click and drag the class from the Project Manager window to an op en Form Designer.

See Also
Concepts

Working with Classes in Visual FoxPro


Object-Oriented Programming
Container Hierarchy Object Referencing
How to: Set Properties
How to: Call Methods

cc54 6bb3-f3fc-41e9 -8351-193d17283b94 How to: Add Classes to Forms

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Adding Objects to a Container Class
See Also Send Feedback

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:

Copy Code
DEFINE CLASS myform AS F ORM
ADD OBJECT cmdOK AS CO MMANDBUTTON
ADD OBJECT PROTECTED c mdCancel AS COMMANDBUTTO N
ENDDEFINE

Use the AddObject method to add objects to a con tainer 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:

Copy Code
frmMessage = CREATEOBJEC T("FORM")
frmMessage.AddObject("tx t1", "TEXTBOX")
frmMessage.AddObject("tx t2", "TEXTBOX")

You can also use the AddObject method in the method cod e of a class. For example, the following class d efinition uses AddObject in
the code associated with the In it event to add a control to a grid column.

Copy Code
DEFINE CLASS mygrid AS G RID
ColumnCount = 3
PROCEDURE Init
THIS.Column2.AddObject ("cboClient", "COMBOBOX" )
THIS.Column2.CurrentCo ntrol = "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 p roperty 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 p roperty of the class or a variable in the
method that calls this function. The parent property of the object is und efined.

See Also
Concepts

Creating Objects from Classes


Pro tecting and Hidin g Class Members
Object-Oriented Programming
Parent Object Reference

78522d7b-4340-4db9-89db-f03013effaa5 Adding Objects to a Container Class

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Add Objects to a Control or Contain er Class
See Also Send Feedback

If you base a new class on a control or contain er class, you can add contro ls to it using the Class Designer the same way you add
controls in the Form Designer.

To add controls to a class

1. Open the class in the Class Designer.

2. Fro m the Form Controls toolbar, drag a control to the control or container class in the Class Designer.

Tip:
To deactivate the snap -to -grid functionality, press and hold the CTRL key while draggin g objects from the toolbar.

See Also
Concepts

Working with Classes in Visual FoxPro


How to: Add Properties to Classes
Object-Oriented Programming
Container Hierarchy Object Referencing

c84a3ab0 -a052 -441e-b520-bff9c79f40fd How to: Add Objects to a Control or Contain er Class

c
d
e
f
g Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Creating Table Navigation Buttons
See Also Send Feedback

A commo n 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 o r prior record in the table, as well as to the top or bottom record in the table.

Designing the Navigation Buttons


Each of the buttons will have some characteristics and functio nality in common, so it is a good idea to create a n avigation button
class. Then the individual buttons can easily derive this common ap pearance and function ality. This parent class is the Navbutton
class defined later in this section.

Once the paren t class is defined, the following subclasses define the fu nctionality and appearance specific to each of the fou r
navigation buttons: navTop, navPrior, navNext, navBottom.

Finally, a container class, vcr, is created and each o f 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 o f the Generic Navigation Commandbutton Class


Code Comments

DEFINE CLASS Navbutton


AS Define the parent class of the
navigation buttons. Give the
COMMANDBUTTON class some dimensions.
Height = 25 Include a custo m property,
TableAlias , to hold the name of
Width = 25 the alias to navigate through.

TableAlias = ""
PROCEDURE Click
If TableAlias has been set, this
parent class procedure selects
IF NOT EMPTY
the alias before the actual
(This.TableAlias)
navigation code in the
sub classes is executed.
SELECT (Th is.TableAlias) Otherwise, assume that the user
wants to navigate through the
ENDIF table in the currently selected
work area.
ENDPROC
Using
PROCEDURE RefreshForm
_SCREEN.ActiveForm.Refresh
instead of THISFORM.Refresh
_SCREEN.ActiveForm.Refresh allows you to add the class to a
form or a toolbar and have it
ENDPROC 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. Th e remain ing three navigation buttons are defined in the following table. The four class definitions are similar,
so only the first one has extensive comments.

Definition o f the Top Navigation Button Class


Code Comments
DEFINE CLASS
navTop AS
Define the Top navigation button class
Navbutton
and set the Caption property .
Caption = "|<"
PROCEDURE Create metho d code to be executed when
Click the Click event for the control occurs.
Call the Click event code in the paren t
class, Navbutton , so that th e approp riate
alias can be selected if the TableAlias
property has been set. Include th e code to
set the record pointer to the first record in
DODEFAULT( )
the table: GO TOP. Call the
RefreshFo rm method in the parent class.
GO TOP
It is no t necessary to use the scope
resolution operator (::) in this case
THIS.RefreshForm because there is no method in the
sub class with the same name as the
method in the p arent class. On th e other
hand, both the parent and the subclass
have method code for the Click event.
ENDPROC End the Click p rocedure.
ENDDEFINE End the class definition.

The other navigation buttons have similar class definitions.

Definition o f the Other Navigation Button Classes


Code Comments
DEFINE CLASS
navNext AS Navbutton Define the Next navigation b utton
class and set the Caption property.
Caption = ">"
PROCEDURE Click

DODEFAULT( )

SKIP 1

IF EOF( )
Include the code to set the record
GO BOTTOM pointer to the next record in the
table. End the class definition.
ENDIF

THIS.RefreshForm

ENDPROC

ENDDEFINE
DEFINE CLASS
navPrior AS Navbutton Define the Prior nav igation button
class and set the Cap tion property.
Caption = "<"
PROCEDURE Click

DODEFAULT( )

SKIP –1

IF BOF( )
Include the code to set the record
GO TOP pointer to the previous record in th e
table. End the class definition.
ENDIF

THIS.RefreshForm

ENDPROC

ENDDEFINE
DEFINE CLASS
navBottom AS
Define the Bottom navigation
button class and set the Caption
Navbutton
property.
Caption = ">|"

PROCEDURE Click
Include the code to set the record
DODEFAULT( ) pointer to the botto m record in the
table. End the class definition.
GO BOTTOM

THIS.RefreshForm
ENDPROC

ENDDEFINE

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 pro perty of th e b uttons.

Definition o f a Table Navigation Control Class


Code Comments
DEFINE CLASS vcr AS
CONTAINER

Height = 25 Begin the class definition. Th e


Height p roperty is set to the same
Width = 10 0 height as the co mmand buttons it
will contain.
Left = 3

Top = 3
ADD OBJECT cmdTop
AS navTop ;

WITH Left = 0

ADD OBJECT cmdPrio r


AS navPrior ;

WITH Left = 25
Add the navigation buttons.
ADD OBJECT cmdNex t
AS navNext ;

WITH Left = 50

ADD OBJECT cmdBot AS


navBottom ;

WITH Left = 75

PROCEDURE SetTab le
(cTableAlias)

IF TYPE("cTableAlias") =
This method is used to set the
'C'
TableAlias property of the
buttons. TableAlias is defined in
THIS.cmdTop.TableAlias the parent class Navbutton . You
=; could also use the SetAll method
to set this property:IF TYPE
cTableAlias ("cTableAlias") = 'C' This.SetAll
("TableAlias", "cTableAlias")
THIS.cmdPrior.TableAlias ENDIF However, this would
=; cause an error if an object were
ever added to the class that did
cTableAlias not have a TableAlias property.

THIS.cmdNext.TableAlias
=;

cTableAlias
THIS.cmdBot.TableAlias
=;

cTableAlias

ENDIF

ENDPROC
ENDDEFINE End class definition.

Once you have d efined 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:

Definition o f a Table Navigation Control Subclass


Code Comments
DEFINE CLASS vcr2 AS vcr

ADD OBJECT cmdQuit AS

COMMANDBUTTON WITH ;

Caption = "Quit",;
Define a class based on vcr
Height = 25, ; and add a command button to
it.
Width = 50

Width = THIS.Width +
THIS.cmdQuit.Width

cmdQuit.Left = THIS.Width - ;

THIS.cmdQuit.Width
PROCEDURE
cmdQuit.CLICK
When the user clicks
cmdQuit, this code releases
RELEASE THISFORM the form.
ENDPROC
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 b ased on the parent. For example, you co uld let the
user know that the bottom of the table has been reach ed by changing the IF EOF( ) statement in navNext.Click to the following:

Copy Code
IF EOF( )
GO BOTTOM
SET MESSAGE TO "Botto m 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:

Copy Code
IF BOF()
GO TOP
SET MESSAGE TO "Top o f the table"
ELSE
SET MESSAGE TO
ENDIF

If these changes are made to the navNext an d 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 ad ded in the defin ition of a container. For example, the following code added to
Navclass.prg defines a form with added navigation buttons:

Copy Code
DEFINE CLASS NavForm AS Form
ADD OBJECT oVCR AS vc r
ENDDEFINE

Running the Form Containing VCR


Once the fo rm subclass is defined, you can display it by loading the class definition, creating an ob ject based on th e sub class and
calling the Show method for the form:

Copy Code
SET PROCEDURE TO navclas s ADDITIVE
frmTest = CREATEOBJECT(" navform")
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 mov es in the table in the currently selected work area. You can call the SetTable method to specify what table to move
through.

Copy Code
frmTest.oVCR.SetTable("c ustomer")
Note:
When the user closes the form, frmTest is set to a null value (.NULL.). To release the object variable fro m memory, use the
RELEASE command. Object variables created in program files are released from memory when the program is completed.

See Also
Concepts

Defining a Grid Control


Caption Property (Visual FoxPro)
Height Prop erty
SetAll Method
Object-Oriented Programming

1965dff9 -670b-4aa1 -bbb0-b8fca7841eae Creating Table Navigation Buttons

c
d
e
f
g Visual Basic
c
d
e
f
g C#
c
d
e
f
g Visual C++
g
c
d
e
f J#
c
d
e
f
g JScript
Visual FoxPro 9.0 SP2
Defining a Grid Control
See Also Send Feedback

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. Howev er, the underlying architecture of the grid
opens it up to endless extensibility.

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

Grid control with a ch eck box in one colu mn

Definition o f a Grid Class with a Check Box in a Grid Column


Code Comments
DEFINE CLASS grdProducts
AS Grid
Start the class definition and
Left = 24 set properties that determin e
the grid appearance. When
Top = 1 0 you set the ColumnCount
property to 2, you add two
Width = 29 5 columns to the grid. Each
column contains a header
Height = 210 with the name Header1. In
additio n, each column has
Visible = .T. an independent group of
properties that determines
RowHeight = 28 its appearance and b ehavior.

ColumnCount = 2
When you set the
Column1.ControlSource Contro lSource of a column,
="prod_name" the column displays th at
field's values for all the
Column2.ControlSource records in the
="discontinu" table.Discontinu is a logical
field.

Column2 will contain the


Column2.Sparse = .F. 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.
Pro cedu re Init

THIS.Column1.Width = 175

THIS.Column2.Width = 68

THIS.Column1.Header1.Caption
=;

"Product Name" Set column widths and


head er captio ns. The
THIS.Column2.Header1.Caption AddObject method allows
=; you to add an object to a
container — in this case, a
"Discontinued" check box named chk1 . Set
the CurrentControl of the
THIS.Column2.AddObject column to the check b ox so
("chk 1", ; that the check box will be
displayed. Make sure that
"checkbox") the check box is visible. Set
the caption to an empty
THIS.Column2.CurrentControl string so that the default
=; caption "chk1" won't be
displayed.
"chk1"

THIS.Column2.chk1.Visible
= .T.

THIS.Column2.chk1.Caption =
""

ENDPROC
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 p rogram file.

Definition o f a Form Class that Co ntains the Grid Class


Code Comments
DEFINE CLASS
GridForm AS
FORM

Width = 33 0

Height = 250 Create a form class and add an object,


based on the grid class, to it.
Caption = "Grid
Example"

ADD OBJECT
grid1 AS
grdProducts

PROCEDURE The program that creates an object based


Destroy on this class will use READ EVENTS.
CLEAR Including CLEAR EVENTS in the Destroy
EVENTS even t of the form allows the program to
finish running when the user closes the
ENDPROC form. End of the class definition.

ENDDEFINE

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

Copy Code
CLOSE DATABASE
OPEN DATABASE (HOME(2) + "data\testdata.dbc")
USE products
frmTest= CREATEOBJECT("G ridForm")
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 p rogram with the class definitions and include this code in a separate prog ram.

See Also
Concepts

How to: Create Classes and Subclasses


Creating Table Navigation Buttons
Object Reference Creation
Browse Window
Sparse Property
AddObject Meth od
SYS(18) - Current Control
Object-Oriented Programming

2509e004 -ed1a-4e07-801a-30fe35abba10 Defining a Grid Control

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Set Properties
See Also Send Feedback

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

Specifying the Default Value for a Property


You can 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 pro perty settings.

Caution:
Pro perties in subclasses inherit the d efault property values that you specify unless you choose Reset to Default on the shortcut menu
for the property, which resets the default values to those of the parent class.

To set a property

 Use the following syntax to set an object property pro grammatically:


Container .Object.Property = Value

For example, the following statements set various properties of a text box named txtDate on a form named frmPhoneLog :

Copy Code
frmPhoneLog.txtDate.Valu e = DATE( ) && Display t he current date
frmPhoneLog.txtDate.Enab led = .T. && The control is enabled
frmPhoneLog.txtDate.Fore Color = RGB(0,0,0) && black text
frmPhoneLog.txtDate.Back Color = RGB(192,192,192) && gray background

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:

Copy Code
frsContacts.frmPhoneLog. txtDate.Value = DATE( )

To set multiple prope rties

 Use the WITH ... ENDWITH Command structure to simplify setting multiple properties.

For example, to set multiple properties of a colu mn in a grid in a form in a form set, you could use the following syntax:

Copy Code
WITH THISFORMSET.frmForm 1.grdGrid1.grcColumn1
.Width = 5
.Resizable = .F.
.ForeColor = RGB(0,0,0)
.BackColor = RGB(255,25 5,255)
.SelectOnEntry = .T.
ENDWITH
Note:
You can also modify an object's properties in the Pro perties Window (Visual FoxPro).

See Also
Concepts

Object-Oriented Programming
Working with Classes in Visual FoxPro
Pro tecting and Hidin g Class Members
Overriding Default Property Settings

cabe2fb3 -3662-407e-818a-f203bc9 af61d How to: Set Properties

c
d
e
f
g Visual Basic
c C#
d
e
f
g
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Container Hierarchy Object Referencing
See Also Send Feedback

The container and the class hierarchy are two separate entities. Objects are referenced in the container hierarchy, whereas Visual
FoxPro searches for event co de up through the class 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 contain er hierarchy to givin g Visual FoxPro an address to your object. When
you describe the locatio n of a house to someone outside yo ur immediate frame of reference, you need to indicate the country, th e
state o r 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 con tainer-nesting situation.

Nested co ntainers

To disab le the control in the grid column, y ou need to prov ide the following address:

Copy Code
Formset.Form.PageFrame.P age.;
Grid.Column.Control.Ena bled = .F.

The ActiveForm property of the applicatio n 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 o f the active form, n o matter what form set it
belongs to:

Copy Code
_VFP.ActiveForm.BackColo r = 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 th e Watch windo w displays the name of the active control on a form as you interactively choose the variou s
controls:

Copy Code
_VFP.ActiveForm.ActiveCo ntrol.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:

Where to include the


Command
command

THISFORMSET.frm1 .cmd1.Caption In the event or method


= "OK" code of any controls on
any form in the form
set.
In the event or method
code of any control on
THISFORM.cmd1.Caption = "OK" the same form th at
cmd1 is on.
In the event or method
code of the control
THIS.Caption = "OK"
whose caption you
want to ch ange.
In the event or method
code of a con trol on a
THIS.Parent.BackColor = RGB form. The command
(192,0,0) chan ges the
back ground color of the
form to dark red.

See Also
Concepts

Object-Oriented Programming
Working with Classes in Visual FoxPro

1306572d-66d4-492b-9948-a82ec9aafc5c Container Hierarchy Object Referencing

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Object Reference Creation
See Also Send Feedback

Instead of making a copy of an object, you can create a reference to th e object. A referen ce 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. Fo r example, the following
program defines a class, creates an object based on the class, and returns a reference to th e o bject:

Copy Code
*--NEWINV.PRG
*--Returns a reference to a new invoice form.
frmInv = CREATEOBJECT("I nvoiceForm")
RETURN frmInv

DEFINE CLASS InvoiceForm AS FORM


ADD OBJECT txtCompany AS TEXTBOX
* code to set propert ies, add other objects, and so on
ENDDEFINE

The following program establishes a reference to th e object created in Newin v.prg . The reference variable can be manip ulated in
exactly the same way as the object variable can:

Copy Code
frmInvoice = NewInv() && store the object refere nce to a variable
frmInvoice.SHOW
You can also create a reference to an object on a form, as in the following example:

Copy Code
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),
even ts, metho ds, 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 ex ample, the following command
releases frmInvo ice, the original object:

Copy Code
RELEASE frmInvoice

However, b ecause a reference to an object b elonging to frmInvo ice still exists, th e object is not released from memory until
txtCustName is released with the following comman d:

Copy Code
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 ex ists:

Copy Code
IF TYPE("oConnection") = "O" AND NOT ISNULL(oCon nection)
* Object exists
ELSE
* Object does not exi st
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".

See Also
Concepts

Defining a Grid Control


Object and Member Arrays
DISPLAY OBJECTS Command
AMEMBERS( ) Fun ction
Object-Oriented Programming

4e7850a9-ea47 -499b-9d5a-16feeaec4395 Object Reference Creation

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Object and Member Arrays
See Also Send Feedback
You can create arrays containing objects and as class members.

Object Arrays
You can create arrays that contain o bjects. When creating arrays that contain objects, keep in mind the following con siderations:

 You cannot assign an individual object to all the elements in an array using a single command. You must assign the object to
each element of the array individu ally.

 You cannot assign a value to the pro perty of an entire array.

For example, the following comman d results in an erro r:

Copy Code
MyArray.Enabled = .F.
 When you redimension an object array so that it is larger than the original array, the new elements are initialized to False (.F.)
as is th e case with all arrays in Visual FoxPro. When you redimension an object array so that it is smaller than the original
array, the objects with a subscript greater than the largest new subscript are released.

For example, the following code creates an array named My Array that holds five command buttons usin g a loop structure:

Copy Code
DIMENSION MyArray[5]
FOR x = 1 TO 5
MyArray[x] = CREATEOB JECT("CommandButton")
ENDFOR

Class Member Arrays


You can include arrays as class members and store objects in them.

The following example creates a form that contains an object created from the custo m Container class, ButtonList. The ButtonList
class contains a member that is an array named, aChoices, in which each element contain a different control object.

When you run the example from a program (.prg) file, a form appears with two command b uttons and a check box. Wh en the user
clicks a command button or selects the check box on the form, Visual Fo xPro passes the index number of the array elemen t that
contains the control to the Click ev ent through the tnIndex parameter. A DO CASE co mmand structure displays a window with the
number of the element.

different code depending on which button was clicked.

Copy Code
loForm = CREATEOBJECT("F orm")
loForm.AddObject("cntBut tons", "ButtonList")
loForm.cntButtons.SetAll ("Visible", .T.)
loForm.cntButtons.Visibl e = .T.
loForm.Show(1)

DEFINE CLASS ButtonList AS Container


Height = 100
Width = 130
BorderWidth = 0

DIMENSION aChoices[3]

ADD OBJECT aChoices[1 ] AS CommandButton WITH ;


Top = 10, ;
Height = 20, ;
Left = 10, ;
Caption = "Element One"
ADD OBJECT aChoices[2 ] AS CommandButton WITH ;
Top = 40, ;
Left = 10, ;
Height = 20, ;
Caption = "Element Two"
ADD OBJECT aChoices[3 ] AS CheckBox WITH ;
Top = 70, ;
Left = 10, ;
Caption = "Element Three"

PROCEDURE aChoices.Cl ick


LPARAMETER tnIndex
DO CASE
CASE tnIndex = 1
WAIT WINDOW "1"
CASE tnIndex = 2
WAIT WINDOW "2"
CASE tnIndex = 3
WAIT WINDOW "3"
ENDCASE
ENDPROC
ENDDEFINE

See Also
Concepts

Arrays
Objects in Visual FoxPro
Adding Objects to a Container Class
Working with Objects in Visual Fox Pro

b2836c9a-fc0b-4915-a6b7 -3dc1a0cee1c5 Object and Member Arrays

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Data Sto rage with Objects
See Also Send Feedback

In ob ject -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:

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

However, d ata stored in objects based on the customer class are sto red 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 g ive you access to all of the Visual Fox Pro
database management command s 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. Usu ally, th e data will be significant only while your application is run ning an d 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 wh o have access to the
application. Th e 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 an d
manipulated in an object. The fo llowing class definition, for example, initiates a logon when an object based on the class is created:

Copy Code
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.AccessLeve l
This.LogonTime = D ATETIME( )
ENDPROC
* Create methods to retu rn protected property va lues.
PROCEDURE GetLogonTim e
RETURN This.LogonT ime
ENDPROC
PROCEDURE GetAccessLe vel
RETURN This.Access Level
ENDPROC

ENDDEFINE

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

Copy Code
oUser = CREATEOBJECT('Ne wUser')
oUser.Logon

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

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

See Also
Concepts

Object and Member Arrays


Object and Data Integration
Object Reference Creation
Object-Oriented Programming

0d845e0e-8f95-4dfc-8b75-4a414a5ae37b Data Sto rage with Objects

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Call Methods
See Also Send Feedback

Once an object h as been created, you can call the methods of that o bject from anywhere in your application.

To call a method

 Use this syntax:


Copy Code
Parent.Object.Method

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

Copy Code
frsFormSet.frmForm1.Show
frsFormSet.frmForm1.txtG etText1.SetFocus

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

Copy Code
Form1.Caption = Form1.Ge tNewCaption( )
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.

See Also
Concepts

Pro tecting and Hidin g Class Members


Overriding Default Property Settings
Working with Classes in Visual FoxPro
Object-Oriented Programming

2dea8b2b-fd68-4e14 -a564 -0cf3778 565b6 How to: Call Methods

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Object and Data Integration
See Also Send Feedback

In most applications, you can b est utilize the power of Visual FoxPro b y integrating objects and d ata. Most Visual FoxPro classes
have prop erties and methods th at allow you to integrate the power of a relational database manager and a full object-oriented system.

Pro perties for Integrating Visual FoxPro Classes and Database Data
Class Data properties
RecordSource, ChildOrder,
Grid
Lin kMaster
All other controls Contro lSource
List box and combo
Contro lSource, RowSource
box
Form and form set DataSession

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

For more info rmation about integrating data and objects, see Creating Forms, and Using Controls

See Also
Concepts

Data Sto rage with Objects


Object Reference Creation
Object-Oriented Programming

c5aa391f-027d-4ad6-b784-4670947203be Object and Data Integration

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Create Instances of Classes with the Class Browser
See Also Send Feedback

You can create instances of classes in the Class Browser so you can view instances of those classes. For example, if you create an
instance of a form or form class, the form is created and displayed.

Note:
When you create an instance of a class, the code in the Init ev ent and po ssibly other events ru ns. Before y ou create an instance, know
what code is associated with your classes. If the class requires a particular environment th at has not been set up, Visual FoxPro
generates errors. The Class Browser does not provide error handling for user-defined classes.

To create an instance of a class

1. Open the class library or fo rm in the Class Browser.

2. In the class list of the Class Browser, select the class or form you want to create an instance of.

3. Drag the class icon that appears nex t to the type list in the Class Browser to the main Visual FoxPro window.

Note:
If you drag a form or form class to the main Visual Fox Pro window, the form is created and displayed. If you drag a control to the
main Visual FoxPro window, the control is add ed to the _SCREEN object. For more information, see _SCREEN System Variable

To create an instance of the class without displaying it, press an d hold the SHIFT key during the drag operation. To suppress error
messages when y ou create in stances, press and hold the CTRL key during the drag operation.

To call the appropriate NEWOBJECT( ) or CREATEOBJECT( ) function to instantiate the class, you can drag the class icon to the
Command window.

To remove an object from the _SCREEN object

 Use the RemoveObject method for _SCREEN.

For example, suppose you drag the VCR class from Buttons.vcx class in the Visual FoxPro ...\Samples\Classes directory to a form.
You can remove the instance of the class from _SCREEN by typ ing the following line of code in the Command wind ow:

Copy Code
_SCREEN.RemoveObject("VC R1")

See Also
Concepts

Operating the Class Browser


Class Browser Buttons
Class Browser Window
How to: Customize the Class Browser
SaveAs Method (Visual FoxPro)
SaveAsClass Method
How to: View Class Hierarchies
How to: View Type Library In formation

8a4e34cd -0c1b -4bf3-8dab-01f49de77661 How to: Create Instances of Classes with the Class Browser

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Add Controls to Forms with the Class Browser
See Also Send Feedback

You can add con trols from the Class Browser while designing or running a form.

To add controls to a form or container

1. In the Form Designer, open th e form.

2. In the Class Browser Window, open th e class library file con taining the class of the object you want to add to the form.

3. Fro m the Class list, select the class name, and then drag the class icon on the form. The class icon is located above th e Class
list.

To vie w the class for a control on a form or in a c ontainer

1. In the Form Designer, select the control.

2. Fro m the Tools menu, choose Class Browser. The Class Browser opens and displays the class of the control you selected on
the form.

You can design your forms so that you can add objects of a class from the Class Browser on the form while it is ru nning. You might
want to design a form class that has th is feature as one of its properties.

To add objects on a running form or a container on a form

1. Run the form.

2. Open the Class Browser an d view the class list containing the class of object you want to add to the form.

3. Select the class you want and d rag the class icon from the Class Browser to the form.

4. A new object appears on th e form based on the class you selected from the Class Browser.

Tip:
You can also add an instance of the selected class to any container by positioning the mouse pointer over the container and entering
the followin g line of code in the Command window: _oBrowser.FormAddObject(SYS(1270))

To vie w the class for a control on a running form

1. Set the focus to the control.

2. Fro m the Tools menu, choose Class Browser. The Class Browser ev aluates _SCREEN.ActiveForm.ActiveControl an d
displays the class of the control you selected on the form.

See Also
Concepts

Operating the Class Browser


Class Browser Buttons
Class Browser Window
How to: Customize the Class Browser
SaveAs Method (Visual FoxPro)
SaveAsClass Method
How to: View Class Hierarchies
How to: View Type Library In formation

44912b18-c809-4208-b689-cf6f4c0978d1 How to: Add Controls to Forms with the Class Browser

c
d
e
f
g Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Understanding the Event Model
Send Feedback

The Visual FoxPro event model is extensive and provides much control over ho w the components in your application respond to
wide variety of system and user actions. Visual FoxPro manag es the processing of events so you can provide a richer interactive
environment for application users.

In This Section
Events in Visual FoxPro

Pro vides an overview of events in Visual FoxPro.

Event Sequence in Visual FoxPro

Explains and illustrates the sequence in which events occur.

How to: Track Even t Sequen ces

Explains how to track events.

Considerations for Even t Code

Describes considerations to remember when adding code to events.

Event Binding for Objects

Introduces event binding which makes it possible for you to attach events, methods, and properties from a Visual FoxPro
object or an event from a Component Object Model (COM) object to a Visual FoxPro object.

Related Sections
Object-Oriented Programming

Discusses how you can create self-contained application componen ts that respond to user actions and to the system and which
can be easily maintained and reused.

Pro gramming in Visual FoxPro

Describes how understanding object -oriented prog ramming techniques and the ev ent-driven model can maximize your
programming productivity and enable you to access the full power of Visual FoxPro.
d3087fe2-ae39 -42b0-95a1 -62618480a63b Understanding the Event Model

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Events in Visual FoxPro
See Also Send Feedback

Events o ccur automatically when the system o r application user performs a specific action. Events associated with an object occur
when a user interacts with the object in any way , su ch as tabbing to it, clicking it, or moving the mouse pointer over it. For example,
the CommandButton class contains a Click ev ent that is triggered when the user clicks the command button.

You can add cod e to the event pro ced ure of an object so that when the event occurs for the object, the code executes automatically.
For example, you can add code to the Click ev ent so that when the user clicks the command button, the code executes automatically
to perform an action , su ch as o pening a form. System events can also execute code in events as in th e case of the Timer ev ent in a
Timer co ntrol.

The following table contains a list of the core set of Visual FoxPro events, which apply to most controls.

Core Events in Visual FoxPro


Event Event occurs when
Init An object is created.
Destroy An object is released from memory.
The user clicks the object using the primary
Click mouse button.
The user double-clicks the object using the
DblClick primary mouse butto n.
The user clicks the object using the secondary
RightClick
mouse button.
The object receives the focus through u ser action
such as tabbing or clicking or by changing the
GotFocus focus in code using the SetFocus Method. For
more information, see SetFocus Method .
The object loses the focus through user actio n
such as tabbing to or clicking another object or
LostFocus by changing the focus in code usin g the
SetFocus method.
KeyPress The user presses and releases a key.
The user presses the mouse button while the
Mo useDown mouse pointer is over the object.

The user moves the mouse pointer over the


Mo useMove
object.
The user releases the mouse button while the
Mo useUp
mouse pointer is over the object.

Triggering Events Programmatically


Mo st events occur automatically when th e sy stem or user performs an action. However, you can generate the following events
programmatically using certain Visual Fox Pro commands:
 Use the MOUSE co mmand to generate the Click, DblClick, MouseMove, and DragDrop ev ents.

 Use the ERROR co mmand to generate the Error ev ent.

 Use the KEYBOARD co mmand to generate the KeyPress ev ent.

For more info rmation, see MOUSE Command , ERROR Command, and KEYBOARD Command.

Though you cannot trigger most events programmatically, you can call the procedure associated with the event, which executes the
code in the event but does not trigger the event itself. For example, the following line calls the Activate ev ent procedure for the form
frmPhoneLog an d executes the code in the event; however, it does not activate the form itself:

Copy Code
frmPhoneLog.Activate

If you want to activate the form, use the form's Show method:

Copy Code
frmPhoneLog.Show

Calling the Show method displays and activates the form, which also executes the code in the Activate ev ent.

See Also
Concepts

Event Sequence in Visual FoxPro


Considerations for Even t Code
Event Binding for Objects
Understanding the Event Model

e84973a0-2060-47ad -adfc-52b472305ed2 Events in Visual FoxPro

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Event Sequence in Visual FoxPro
See Also Send Feedback

Though some events o ccu r as single events, a user action often triggers multiple events. Some of these events occur independently;
however, some event sequences are fixed, for examp le, the event sequ ence that occurs when a form is created or destroyed.

When a seq uence of even ts is triggered for a control, the entire seq uence of even ts is associated with the control. Fo r example,
sup pose you click the left mouse button on a comman d button and the drag the mou se po inter away from the command button. The
command butto n's MouseMove ev ent continues to occur even though the mouse poin ter moves over the form. If you release the left
mouse button over the form instead of over the command button, the MouseUp ev ent that occurs is associated with the command
button instead of the form.

The following table sh ows the general sequence of Visual FoxPro events, assuming that the data env ironment's AutoOpenTables
property is set to True (.T.). Other even ts can occur based on user interaction and system response.

Visual FoxPro Event Sequence


Object Event that occurs
Data environment BeforeOpenTables
Form set Load
Form Load
Data environment cursor(s) Init
Data environment Init
Objects 1 Init
Form Init
Form set Init
Form set Activate
Form Activate
Object1 2 When
Form GotFocus
Object1 GotFocus
Object1 Message
Object1 Valid 3
Object1 LostFocus
Object2 3 When
Object2 GotFocus
Object2 Message
Object2 Valid 4
Object2 LostFocus
Form QueryUnload
Form Destroy
Object 5 Destroy
Form Unload
Form set Unload
Data environment AfterCloseTables
Data environment Destroy
Data environment cursor(s) Destroy

1. For each object, fro m innermost object to outermost container 2. First object in the tab order 3. Next ob ject to get focus 4. As the
object lo ses focus 5.For each object, from outermost container to innermost object

Event Sequence Example


The following example uses a form to illustrate the ord er in which events occur in response to user interactio n.

A sample form
In this example, the user performs the following actions:

1. Runs the form.

2. Types text in th e Text1 text box.

3. Selects the text and copies it to the Clipboard.

4. Mo ves to the Text2 text box by pressing the TAB key.

5. Pastes the text into Text2.

6. Closes the form by clicking the Command2 command button.

These actions trigger sy stem events for each object. Th e following tables list the events that occur in response to each user action.

Note:
In this example, the Paint event has been removed from the tables because this event occurs frequently and makes it difficult to see
the sequences of the o ther events.

Action 1

The user runs the form by typing the following command in the Command wind ow:

Copy Code
DO FORM form1 NAME frmOb ject

Visual FoxPro loads the form, initializes each object, and then initializes the form. The form is activ ated and the first text box
receives input focus.

Object Event
DataEnvironment BeforeOpenTables
Form1 Load
DataEnvironment Init
Text1 Init
Text2 Init
Command 1 Init
Command 2 Init
Form1 Init
Form1 Activate
Form1 GotFocus
Text1 When
Text1 GotFocus
Action 2

The user types the text "Test" in the text box, Text1. Each keystroke generates two events.

Note:
The KeyPress ev ent receives two parameters: a number representing the pressed key and the state of the SHIFT, ALT, and CTRL
keys.
Object Event Parameters
Text1 KeyPress (84 for "T", 1)
Text1 InteractiveChange
Text1 KeyPress (101 for "e", 0)
Text1 InteractiveChange
Text1 KeyPress (115 for "s", 0)
Text1 InteractiveChange
Text1 KeyPress (116 for "t",0)
Text1 InteractiveChange

Action 3

The user selects the text in the text box, Text1, b y double-clicking the text and copies the tex t to the Clipboard by p ressing CTRL+C.
Mo use events and a Click ev ent accompany the DblClick ev ent.

Note:
The MouseMove, MouseDown, and MouseUp ev ents receive four parameters: a number indicating the pressed button, the state of
the SHIFT key, and (X, Y) coordinates. The X and Y coordinates are relative to the form and reflect the form's scale mode, for
example, pixels. Though only one MouseMove ev ent is listed for each control, in actuality, this event can occur half a dozen times or
more.
Object Event Parameters
Form1 Mo useMove (0, 0, 100, 35)
Text1 Mo useMove (0, 0, 44, 22)
Text1 Mo useDown (1, 0, 44, 22)
Text1 Mo useUp (1, 0, 44, 22)
Text1 Click
Text1 Mo useDown (1, 0, 44, 22)
Text1 Mo useUp (1, 0, 44, 22)
Text1 DblClick

Action 4

The user moves to the text box, Text2, by pressing the TAB key.

Object Event Parameters


Text1 KeyPress (9, 0)
Text1 Valid
Text1 LostFocus
Text2 When
Text2 GotFocus
Action 5

The user pastes the text into the text box, Text2, by pressing CTRL+V.

Object Event
Text2 InteractiveChange

Action 6

The user clicks the command button, Command2, to close th e form.

Object Event
Form1 Mo useMove
Command 2 Mo useMove
Text2 Valid
Command 2 When
Text2 LostFocus
Command 2 GotFocus
Command 2 Mo useDown (1, 0, 143, 128)
Command 2 Mo useUp (1, 0, 143, 128)
Command 2 Click
Command 2 Valid
Command 2 When

When the form closes and objects are released, additional events take place in the opposite order of the events listed for Action 1.

Object Event
Form1 Destroy
Command 2 Destroy
Command 1 Destroy
Text2 Destroy
Text1 Destroy
Form1 Unload
DataEnvironment AfterCloseTables
DataEnvironment Destroy

See Also
Concepts

Events in Visual FoxPro


How to: Track Even t Sequen ces
Event Binding for Objects
Understanding the Event Model

14fedca4 -268d-4abb-af1f-091f5f524 0c5 Event Sequence in Visual FoxPro


g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Track Even t Sequen ces
See Also Send Feedback

You can view the sequence in which events occur by turning on event tracking in the Visual Fo xPro Debugger. You can determine
the most efficient location to add co de to events by using event tracking to see when the events associated with your forms and
controls occu r in relatio n to o ther events.

To turn on event tracking

1. On the Tools menu, choose Debug ger.

2. On the Tools menu of the Visual FoxPro Debugger, choose Event Tracking.

3. In the Event Tracking dialog box, select Turn event tracking on.

You can also set event tracking by using the SET EVENTTRACKING co mmand. For more information, see SET
EVENTTRACKING Command .

By default, the events that appear in the event trackin g list appear in th e Debug Output window as they occur. You can also choose to
send output results to a file.

For more info rmation, see How to: Use the Debugger, Debugger Window, and Event Tracking Dialog Box .

See Also
Concepts

Event Sequence in Visual FoxPro


Events in Visual FoxPro
Considerations for Even t Code
Understanding the Event Model

e77b7e4b-12e9-4d8d-9297-da21d4f36cd9 How to: Track Even t Sequen ces

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Considerations for Even t Code
See Also Send Feedback

When you add code to events, remember the following considerations:

 The set of events for Visual FoxPro base classes is fixed and cann ot be extended.

 Every class recognizes a set of fixed default events, which includes a minimum of the Init, Destroy , and Error ev ents.

 Containers do not process even ts associated with the co ntrols they contain.

 If no event code is associated with a control, Visu al FoxPro checks whether code exists for the event higher up in the class
hierarch y for the control.
 The sequence of events can affect the location where you add code.

The following sections contain mo re information ab out the last three con siderations.

Events of Objects in Containers


Each object, even those in containers, receives its events independently. For example, suppose a form contains a command button.
When the user clicks the command button, only th e Click ev ent for the command button is triggered, not the form's Click ev ent.
Therefore, if cod e exists for a form's Click ev ent but no code exists for the command button's Click ev ent, nothing happens when the
user clicks the button.

This con sideration also applies to grid contro ls. A grid contain s columns, wh ich contain headers and controls. When an event occurs
for an inner object, only the object asso ciated with event recognizes the event. The h igher-level container does not recognize the
even t.

Note:
An exception to this rule exists. If event code exists for an option button group or a command b utton group, but no event code exists
for the event of a particular option or button in the group, the group's event code is executed when the event for the particular option
or bu tton occurs.

Events of Controls from User-Defined Classes


When an event o ccu rs for a control based on a user-defined class, Visual FoxPro checks the contro l for event code. If code exists in
the control's event procedure, Visual FoxPro executes it. However, if n o code exists in the control's event p rocedure, Visual FoxPro
searches the next level up in the control's class hierarchy for code asso ciated with that event. If Visual FoxPro finds code for the
even t, it executes that code and does not continue searching further up the hierarchy.

Event Sequence Considerations


When determining where to add event code, remember the following considerations:

 The Init ev ent of a form occurs after all Init ev ents for controls on the form occur. Therefore, you can include code in the
form's Init ev ent to manipulate any of the controls on the form b efore the form displays.

 If you want to execute code when the value of a list box, combo box, or check box changes, add the code to the control's
InteractiveChange ev ent instead o f the Click ev ent. The Click ev ent might no t occur or might be called even if the value does
not change.

 When you drag a control, other mouse events are suspended. For example, the MouseUp an d MouseMove ev ents do not occur
during a drag operation.

 The Valid an d When ev ents return a value with True (.T.) as the default. If code returns False (.F.) or 0 in the When ev ent, the
control cannot receive focu s. If code returns False (.F.) o r 0 in the Valid ev ent, focus cannot leave the control.

See Also
Concepts

Events in Visual FoxPro


Event Sequence in Visual FoxPro
Understanding the Event Model

679788e5 -bc81 -470b-b86f-854dd70a1559 Considerations for Even t Code

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c
d
e
f
g J#
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Event Binding for Objects
Send Feedback

You can use event binding to attach an event, method, or property from a Visual FoxPro o bject or an event from a Component Object
Mo del (COM) object, both of which can act as event sources, to a Visual FoxPro object. Ho wever, the ap proach for bindin g events
from native and COM objects differs.

In This Section
Event Binding for Visual FoxPro Objects

Discusses binding events, methods, and properties from other native Visual FoxPro objects to Visual FoxPro objects.

Event Binding for COM Objects

Discusses binding events from COM objects to Visu al FoxPro objects.

Related Sections
Understanding the Event Model

Pro vides an overview of events, how ev ents occur, and how to track events.

Using Visual FoxPro

Pro vides an overview of Visual FoxPro featu res, describes concepts and productivity tools for developing, programming, and
managing high-performance database applications and componen ts.

Reference (Visual FoxPro)

Includes Visual FoxPro general, programming language, user interface, and error message reference topics.

Samples and Walkthroughs

Contains Visual FoxPro code samples and step -by-step walkthroughs th at you can u se for experimenting with and learning
Visual FoxPro features.

70c74abb-6b29-4696-822a-5301a48de671 Event Binding for Objects

c
d
e
f
g Visual Basic
c C#
d
e
f
g
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Event Binding for Visual FoxPro Objects
See Also Send Feedback

You can use event binding to trigger events, properties, o r methods of native Visual FoxPro objects from other Visual FoxPro objects
using the following functions:

 BINDEVENT( )

Associates an event from a native Visual FoxPro object with the metho d or ev ent of another Visual Fo xPro object.

 UNBINDEVENTS( )
Detaches events previously boun d to Visual FoxPro o bjects.

 RAISEEVENT( )

Raises, or triggers, events for user-defined custo m methods. You can also use RAISEEVENT( ) for native events and
methods.

 AEVENTS( )

Retrieves information about the number of existing event bindings.

For a solution sample demo nstrating binding events, raising events programmatically, un binding events, and retrieving events, see
Binding, Raising, Unbinding, and Retrieving Events Sample.

For information about binding events from Compon ent Object Model (COM) objects, see Event Binding for COM Objects an d
EVENTHANDLER( ) Function .

Binding an Event
You can use the BINDEVENT( ) function to attach, or bind, an event, method, or property fro m one Visual Fox Pro object, or event
sou rce, to the method or event of an other Visual FoxPro object, or the event handler. The method that handles the event acts as a
"delegate" for the event handler.

You can bind to any valid Visu al FoxPro object method o r event, including the Access an d Assign methods. However, both th e event
sou rce and event handler must be valid Visual FoxPro ob jects. You cannot use COM objects or bind to methods of objects in
collections referenced by the _VFP system variable because these collections also pass through COM.

Note:
When you specify objects for event binding, make sure they are fully instantiated. Do not bind events, methods, or prop erties to an
object in its Load or Init ev ent because the object migh t not yet be fu lly instantiated and can cause the binding operation to fail.

You can use the same object as both the event source and event hand ler. The following example shows how Form1 acts as both
sou rce and handler:

Copy Code
BINDEVENT( Form1, "Resiz e", Form1, "myresize1" )

You can use different objects from the same class as the event source and handler. However, the event of an object that is used as
both the event source and handler cannot be the same as the delegate method.

You can bind multiple even t handlers to the same event source and event in an act referred to as "multi-casting." If multiple handlers
exist for the same event, events occur in first in, first out (FIFO) order.

You can bind multiple d elegate methods from an event handler to a particular event source and event. For example:

Copy Code
BINDEVENT( Form1, "Resiz e", oHandler, "myresize1 " )
BINDEVENT( Form1, "Resiz e", oHandler, "myresize2 " )

You cannot bind to an event with parameters that are passed by reference. Though calling BINDEVENT( ) succeeds, raising the
even t, for examp le, using RAISEEVENT( ), fails.

Visual FoxPro does not support event binding in designers such as the form and class d esigners, even though you can obtain object
references using the ASELOBJ( ) or SYS(1270 ) functions.

For more info rmation, see BINDEVENT( ) Function, ASELOBJ( ) Function , and SYS(1270 ) - Object Location . For a sample, see
Bind, Raise, Unbind, and Retrieve Events Sample.

Unbinding an Event
You can use the UNBINDEVENTS( ) function to detach events, methods, and properties that were b ound using the BINDEVENT
( ) function from native Visual FoxPro o bjects. UNBINDEVENTS( ) returns the number of events that it unbinds if it succeeds. You
can specify a Visual FoxPro object event source or an object reference, which can be used as the event sou rce or event handler.

For more info rmation, see UNBINDEVENTS( ) Function.

Raising an Event
You can use the RAISEEVENT( ) function to raise, or trig ger, events for custom and native methods. Directly calling methods does
not make events occur, unless you set the appropriate flags when using BINDEVENT( ) to attach events to oth er objects. Therefore,
you need RAISEEVENT( ) to trigger these ev ents.

For more info rmation, see RAISEEVENT( ) Function .

Retrieving Event Binding Information


You can use the AEVENTS( ) function to retrieve the number of Visual FoxPro events that are currently bound to Visual FoxPro
objects. Visual FoxPro stores the information in an array. Dependin g on th e parameters you pass, AEVENTS( ) returns either a
single-element array containing an object reference to the event source or an array which represents each existing ev ent binding as a
row and contains information ab out the binding across five columns.

For more info rmation, see AEVENTS( ) Function.

See Also
Concepts

Event Binding for Objects


Understanding the Event Model

d0d1eaf7 -9399-4b84 -a073 -42239bdafdbb Event Binding for Visual FoxPro Objects

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Event Binding for COM Objects
See Also Send Feedback

You can bind events from Co mponent Object Model (COM) objects to a Visual FoxPro object by using the EVENTHANDLER( )
function. For example, by b inding an event from an ActiveX Data Object (ADO) recordset, you can run Visual FoxPro code when
the record poin ter moves around in the recordset. The EVENTHANDLER( ) function specifically handles binding events raised by
COM objects and by the IConnectionPoint interface, which is part of COM. For more information, see EVENTHANDLER( )
Function .

However, Visu al FoxPro does not support the raising events through the IConnectionPoint interface directly. In order to bind a
COM ev ent to a Visual FoxPro object, the object must implement the event interface of the COM ob ject, an action referred to as
tightly-coupled event handling, where both the event source and event sink objects are live when the event occurs. Event sinks are
clients that bind to a connectable o bject because they receive events triggered by the connectable object.

Instead, COM+ Events, part of COM+ Services, provides the preferred strategy for handling events between COM components.
COM+ Events sends and delivers event no tifications between applications. Applications can send and receiv e notifications of events,
such as the hiring of a new employee, a change in a sto ck price, or a drop in inventory lev el that requires restocking.

In the COM+ Events model, applications that send out event notifications act as event sources and are called publishers. Applications
that receive event notifications are called subscribers. COM+ Events are often called loo sely coupled events becau se pu blishers and
sub scribers do not possess any knowledge ab out each other and allow event sub scribers to remain inactive until events occur. Instead,
you define a set of even ts inside the scope of an event class, and this event class is installed in a COM+ applicatio n.
To use COM+ Events, you author an event class that implements o ne or more interfaces. Each interface defines a group of methods,
which rep resents a set of events. You write subscriber components that implement these interfaces and respond to events wh en they
occu r. Finally , you write a pu blisher application to create objects from the event class and call various methods when the application
is ready to fire events. Th e event service han dles processing the method and delivering the events to every subscriber.

See Also
Concepts

Event Binding for Visual FoxPro Objects


Event Binding for Objects
Understanding the Event Model

ffbb29bb -77ed -48c3 -9161-19f56dd505b6 Event Binding for COM Objects

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Accessing APIs
Send Feedback

If your application has requirements that cannot be met by the features already built into Visual FoxPro, you can extend the program
by taking advantage of external libraries such as Microsoft ActiveX controls or d ynamic-link libraries (DLLs). Using external
libraries, you can add all kinds of objects to your application, from enhanced text boxes to calendars and other full-featured
applications, and you can take advantage of the functio nality offered by other p rograms (including Microsoft Windows) through their
application programming interfaces (APIs).

In This Section
Extending Visu al FoxPro with External Libraries

Explains that you can add Microsoft ActiveX controls (.ocx files) to your application easily, which provides you with new
objects to use in forms, to subclass, and to manage the way you work with native Visual FoxPro controls. In addition, you can
link to an external library, such as a DLL, and call the library's functions to use in yo ur own programs.

Accessing the Visual FoxPro API

If an external library is not available to suit your needs, you can write your own Microsoft ActiveX control o r Visual FoxPro -
specific dynamic-link library (.fll file). By calling the functions availab le in the Visual FoxPro API, you can create controls or
libraries that are tightly integ rated with and optimized for use in Visual FoxPro.

Related Sections
Pro gramming in Visual FoxPro

Visual FoxPro is a powerful interactive data management tool, but you also can access the full power of Visual FoxPro by
creating applications. Understanding object-oriented prog ramming techniques and the ev ent-driven model can maximize your
programming productivity.

How to: Create Programs

Explains the two ways to create a Visual Fox Pro prog ram, which is a text file containing a series of commands.

Object-Oriented Programming

With object -oriented prog ramming, you can create self-contained application componen ts that respond to user actions and to
the system and which can be easily maintained an d reused.

Optimizing Applicatio ns

Describes ways to optimize the performance o f you r stable, running application by making your application smaller and faster.

ae4c77c5-b2f9 -4a9c-b46f-fcb3582 28d26 Accessing APIs

c
d
e
f
g Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Extending Visu al FoxPro with External Libraries
Send Feedback

You can extend the native capabilities of Microsoft® Visual FoxPro ® by taking advantage of the facilities of Microsoft® ActiveX ®
controls (.ocx files), ActiveX objects, and dynamic-link libraries (DLLs). External libraries make it possible for you to access not
only the capabilities of other programs but also those of Micro soft® Windows ®. For example, you can use an ActiveX control to
read and up date the Windows registry directly, or it can call system-level functions by linking to one of the DLLs in Windows.

In This Section
Accessing External Libraries

In most cases, Visual FoxPro provides all the tools you must have to complete your application. However, occasionally you
might find that an ap plication requires additional functionality not available in Visual FoxPro already.

How to: Access ActiveX Controls and Objects

You can use any Microso ft® ActiveX® control that is available on your co mputer. To use an ActiveX control, you add it to a
form and th en set its properties, write hand lers for its events, or call its methods.

How to: Access Dynamic-Lin k Libraries

If the functionality you require is available in a DLL, y ou can link to the library and call its functions.

How to: Access a Visual FoxPro Library

Lik e a DLL, a Visual FoxPro library (.fll file) contains functions yo u can call as you would any other function.

Related Sections
Accessing APIs

If your application has requirements that cannot be met by the features already built into Visual FoxPro, you can extend the
program by taking advantage of external libraries — Microsoft® ActiveX® controls or dy namic-link libraries (DLLs).

Accessing the Visual FoxPro API

If an external library is not available to suit your needs, you can write your own Microsoft ® ActiveX® control or Visual
FoxPro -specific dynamic-link library (.fll file). By calling the functions availab le in the API available in Visual FoxPro, you
can create controls or libraries that are tightly integrated with and optimized for use in Visual FoxPro.

941bd4e8 -58e8 -4353-890d-91a96b8344c0 Extending Visu al FoxPro with External Libraries

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Accessing External Libraries
See Also Send Feedback

In most cases, Visual FoxPro provides all the tools you need to complete your application. However, occasionally you might find that
an application requires additional functionality not already available in Visual FoxPro. In those cases, you can reach outside Visual
FoxPro and take advantag e of the capabilities of external libraries.

Visual FoxPro makes it possible for you to access these kinds of external libraries:

 ActiveX controls (.ocx files) and Objects . ActiveX controls and objects are programs that include objects designed to
accomplish specific tasks. Most ActiveX con trols and objects add new objects to Visual FoxPro — everything from a new type
of text box to a calendar, calcu lator, or other complex ob ject. Some ActiveX controls and objects also incorporate additional
facilities, such as access to your e-mail system o r to the communications ports on your computer. As a rule, after incorporating
an ActiveX control or object into Visual FoxPro, you can use the objects in them as you would any Visual FoxPro base class.

 Dynamic-link libraries (.dll files). A .dll file is a library of functions that you can call from Visual FoxPro programs as you
would any user-defined function in Visual FoxPro. Many Windows programs — and Windows itself — make their
functionality available using .dll files. For example, you can access the system color settin gs for Windows by linking to a
system .dll file and calling functions in it.

 Visual FoxPro external libraries (.fll files). An .fll file is like a .dll file, but uses special protocol for sharing data with Visual
FoxPro, and often contains calls to internal Visual FoxPro functions. As a consequence, .fll files are specific to Visual FoxPro,
unlike .dll files, which can be called from any Windows program. You can call the functions in an .fll as you would any user-
defined function in Visual FoxPro.

Before yo u use any library, you must be familiar with the conventions used to access its controls or functions. For example, if you
want to include an ActiveX control on a form, you must know what prop erties, events, and method s you can use to manage the
control. For an ActiveX control, you can use a Visual FoxPro Class Browser to determine the properties, events, and methods you
can use. Similarly, if you want to call a functio n in a .dll file, you must know the fu nction name, the number and data ty pes o f the
parameter it requires, and the data type of its return value. In general, you can obtain this type of information from the documentation
that accompanies a library, whether in a book or a Help system. For info rmation about system .dll files for Windows, you can refer to
the Software Development Kit (SDK) appropriate to your version of Windows.

See Also
Concepts

Extending Visu al FoxPro with External Libraries


How to: Access ActiveX Controls and Objects
How to: Access Dynamic-Lin k Libraries
How to: Access a Visual FoxPro Library
Accessing the Visual FoxPro API

7a6eac1 a-b602-4c0e-9c9e-bddf36541ca7 Accessing External Libraries

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Access ActiveX Controls and Objects
See Also Send Feedback

You can use any ActiveX control th at is available o n your comp uter. To use an ActiveX control, you add it to a form, then set its
properties, write handlers for its events, or call its methods. You can add an ActiveX control to a form using the Form Controls
toolbar or the OLE Container Control, or b y using code. For details about adding an ActiveX control in the Form Designer, see
Sharing Information and Add ing OLE.

You can create an ActiveX control in code in much the same way you would create any Visual FoxPro con trol. However, before
creating the control you must determine the name of the con trol's class library, which is stored in the Windows registry. If you h ave
no other way to determine the class library name, use the Fo rm Designer to create the con trol (as described in the previous section),
and then g et the control's OLEClass property.

ActiveX objects can be created directly with CREATEOBJECT( ), and don't require an instance of a form.

To create an ActiveX control in code

1. Call CREATEOBJECT( ) Function to create a form.

2. Call the new form's AddObject Meth od to add the control, specifying olecontrol as the class. You must pass the control's class
library name as the third parameter of the Add Object method.

For example, the following program creates a new form and adds a listview control to it:

Copy Code
oMyForm = CREATEOBJECT(" form")
oMyForm.AddObject("oleLi stview","olecontrol", ;
"MSComctlLib.ListView Ctrl")

After you've created the form and control, you can display the form by calling its Show method, and display the control by setting its
Visible prop erty to true:

Copy Code
oMyForm.oleListview.Visi ble = .T.
oMyForm.Show

Some ActiveX controls aren't designed primarily to be used interactively by a u ser. For example, a timer control doesn't su pport
methods for u ser interaction. Even then , you can still create the control on a form because the control will usually make available a
default visible component, such as an icon. Frequently you will not be able to change or resize the icon.

If you don 't want your applicatio n to display the icon for non -interactive controls, you can hide the con trol by settin g the Visible
property of its OLE container control to false, or set its Left prop erty to a negative value (such as –100) that moves it off the visible
portion of the screen. Alternatively, you can place the control on a form that's never made visible (that is, for which the Show method
is never called). In all cases, you can still call the control's methods as if the control were visible.

See Also
Concepts

Accessing External Libraries


How to: Access Dynamic-Lin k Libraries
How to: Access a Visual FoxPro Library
Extending Visu al FoxPro with External Libraries
Accessing the Visual FoxPro API
Sharing Information and Add ing OLE
CREATEOBJECT( ) Function

5629b56f-eafd-475f-b3a0-d07b530f7e23 How to: Access ActiveX Controls and Objects

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Access Dynamic-Lin k Libraries
See Also Send Feedback
If the functionality you require is available in a DLL, y ou can link to the library and call its functions. Before calling a DLL function,
you must determine its calling protocol, including the name of the function, the number and data types of its parameters, and the d ata
type of its return value.

In Visual FoxPro, you can only use DLLs that have been written for a 32-bit environment. However, if you require access to a 16-bit
DLL, you can call it u sing functions available in Foxtools.fll. For details, see Help for Foxtools (Fo xtools.chm).

To call a DLL function

1. Register the DLL function usin g the DECLARE - DLL Command . Function names are case-sensitive.

Note:
If you specify WIN32API for the library name, Visual FoxPro searches fo r the 32 -bit Windows DLL functio n in Kernel32.d ll,
Gdi32.dll, User32.dll, Mpr.dll, and Advapi32.dll.
2. Call the function as you would any Visual FoxPro function.

For example, the following program registers the GetActiveWindow( ) function from the Windows USER system DLL, which
displays the hand le of the Visual FoxPro main window. The GetActiveWindow( ) takes no parameters, but returns a single integer:

Copy Code
DECLARE INTEGER GetActiv eWindow IN win32api
MESSAGEBOX(STR( GetActiv eWindow() ) )

The DLL containing the function you're registering must be available in the default directory, in the Windows or System directo ries,
or along the DOS path.

If the function you want to call has the same name as another functio n already available in Visual FoxPro (either a native function or
a DLL function previou sly declared), you can assign an alias to the function with the duplicate name, then call it using the alias.

Copy Code
DECLARE INTEGER GetActiv eWindow IN win32api AS G etWinHndl
MESSAGEBOX(STR( GetWinHn dl() ) )

Lin ked DLL functions remain available until you quit Visual Fo xPro, so you only need to declare them on ce per session. If you do n't
intend to call th e functions in a DLL again, you can issue the CLEAR DLLS co mmand to remove it from memory and free resources.

Note:
Issuing CLEAR DLLS clears all declared DLL functions from memory.

See Also
Concepts

Accessing External Libraries


Passing Parameters to Dynamic-Lin k Libraries
Extending Visu al FoxPro with External Libraries

ca0d 55e0 -9f98-428e-920d-4834546f53d5 How to: Access Dynamic-Lin k Libraries

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Passing Parameters to Dynamic-Lin k Libraries
See Also Send Feedback

When you register a DLL function, you must specify th e number and data types of its parameters. By default, data is passed by valu e.
You can force a parameter to be passed by reference by including an at sign (@) in front of the p arameter.
In general, DLL functions follow the data type conventions used for C, which differ from tho se used in Visual FoxPro. For example,
DLL functions do not support a data type for a date or fo r currency. If the data you're passing to a DLL function is in a data ty pe not
sup ported by the function, you must convert it to an appropriate type before passing it. For example, you can convert a date to a
numeric Julian format using commands such as the following:

Copy Code
cDate = sys(11, date())
nDate = val( cDate )

Some DLL fun ctions require more complex parameters, such as structures or arrays. If the function requires a pointer to a structure,
you must determine the layout of the structure, then emulate it as a string in Visual FoxPro before passing it or receiving it from the
DLL function. For example, the Windows system function GetSystemTime( ) expects a pointer to a structure consisting of eight
words or unsigned 16-bit in tegers indicating the year, month, day, and so on. The structure is defined this way:

Copy Code
typedef struct _SYSTEMTI ME {
WORD wYear ;
WORD wMonth ;
WORD wDayOfWeek ;
WORD wDay ;
WORD wHour ;
WORD wMinute ;
WORD wSecond ;
WORD wMilliseconds ;
} SYSTEMTIME

To pass data between Visual FoxPro and th e GetSystemTime( ) function, yo u must create a 40-byte string buffer (consisting initially
of spaces) and th en pass the address of this string to the function for it to fill in. When the string is returned, you must parse it in 2-
byte increments to extract the individual fields of the stru cture. The following fragment illustrates how you could extract three of the
fields from the structure:

Copy Code
DECLARE INTEGER GetSyste mTime IN win32api STRING @
cBuff=SPACE(40)
=GetSystemTime(@cBuff)

tYear = ALLTRIM(STR(ASC( SUBSTR(cBuff,2)) * ;


256 + ASC(SUBSTR(cBuf f,1))))
tMonth = ALLTRIM(STR(ASC (SUBSTR(cBuff,4)) * ;
256 + ASC(SUBSTR(cBuf f,3))))
tDOW = ALLTRIM(STR(ASC(S UBSTR(cBuff,6)) * ;
256 + ASC(SUBSTR(cBuf f,5))))

For more info rmation, you can examine the sample form Systime.scx in the Visual FoxPro ...\Samples\Solution \Winapi directo ry.
For other examples of how to pass parameters to DLL fu nctions, see the program Registry.prg in the Visu al
FoxPro ...\Samples\Classes directory.

If the data you're wo rking with in Visual FoxPro is in an array , you must loop through th e array and concatenate it into a single string
representing a C-style array before passing it to the DLL function. If the Windows function expects 16 -bit or 32-bit values, y ou must
convert the values to their hex equivalents before concatenating them into string. When you pass the string containing the array data,
Visual FoxPro passes the address of the string variable to the DLL, which can then manipulate it as an array. For an example of this,
see the sample form Syscolor.scx in the Visual FoxPro ...\Samples\Solution\Winapi d irectory.

See Also
Concepts

How to: Access Dynamic-Lin k Libraries


Extending Visu al FoxPro with External Libraries

f3cc247e-24a4 -4dcd -a30d -44c649d677b0 Passing Parameters to Dynamic-Lin k Libraries

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c
d
e
f
g Visual C++
g
c
d
e
f J#
c
d
e
f
g JScript
Visual FoxPro 9.0 SP2
How to: Access a Visual FoxPro Library
See Also Send Feedback

A Visual FoxPro library (.fll file), like a .dll file, contains functions you can call as you would any other function. It is generally
easier to pass parameters to and from fun ctions in .fll files because they are created specifically fo r calling from Visu al FoxPro.

To use a Visual FoxPro library, register the .fll file by specifying the name of the .fll file with the SET LIBRARY Command
command, and then call the function normally. Unlike registering .dll functions, you do not need to register individ ual functions in
the .fll file, nor do you need to specify information about the p arameters or data types used by the function.

Note:
If you want to use an .fll lib rary from an earlier version of Visual FoxPro, the library must be recompiled to work with Visual FoxPro
version 5.0.

To call an .fll function

1. Register the .fll library by issuing a SET LIBRARY co mmand.

2. Call the functions in the library as you would any function.

For example, the following code calls a function from the Foxtools.fll library in the Visual FoxPro installation directory to determine
what typ e of drive th e C: drive is:

Copy Code
SET LIBRARY TO "C:\Progr am Files\Microsoft Visua l FoxPro 9.0\Foxtools.f ll"
? DriveType("C:")

If you need to register more than one .fll file, include the ADDITIVE keyword in the SET LIBRARY co mmand. If you don't, the
previously registered .fll file is cleared and replaced by the one most recently registered.

If a function name conflicts with that of another function already available in Visual FoxPro, the last function defined takes
precedence. If the functio n name in a linked library has the same name as that of an intrinsic Visual FoxPro function, the Visual
FoxPro function takes precedence.

You only need to register functions in an .fll file once p er session because they remain available until you quit Visual FoxPro. If you
do not intend to call th e functions in a .fll file again, remov e the .fll file from memory and free resources by issuin g the RELEASE
LIBRARY, RELEASE ALL, or SET LIBRARY co mmands. For more information, see RELEASE LIBRARY Command an d
RELEASE Command .

See Also
Concepts

How to: Access Dynamic-Lin k Libraries


How to: Access ActiveX Controls and Objects
Accessing External Libraries
Extending Visu al FoxPro with External Libraries
Accessing the Visual FoxPro API

119e0aa0 -9a04 -4fa1 -8612-01a73351520f How to: Access a Visual FoxPro Library

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Accessing the Visual FoxPro API
Send Feedback

If Visual FoxPro does not include the features you require for your application, you can extend the capabilities of Visual FoxPro by
creating external libraries, for example, a Microsoft ActiveX con trol (.ocx) file or Visual FoxPro dynamic-link library (FLL) file.

Visual FoxPro includes th e Lib rary Construction Kit, which con tains the files Pro_Ext.h, WinAPIMS.lib, and OcxAPI.lib so you can
create ActiveX contro ls and FLLs.

Note:
The Library Construction Kit h as a limit of 65,000 elements for arrays.

In This Section
Lib rary or ActiveX Object Creation

Explains extending the capabilities of Visual FoxPro by creating external libraries that accomplish tasks required by y our
application.

How to: Create a Basic ActiveX Ob ject

Describes how to create an ActiveX control.

Creating Visual FoxPro Dynamic-Lin k Libraries

Pro vides information about creating Visual FoxPro dyn amic-link libraries.

FoxInfo Structure

Describes the FoxInfo structure used to communicate function names an d parameter descriptions between Visual FoxPro and
your FLL library.

FoxTable Structure

Describes the FoxTable structure which keeps track of all the FoxInfo structures you have for a given library.

How to: Add Visual FoxPro API Calls

Describes how to integrate your external library with Visual FoxPro usin g Visual FoxPro API routines.

Parameters in External Libraries

Describes how to pass arguments to parameters in external lib raries.

How to: Return Values from ActiveX Controls and FLL Libraries

Describes how to return values from ex ternal libraries to Visual FoxPro.

Passing Parameters to Visual FoxPro API Functions

Explains how Visual FoxPro API routines require parameters of a particular Visual FoxPro data structure.

Access to Visual FoxPro Variables and Fields

Explains accessing Visu al FoxPro variables or field values in your ActiveX control or FLL fu nction.

Memory Management Using the Visual FoxPro API

Pro vides an overview about managing memory usin g the Visual FoxPro API.

How to: Manage Memory


Describes how th e Visual FoxPro API provides direct access to th e Visual FoxPro dynamic memory manager.

How to: Build and Debug Libraries and ActiveX Controls

Describes how to build and debug ActiveX controls and FLLs.

Related Sections
Accessing APIs

Discusses how you can extend an application by tak ing advantage of external libraries such as Microsoft ActiveX controls or
Visual FoxPro dynamic-link libraries (FLLs).

Extending Visu al FoxPro with External Libraries

Explains that you can add Microsoft ActiveX controls (.ocx files) to your application , which provides you with new objects to
use in forms, to subclass, and to manage the way you work with native Visual FoxPro controls. In addition, you can link to an
external library, such as a Visual FoxPro dyn amic-link library (FLL) and call the library's functions to use in your own
programs.

API Library Construction

Pro vides reference material about API Library routines, system events, and key codes.

566a1828 -db5f-432f-8940-c4dd53c08920 Accessing the Visual FoxPro API

c
d
e
f
g Visual Basic
c C#
d
e
f
g
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Lib rary or ActiveX Object Creation
See Also Send Feedback

You can extend the capabilities of Visu al FoxPro by creating programs in C or C++ that accomplish tasks req uired by you r
application. For example, if your application requires direct access to Win dows facilities, you can write a C or C++ program that
makes calls to the Windows API, and then returns information to Visual FoxPro.

You can create three types of programs to access the Visual FoxPro API:

 An ActiveX co ntrol (.ocx file).

 A COM object.

 A DLL specific to Visual FoxPro. Because the DLL can be called on ly from Visual Fox Pro, it is customary to use the file
name extension .fll for the DLL file.

Each type of program has advantages. ActiveX controls have th e following advantages:

 Can be accessed using standard object-oriented techniques, such as setting its properties and invoking its methods.

 Can be subclassed, and its methods overridden.

 Is encapsulated, and can be called (instantiated) multiple times without complex environment management to preserve user
states.

 Features simpler parameter passing.

 Can also be called from other Windows programs, if you program it with this in mind.
COM objects have the follo wing advantages:

 Can be accessed using standard object-oriented techniques, such as setting its properties and invoking its methods.

 Its methods can be overridden.

 Is encapsulated, and can be called (instantiated) multiple times without complex environment management to preserve user
states.

 Features simpler parameter passing.

 Can also be called from other Windows programs, if you program it with this in mind.

Visual FoxPro dynamic-link (.fll) libraries might be more familiar to you if you have used prev ious versio ns of Visual FoxPro.

See Also
Concepts

How to: Create a Basic ActiveX Ob ject


Creating Visual FoxPro Dynamic-Lin k Libraries
Accessing the Visual FoxPro API

9b71d622-14b2-43bb-a1db-0e3fee2b4f36 Lib rary or ActiveX Object Creation

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Create a Basic ActiveX Ob ject
See Also Send Feedback

You can create COM objects with the ActiveX Temp late Library provided with Microsoft® Visual C++.

You create Microsoft ActiveX controls specific to Visual FoxPro as you would any similar control. Most C++ compilers allow you to
create skeletons of the control, and they can be created with the Micro so ft Visual Basic Control Creation Edition.

The following sections describe the steps for creating an ActiveX control with Microsoft Visual C++ 6.0 for use in Visual Fo xPro.

To create a project for the ActiveX control

1. Start Microsoft Visual C++.

2. Fro m the File menu, choose New.

3. In the New dialog box, choo se Pro ject Work sp ace.

4. In the New Project Workspace dialog box, specify a project name.

5. In the Type list, choose OLE ControlWizard .

6. Choose Create, and then follow the steps in the wizard .

When the wizard is finished, you can build the ActiveX control immediately. However, you will also need to define properties and
methods for the control.

To add properties and methods to the ActiveX control


1. Fro m the View menu, choose ClassWizard.

2. Choose the OLEAutomation tab.

3. Choose Add Method or Add Property.

4. Fill in the name, parameter, and other information required by the element you are creating, and then choose OK.

5. Choose Edit Code to display the editor, and then enter the code that defines the property or method you are creating.

For example, to create a Version property that returns the .ocx file version as an integer (such as 101), you create the property with a
return type of long , and add code similar to the following:

Copy Code
#define VERSION 101

long CPyCtrl::GetVersion ()
{
// set the version nu mber here
return VERSION;
}

Because the version number is ordin arily read-only, y ou wouldn't create a SetVersion( ) function.

See Also
Concepts

Lib rary or ActiveX Object Creation


Creating Visual FoxPro Dynamic-Lin k Libraries
Accessing the Visual FoxPro API
Extending Visu al FoxPro with External Libraries
How to: Add Visual FoxPro API Calls

ad3c5155-f458-405a-a199 -0c5c299268fc How to: Create a Basic ActiveX Ob ject

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Creating Visual FoxPro Dynamic-Lin k Libraries
See Also Send Feedback

A Visual FoxPro dynamic-link library (FLL) is essentially a DLL that contains calls to the Visual FoxPro API. You can create the
basic DLL structure in your development environment and then add the Visual Fox Pro functions you wan t to call. The following
sections describe example templates for creating FLL templates in C and C++.

Setting Up a Library Template


Each Visual FoxPro FLL library has the same basic structure. You can use a template for the structure so that you need o nly to add
code for your specific library routine.

There are five elements in a Visual FoxPro library template:

 #include statement.

 Function definition.

The function defin ition has a void return value and is passed the ParamBlk *parm parameter. For more information about the
ParamBlk parameter, see Parameters in External Libraries.

 Function code.

 FoxInfo structure.

The functions in the FLL interact with Visual FoxPro through the FoxInfo stru cture. Visual FoxPro uses FoxInfo to determine
the function n ame and the number and type of parameters.

 FoxTable structure.

The FoxTable structure is a lin ked list that keeps track of the FoxInfo structures.

For more info rmation about FoxInfo and FoxTable struct d efinitions, see the Pro_ext.h file.

You also need the following files:

 The Pro_ext.h header file.

You can print this file to see the fu nction declarations, typedefs, and structs used in the Visual FoxPro API.

 The Winapims.lib file.

Both of these files are located in the Microsoft Visual FoxPro ..\Samples\API directory.

Sample Templates
For C routines, you can use the following template:

Copy Code
#include <Pro_ext.h>

void Internal_Name(Param Blk *parm)


{
// Function code goes he re.
}

FoxInfo myFoxInfo[] = {
{"FUNC_NAME", (FPFI) Internal_Name, 0, ""},
};

FoxTable _FoxTable = {
(FoxTable *)0, sizeof (myFoxInfo)/sizeof(FoxIn fo), myFoxInfo
};

For C++ routines, you need to declare the FoxTable structure as external in the following template:

Copy Code
#include <Pro_ext.h>

void Internal_Name(Param Blk *parm)


{
// Function code goes he re.
}

FoxInfo myFoxInfo[] = {
{"FUNC_NAME", (FPF I) Internal_Name, 0, ""} ,
};

extern "C" {
FoxTable _FoxTable = {
(FoxTable *)0, siz eof(myFoxInfo)/sizeof(Fo xInfo), myFoxInfo
};
}
See Also
Concepts

FoxInfo Structure
FoxTable Structure
API Library Construction
How to: Add Visual FoxPro API Calls
Accessing the Visual FoxPro API

7c00ef9f-63ed -43bf-b71f-54e98d8a9caf Creating Visual FoxPro Dynamic-Lin k Libraries

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
FoxInfo Structure
See Also Send Feedback

The FoxInfo structure is used to communicate functio n names and parameter descriptions b etween Visual FoxPro and your FLL
library.

The following code illustrates the sy ntax for a FoxInfo structure:

Copy Code
FoxInfo arrayname [ ] = {
{funcName1 , FPFI function1, parmCount1 , parmTypes1}
{funcName2 , FPFI function2, parmCount2 , parmTypes2}
. . .
{funcNameN , FPFI functionN, parmCountN , parmTypesN}
};

The following table describes the parameters in this structure.

Parameter Description
Specifies a variable of type FoxInfo.

arrayname Note:
You can include sev eral FoxInfo structure lines in
this array.
Contains the name that the Visual FoxPro user
funcName
calls to invoke your function.
Specifies the address of y our C language routine.
functio n This is the exact (case-sensitive) name you use to
define your function.

Specifies the number of parameters described in


the parmTypes string or on e of the following flag
values. Th e follo wing list describes possible flag
values:

 INTERNAL

Specifies that the function cannot be called


directly from Visual FoxPro.

 CALLONLOAD
Specifies that the routine is to be called
when the library is loaded.
CALLONLOAD can't call any routine that
returns results to Visual FoxPro.

 CALLONUNLOAD
parmCount
Specifies that the routine is to be called
when the library is unloaded or when the
Visual FoxPro QUIT command is issued.
CALLONUNLOAD cannot call any
routine that returns resu lts to Visual FoxPro.

Describes the data type of each parameter.

The following lists the valid values for


parmTypes .

 ""

No parameter.

 "?"

Specifies that any ty pe can be passed. In the


body of the functio n, you'll need to check
the type of the passed parameter.

 "C"

Specifies a Character type parameter.

 "D"

Specifies a Date type parameter.

parmTypes  "I"

Specifies an Integer type parameter.

 "L"

Specifies a Logical type parameter.

 "N"

Specifies a Numeric type parameter.

 "R"

Reference.

 "T"

Specifies a DateTime type parameter.

 "Y"

Specifies a Currency type parameter

 "O"
Specifies an Object type parameter
Note:
Include a type value for each parameter passed to the library. To indicate that a parameter is optional, precede it with a period (.).
Only trailing parameters can be omitted.

For example, suppose you create a function that accepts a character and a numeric p arameter. When you specify parmType, use
"CN".

The following example FoxInfo structure defines a library with one function, which is internally named dates an d externally accessed
as DATES. The structure accepts one Character type parameter:

Copy Code
FoxInfo myFoxInfo[] = {
{ "DATES", (FPFI) dat es, 1, "C" }
};

After you compile your FLL library with this FoxInfo structure and load it in Visual FoxPro using the SET LIBRARY co mmand,
you can call this function in Visual FoxPro with the following line of cod e:

Copy Code
=DATES("01/01/95")

See Also
Concepts

Creating Visual FoxPro Dynamic-Lin k Libraries


API Library Construction
How to: Add Visual FoxPro API Calls
Accessing the Visual FoxPro API

f29fdefe-24fe-48d7-868b-59e3a9551226 FoxInfo Structure

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
FoxTable Structure
See Also Send Feedback

The FoxTable structure is a lin ked list that keeps track of all the FoxInfo structures you have for a given library.

The following code illustrates the sy ntax for th e FoxTable structure:

Copy Code
FoxTable _FoxTable = { nextLibrary, infoCount ,infoPtr};

The following table describes the parameters in this structure.

Parameter Description
Specifies a pointer used internally by Visual
nextLibrary FoxPro and should be initialized to 0.

Specifies the number of Visual FoxPro external


infoCount routines defined in this library.

infoPtr Specifies the address of the first element of an


array of FoxInfo structures. This name must
match the array name listed in the FoxInfo
statement.

The following example illustrates a Fox Table statement. If your Fo xInfo array name is myFoxInfo , you'll never need to chang e this
statement:

Copy Code
FoxTable _FoxTable = {
(FoxTable *) 0,
sizeof( myFoxInfo) / sizeof( FoxInfo ),
myFoxInfo
};

Visual FoxPro captures General Protection Faults (GPFs) in ActiveX controls placed on a form, or COM objects instantiated from
within Visual FoxPro. A GPF in an ActiveX control or COM object is now treated as a trappable Visual FoxPro error (Error 1440 -
OLE object migh t be corrupt).

See Also
Concepts

Creating Visual FoxPro Dynamic-Lin k Libraries


API Library Construction
How to: Add Visual FoxPro API Calls
Accessing the Visual FoxPro API

1cf7cf31 -6b15-46ba-baf8 -3c1229ef8569 FoxTable Structure

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Add Visual FoxPro API Calls
See Also Send Feedback

To integrate your program with Visual FoxPro, you can call Visual FoxPro API routines. Th ese API routines are functions you can
call from any C or C++ program, including an .ocx or .fll file, that give you access to variables, manag e d atabase operations, and
accomplish many other Visual FoxPro-specific tasks.

The following table lists the general categories of API calls availab le in Visual FoxPro. For details about individual API functions,
see API Library Routines A -Z or API Library Routines by Categ ory.

To use the Visual Fo xPro API routines, you must include the file Pro_ext.h, available in the Visual FoxPro API directory. This file
includes the p rototypes for the functions and structures that allow you to share information with Visual FoxPro.

If you're writing an ActiveX control, you mu st also add calls to initialize and clear the API.

To add Visual FoxPro API routines to your ActiveX obje ct

1. Use #INCLUDE to include the Pro_ext.h file along with any other required header files.

2. In the Constructo r (Init method ) of the control, call _OCXAPI( ) to initialize the interface to Visual FoxPro using this code:

Copy Code
_OCXAPI(AfxGetInstanceHa ndle(),DLL_PROCESS_ATTAC H);
3. Include calls to the Visu al FoxPro API as required in your object.

4. In the Destructor (Destroy method) for the object, call _OCXAPI( ) again to release the p rocess created in the Constructor,
using this cod e:
Copy Code
_OCXAPI(AfxGetInstanceHa ndle(),DLL_PROCESS_DETAC H);

For an example of an .fll library that includes calls to the Visual FoxPro API, see the sample programs in \Api\Samples directory that
have the extension C: EVENT.C, HELLO.C, and so on.

If you use Visual FoxPro API calls in your ActiveX control, COM object, or .fll library, the code containing the calls is incompatible
with other applications. You mig ht therefore want to build one or more tests into the program to determine whether the object is
being called from Visual FoxPro.

For example, if you're creating an ActiveX control using the Microsoft Foundation Classes, you can change the control's constructor
code to include a test and then alert the user if the control has been called from a p rogram other than Visual FoxPro:

Copy Code
if (!_OCXAPI(AfxGetInsta nceHandle(),DLL_PROCESS_ ATTACH))
{
::MessageBox(0,"This OCX can only be hosted b y Visual Foxpro","",0);
//Here you can do whatever you want when t he host isn't VFP:
// you might want to reject loading or you
// might want to s et a property
// saying that the host isn't VFP and the control will use other
// means to achiev e it's purpose.
}

If you're creating an ActiveX control using the Microsoft ActiveX Template Library, use the following code:

Copy Code
if (!_OCXAPI(_Module.Get ModuleInstance(),DLL_PRO CESS_ATTACH))
{
::MessageBox(0,"This OCX can only be hosted b y Visual Foxpro","",0);
//Here you can do whatever you want when t he host isn't VFP:
// you might want to reject loading or you
// might want to s et a property
// saying that the host isn't VFP and the control will use other
// means to achiev e it's purpose.
}

In this example, the control doesn't exit, and will continue running after the user has acknowledged the message. The strategy you
choose depends on how you anticipate the control will be used. For examp le, if you detect that the control is being u sed o utside of
Visual FoxPro, you can set a flag that you test at each point in the control where yo u call the Visual Fox Pro API. If the flag indicates
that the con trol is outside Visual FoxPro , you can branch aro und the API call to an alternative means of accomplishing the same task.

See Also
Concepts

Creating Visual FoxPro Dynamic-Lin k Libraries


Accessing the Visual FoxPro API
Parameters in External Libraries
How to: Return Values from ActiveX Controls and FLL Libraries
Extending Visu al FoxPro with External Libraries
API Library Construction

9f65d44f-5cd5 -407e-bd20-c6a8 ca5 84db9 How to: Add Visual FoxPro API Calls

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Parameters in External Libraries
See Also Send Feedback
You can pass arguments to parameters when Visual FoxPro calls an ActiveX control, COM object, or Visual FoxPro dynamic-link
library (FLL). For example, an ActiveX co ntrol might accept arguments when calling one of its method s. Similarly, a Visual FoxPro
program might call a function in your FLL library and pass argu ments to it.

Visual FoxPro can pass arguments to parameters in an ex ternal library by value or by reference. By default, the setting of the SET
UDFPARMS co mmand is respected. However, oth er variables, such as arrays or fields, and expressions are passed by value. For
information about how to change the default way of passing argumen ts, see Passing Data to Parameters.

Because ActiveX controls and COM objects are Windows -standard programs, no special mechanism is required to pass arguments
from Visual FoxPro to parameters in an ActiveX control or COM object. You can write library code as if it were receiving arguments
from any C or C++ p rogram.

However, functions in an FLL library use the FoxInfo structure to receive data from Visual FoxPro. The FoxInfo structure lists
library functions and the number and type of parameters they expect. For example, the following FoxInfo structure belon gs to a
library with one function, internally called dates , that accepts one Character parameter:

Copy Code
FoxInfo myFoxInfo[] = {
{ "DATES", (FPFI) dat es, 1, "C" }
};

Functions you define in external libraries actually receive only one parameter, a pointer to the parameter block. This parameter block,
defined in the ParamBlk structure, stores all the information abou t the parameters that were passed from the Visual FoxPro function
call. The following co de illustrates the fo rmat that your function declaration should follow:

Copy Code
void function_name(Param Blk *parm)

For example, the function definition for dates is:

Copy Code
void dates(ParamBlk *par m)

The ParamBlk structure consists of an integer that represen ts the number of parameters, immediately followed by an array of
parameter unions. The structure definition is included in Pro_ext.h:

Copy Code
/* A parameter list to a library function. */
typedef struct {
short int pCount; /* number of parameter s passed */
Parameter p[1]; /* pCount parameters */
} ParamBlk;

The Parameter typedef included in the ParamBlk structure is a union of a Value structure and a Locator structure. Call by value is
handled by a Value structure; call by reference is handled by a Locator structure. You use these structures to access the parameters
passed to your function when the function is called in Visual FoxPro.

The following information is extracted from the file Pro_ext.h and shows the definition of the Parameter type:

Copy Code
/* A parameter to a libr ary function. */
typedef union {
Value val;
Locator loc;
} Parameter;

Value Structure Definition


If a parameter is passed to your function by value, use the Value structure to access it. The following Value structure defin ition is
extracted from the Pro_ext.h file:

Copy Code
// An expression's value .
Typedef struct {
char ev_type;
char ev_paddi ng;
short ev_widt h;
unsigned ev_leng th;
long ev_long;
double ev_rea l;
CCY ev_curren cy;
MHANDLE ev_handl e;
ULONG ev_obje ct;
} Value;

Value Structur e Fields

The following table is a guide to the values you can pass and receive in the Value structure for different types of data. Only the
structure fields listed for a data type are used for that data type.

Contents of Value stru cture for different data types


Data type Structure field Value
Character ev_type 'C '
ev_length string length
ev_handle MHANDLE to string
Numeric ev_type 'N '
ev_width Display wid th
ev_length Decimal places
ev_real Double precision
Integer ev_type 'I '
ev_width Display wid th
ev_long Long integer
Date ev_type 'D '
ev_real Date 1
Date Time ev_type 'T'
ev_real Date + (seco nds/8640 0.0)
Currency ev_type 'Y '
ev_width Display wid th
ev_currency Currency value 2
Logical ev_type 'L'
ev_length 0 or 1
Memo ev_type 'M'
ev_wdith FCHAN
ev_long Length of memo field
ev_real Offset of memo field
General ev_type 'G '
ev_wdith FCHAN
ev_long Length of general field
ev_real Offset of general field
Object ev_type 'O '
ev_object Object identifier
Null ev_type '0' (zero)
ev_long Data type

1. The date is represented as a double-precision floating-point Julian day nu mber calculated using Algorithm 199 from Collected
Algorithms of the ACM. 2. The cu rrency value is a long integer, with an implied decimal point in fron t of the last fo ur digits.

Note:
ev_length is the only true indicator of a string's length. The string can't have a null terminator because the string can contain
embedded nu ll characters.

Locator Structure Definition


Use the Locato r stru cture to manipulate parameters passed by reference. The followin g Locator structure defin ition is extracted from
the Pro_ext.h file:

Copy Code
typedef struct {
char l_type;
short l_where, /* Data base number or -1 for memory */
l_NTI, /* Variabl e name table offset*/
l_offset, /* Index in to database*/
l_subs, /* # subscrip ts specified 0 <= x <= 2 */
l_sub1, l_sub2; /* sub script integral values * /
} Locator;

Locator Structure Fields

The following table is a guide to the fields in the Locator structure.

Locator Field use


field
l_type 'R '
The number of the table containing this field , or –
l_where
1 for a variab le.
l_NTI Name Table Index . Visual FoxPro internal use.
Field number within table. Visual Fox Pro internal
l_offset use.
For variables only, the number of subscripts (0 –
l_subs 2).
For variables only, the first sub script if l_subs is
l_sub1
not 0.
For variables only, the second subscript if l_subs
l_sub2
is 2.
Note:
It's good programming practice to check for the parameter type in ev_type to help determine which fields to access from the Value
structure.

An Example of Accessing Parameters in an FLL Library

The following example uses _StrCpy( ) to return a Character ty pe to Visual FoxPro that's the concatenation of its two Character
parameters. Notice that although the handle of each parameter's Value structure is used as working memory to p erform the
concatenation, changes to this memory allocation don 't affect the Visual FoxPro argument that was passed by value.
Copy Code
#include <Pro_ext.h>

Example(ParamBlk *parm)
{
// make the paramBlk str ucture easier
// to manage by using #d efine shortcuts
#define p0 (parm ->p[0].val)
#define p1 (parm ->p[1].val)

// make sure there is en ough memory


if (!_SetHandSize(p0.ev_ handle, p0.ev_length + p 1.ev_length))
_Error(182); // "Insu fficient memory"

// lock the handles


_HLock(p0.ev_handle);
_HLock(p1.ev_handle);

// convert handles to po inters and make sure the


// strings are null -terminated
((char *)_HandToPtr(p0.e v_handle))[p0.ev_length] = '\0';
((char *)_HandToPtr(p1.e v_handle))[p1.ev_length] = '\0';

// concatenate strings u sing the API function _S trCpy


_StrCpy((char *)_HandToP tr(p0.ev_handle) + p0.ev _length,
_HandToPtr(p1.ev_handle) );

// return the concatenat ed string to Visual FoxP ro


_RetChar(_HandToPtr(p0.e v_handle));

// unlock the handles


_HUnLock(p0.ev_handle);
_HUnLock(p1.ev_handle);
}

FoxInfo myFoxInfo[] = {
{"STRCAT", Example, 2 , "CC"},
};

FoxTable _FoxTable = {
(FoxTable *) 0, sizeo f(myFoxInfo)/sizeof(FoxI nfo), myFoxInfo
};

See Also
Concepts

How to: Add Visual FoxPro API Calls


How to: Return Values from ActiveX Controls and FLL Libraries
Accessing the Visual FoxPro API
Passing Parameters to Visual FoxPro API Functions
Extending Visu al FoxPro with External Libraries
API Library Construction

ad9896fa-643e-48d3-a3b9 -d738971e71a3 Parameters in External Libraries

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Return Values from ActiveX Controls and FLL Libraries
See Also Send Feedback

You can return v alues fro m ActiveX controls or Visu al FoxPro dynamic-link libraries (FLL) to Visual FoxPro.

To return values from ActiveX controls to Visual FoxPro


 Use the RETURN statement in the control and pass a single value.

The following example returns uses a RETURN statement to return the version number stored in VERSION:

Copy Code
#define VERSION 101

// other code here

long CPyCtrl::GetVersion ()
{
// set the version nu mber here in variable fV ersion
return VERSION;
}

Returning Values from FLL Libraries


When you wan t to return values from FLL libraries, use API functions, not native C or C++ commands.

Note:
When return values from an Activ eX control (.ocx) file, do not use the API functions for returning values from FLL lib raries.
Instead, use the RETURN statement.

To return values from an FLL library

 Use the API functions listed in the following table.

The following API functions should be used only for FLL lib raries.

Function Description
_RetChar(char Sets the function return value to a null-
*string ) terminated string.
_RetCurren cy(CCY Sets the function return value to a
cval, int width) currency value.
Sets the function return value to a date.
_RetDateStr(char
The date is specified in mm/dd/yy[yy]
*string )
format.
Sets the function return value to a date
_RetDateTimeStr
and time specified in mm/dd/yy[yy]
(char *string) hh:mm:ss format.
_RetFloat(double Sets the function return value to a float
flt, int width, in t
value.
dec)
_RetInt(long ival, Sets the function return value to a
int width) numeric value.
Sets the function return value to a logical
_RetLogical(in t
value. Zero is consid ered FALSE. An y
flag) non-zero value is con sidered TRUE.
Passes a complete Visual FoxPro Value
structure; any Visual FoxPro data type
_RetVal(Value except for memo can be returned. You
*val) must call _RetVal( ) to return a string
that contains embedded null characters or
to retu rn a .NULL. value.
Note:
To return the value of an object data type, use the _RetVal() function, filling in the ev_object field in the Value structure.
The following example, Sum , accepts a reference to a numeric field in a table and uses _RetFloat to return the sum of the values in
the field:

Copy Code
#include <Pro_ext.h>

Sum(ParamBlk *parm)
{
// declare variables
double tot = 0, rec_cnt;
int i = 0, workarea = -1; // -1 is current workarea
Value val;

// GO TOP
_DBRewind(workarea);

// Get RECCOUNT( )
rec_cnt = _DBRecCount(wo rkarea);

// Loop through table


for(i = 0; i < rec_cnt; i++)
{
//Place value of the field into the Value str ucture
_Load(&parm ->p[0].loc, &val);

// add the value to t he cumulative total


tot += val.ev_real;

// SKIP 1 in the work area


_DBSkip(workarea, 1);
}

// Return the sum value to Visual FoxPro


_RetFloat(tot, 10, 4);
}
// The Sum function rece ives one Reference param eter
FoxInfo myFoxInfo[] = {
{"SUM", Sum, 1,"R"}
};
FoxTable _FoxTable = {
(FoxTable *) 0, sizeo f(myFoxInfo)/sizeof(FoxI nfo), myFoxInfo
};

Assuming there's a numeric field named amount in the currently open table, the following line of code in a Visual FoxPro program
calls the function:

Copy Code
? SUM(@amount)

See Also
Concepts

Parameters in External Libraries


Passing Parameters to Visual FoxPro API Functions
Accessing the Visual FoxPro API
Extending Visu al FoxPro with External Libraries
Access to Visual FoxPro Variables and Fields
API Library Construction

73c38886 -0f6a-4f7b -a01e-af8727aa03 ca How to: Return Values from ActiveX Controls and FLL Libraries

c
d
e
f
g Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Passing Parameters to Visual FoxPro API Functions
See Also Send Feedback

Often the Visual FoxPro API routines will require parameters of a particular Visual FoxPro data structu re. The following sections
provide a list of Visual FoxPro data types and additional data structures. For the actual type definitions and structure definitions, refer
to the Pro_ext.h file.

Visual FoxPro API Data Types


The following data types are used in Visual FoxPro API routines.

Data type Description


The number of a line in an open file in an editing
EDLINE
window. The first line is 1.
The offset position of a character in an open file
EDPOS in an editing window. The offset position of the
first character in the file or memo field is 0.
File channel. Every file opened by Visual
FCHAN FoxPro, or through the API by using _FCreate( )
and _FOpen( ), is assigned an FCHAN.
A 32 -bit pointer to a fu nction returning an
FPFI
integer.
A unique identifier assigned to a single
ITEMID
command on a menu.
MENUID A unique identifier assigned to a menu.
A unique identifier given to every block of
memory allocated by Visual FoxPro, or allocated
MHANDLE through the API using _AllocHand( ). It can be
de-referenced to its pointer using _HandToPtr( ).
Name table index. Every variable and table
NTI field's name has an entry in this table.
Window handle. A u nique identifier assigned to
WHANDLE every win dow op ened by Visual FoxPro, or
opened through the API using _WOpen( ).
Note:
Because FAR pointers are not app ropriate for 32-bit compilers, #define statements in Pro_ ext.h redefine FAR, _far , and __far as null
values.

Visual FoxPro API Data Structures


The primary data structures used in the Visual FoxPro API library are listed in the following table.

Structure Description
A structure used to d escribe what th e system is
EventRec doing at a given time.
Used in FLL libraries for communicating between
FoxInfo Visual FoxPro and your program; not used in .ocx
files.
Used in FLL libraries for communicating between
FoxTable Visual FoxPro and your program; not used in .ocx
files.
A structure used to access parameter values (FLL)
Locator
or Visual FoxPro v ariables or fields (FLL and ocx).
Used in FLL libraries for communicating between
ParamBlk Visual FoxPro and your program; not used in .ocx
files.
Used in FLL libraries for communicating between
Parameter Visual FoxPro and your program; not used in .ocx
files.
A structure that defines the horizontal and vertical
Point coordinates o f a single point on the screen.
Coordinates are sp ecified in rows and columns.
A structure that defines the coordinates of a
rectangle on the screen. The upp er-left corner of the
Rect rectangle is defined by (top ,left) an d the lower-right
corner is defined by (bottom-1,right -1).
Coordinates are sp ecified in rows and columns.
A structure used to access parameter values (FLL)
Value or Visual FoxPro v ariables or fields (FLL and
OCX).

See Also
Concepts

How to: Return Values from ActiveX Controls and FLL Libraries
Access to Visual FoxPro Variables and Fields
Accessing the Visual FoxPro API
Extending Visu al FoxPro with External Libraries
How to: Manage Memory
API Library Construction

30d2a218 -a9d2 -42cf-8bd9 -d1c05037dd7b Passing Parameters to Visual FoxPro API Functions

c
d
e
f
g Visual Basic
c C#
d
e
f
g
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Access to Visual FoxPro Variables and Fields
See Also Send Feedback

You can access Visual FoxPro variables or field values in your ActiveX control o r FLL function, either to read them or to set them.
In addition, you can create new variables that can be accessed from within Visual FoxPro.

Variables and fields are made available in Visual FoxPro in a name table, which is an array containing the names of all currently
defined variables and fields. You can access an individual element in the array using a name table index (NTI). A special API
function, _NameTableIndex ( ), returns the index of an existing variable or field based on a name that you provide. After y ou've
determined the NTI for a given variable, you can read it using the _Load( ) API function or set it using the _Store( ) API function. To
create a new variable, you can call the API function _NewVar( ).

To access Visu al FoxPro variables o r fields, you u se the Value and Locator structures defined in Pro_ext.h. If you're creating an FLL
library, yo u can use the same technique you used to access parameters passed to your fu nctions. For details about the Value and
Locator structures, see Parameters in External Libraries .

The following example illustrates how you can use the Value and Lo cator structures in an ActiveX co ntrol to access Visual FoxPro
variables.
Copy Code
long CFoxtlibCtrl::TLGet TypeAttr(long pTypeInfo, LPCTSTR szArrName)
{
int nResult = 1;
TYPEATTR *lpTypeAttr;
Locator loc;
Value val;
OLECHAR szGuid[128];
char *szBuff;
__try {
if (_FindVar(_NameTab leIndex(( char *)szArrNa me),-1,&loc)) {
((ITypeInfo *)pTyp eInfo)->GetTypeAttr(&lpTypeAttr );
if (_ALen(loc.l_NT I, AL_ELEMENTS) < 16) {
_Error(631); // Array argument not of pr oper size.
}

//1 = Guid
StringFromGUID2(lp TypeAttr->guid, (LPOLESTR )&szGui d,sizeof(szGuid));
OLEOleToAnsiString (szGuid,&szBuff);
val.ev_type = 'C';
val.ev_length = st rlen(szBuff);
val.ev_handle = _A llocHand(val.ev_length);
_HLock(val.ev_hand le);
_MemMove((char *) _HandToPtr( val.ev_handl e ), szBuff, val.ev_len gth);
OLEFreeString((voi d **)&szBuff);
_HUnLock(val.ev_ha ndle);
loc.l_sub1 = 1;
_Store(&loc,&val);
_FreeHand(val.ev_h andle);

//2 = LCID
loc.l_sub1 = 2;
val.ev_type = 'I';
val.ev_long = lpTy peAttr->lcid;
_Store(&loc,&val);

// code for values 3 - 16 here


((ITypeInfo *)pTyp eInfo) -> ReleaseTypeAttr(lpType Attr);
}
} __except (EXCEPTIO N_EXECUTE_HANDLER) {
nResult = 0;
}
return nResult;

See Also
Concepts

Passing Parameters to Visual FoxPro API Functions


How to: Manage Memory
Accessing the Visual FoxPro API
Extending Visu al FoxPro with External Libraries
How to: Build and Debug Libraries and ActiveX Controls
_NameTableIndex ( ) API Library Routine

516c775c-a95b-418e-bd73 -ed13bba66afd Access to Visual FoxPro Variables and Fields

c
d
e
f
g Visual Basic
c C#
d
e
f
g
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
Memory Management Using the Visual FoxPro API
See Also Send Feedback

The Visual FoxPro API provides direct access to the Visual FoxPro dynamic memory manager. API routines that request memory
allocations return memory handles, which identify memory. The Visual FoxPro segment-loading architecture uses handles instead of
pointers so it can manag e memory more efficiently.

A memory handle is essentially an index in an array of pointers. The pointers point to blocks of memory that Visual FoxPro knows
about. Nearly all references to memory in the API are made through hand les instead of the more conventional C pointers.

Understanding Stacks
The control or library you create does not have its own memory stack. Instead, it uses the memory stack of its calling program, or in
this case, the Visual FoxPro stack. However, you cannot control the size of the Visual FoxPro stack or affect the amoun t of stack
space availab le to an ActiveX control o r FLL.

Under normal circumstan ces, this distinction isn't important. The Visual Fox Pro stack is generally large enough to hold the automatic
variables you might need to allocate in a control or library. If you run out of stack space, you can always allocate additional memory
on the heap d ynamically.

Rules for Using Handles


The following rules apply to allocating and freeing memory handles:

 Users must free all handles they allocate, includin g handles allo cated by function s such as _Load().

 _Load() only creates a han dle when the variable you're loading is a character string (that is, ev_type = 'C'). All the other data
types store their values in the Valu e structure itself, while loading a character string puts an MHANDLE in the ev_handle of
the Value structure.

 In an FLL library, Visual FoxPro assumes responsibility for freeing all handles returned with _RetVal( ). Users must not free
these handles, even if they allocate them.

 Users must not free handles passed to them in their ParamBlk.

Caution:
When you write an ex ternal routine that calls functions, make sure to follow all rules and check the retu rn results. A stray pointer or
handle reference could damage th e Visual FoxPro internal data structures, causing an immediate abnormal termination o r delayed
problems, which could result in data loss.

See Also
Concepts

How to: Manage Memory


Accessing the Visual FoxPro API

9b6de5b9 -949e-4542-93c3-cf177e40ef5c Memory Management Using the Visual FoxPro API

g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Manage Memory
See Also Send Feedback

You can allocate and manage memory using the Visual Fo xPro API.

Note:
The techn iques described apply to both ActiveX controls and FLL libraries.

To allocate and use memory


1. Allocate a handle with _AllocHand( ).

2. Lock the handle with _HLock ( ).

3. Convert the handle into a pointer with _HandToPtr( ).

4. Reference the memory by using the pointer.

5. Unlock the handle with _HUnLock( ).

Note:
To avoid memo file corruption, don't write to a memo file before calling _AllocMemo( ).

In order to address the allocated memory, your API routines must convert the handle to a pointer by calling the _HandToPtr( )
routine. Even if the Visual FoxPro memory manager needs to reorganize memory to obtain more contiguous memory for subsequent
memory requ ests, th e handle remains the same. Routines that grow, shrink, free, and lock memory allocation s are also provided.

When you're creating external routines, try to minimize memory use. If you create an external routine that dyn amically allocates
memory, try to use the least amount of memory possible. Be especially careful abo ut locking large memo ry allocations for long
periods of time. Remember to unlock memory handles with _HUnLock( ) when they no longer need to be locked, becau se the
performance of Visual FoxPro can be adversely affected by locked memory handles.

Caution:
Excessive use of dynamic memory deprives Visual FoxPro of memory for buffers, windows, menus, and so on, and degrades
performance, b ecause the memory given to fill API requests is managed by the Visual FoxPro memory manager. Allocating large
handles and retaining them could cause Visual FoxPro to run out of memory and terminate abnormally. The Visual FoxPro
environment has no memory protectio n. The external API routine cannot provide all the validation that's inherent in a standard Visual
FoxPro program. If you corrupt memory, you receive messages such as "Transgressed handle," "Internal consistency error," an d
"Transgressed node du ring compaction."

The following function from an FLL library illustrates memory allo cation. The example uses _RetDateStr( ) to return a Visual
FoxPro Date type (assuming that the Character parameter is a proper date):

Copy Code
#include <Pro_ext.h>

void dates(ParamBlk *pa rm)


{
MHANDLE mh;
char *instring;

if ((mh = _AllocHand( parm->p[0].val.ev_length + 1) ) == 0) {


_Error(182); // "I nsufficient memory"
}
_HLock(parm ->p[0].val.ev_handle);
instring = _HandToPtr (parm->p[0].val.ev_handle);
instring[parm ->p[0].val.ev_length] = ' \0';
_RetDateStr(instring) ;
_HUnLock(parm ->p[0].val.ev_handle);
}
FoxInfo myFoxInfo[] = {
{"DATES", (FPFI) date s, 1, "C"}
};
FoxTable _FoxTable = {
(FoxTable *) 0, sizeo f(myFoxInfo)/sizeof(FoxI nfo), myFoxInfo
};

See Also
Concepts

Memory Management Using the Visual FoxPro API


Accessing the Visual FoxPro API

36fee911 -c687-49d9-875c-4dfa97a7594e How to: Manage Memory


g
c
d
e
f Visual Basic
c
d
e
f
g C#
c Visual C++
d
e
f
g
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Build and Debug Libraries and ActiveX Controls
See Also Send Feedback

After creating a project in Visual Studio, you can build and debug it. The following procedures are for Visual Studio 6.0. For the
most recent information, read the documentation for version you are using.

Building the Project


Before bu ilding your project, you need to establish the project settings. Some of the settings you make depend on whether you want
to create a debug or release version of the con trol or library. As a rule, create debu g versions of the program until you are satisfied
that it works correctly, then create a release version.

To specify a debug or release version

1. On the Build menu, choose Set Defau lt Configuration.

2. Choose whether you're creating a debug or release version of the control.

3. Choose OK.

To establish project settings

1. Fro m the Build menu, choose Settings .

2. Under Settings For, choose whether you're creating a debug o r release version of the program.

3. Click the C/C++ tab and then make these settings:

 In the Category list, choose Code Generation.

 In the Calling Con vention list, choose _fastcall.

 In the Use run -time library list, choose Mu ltithreaded DLL.

4. Choose the Lin k tab and then in the Object/Library Modules text box, add one of the following libraries:

 If you're building an .ocx, add OCXAPI.LIB from the Visual Fox Pro API directory.

 If you're building an .fll, add WINAPIMS.LIB from the Visual Fox Pro API directory.

5. Unmark Ignore all default libraries.

6. Choose OK.

To make sure the compiler can find the necessary files

1. Fro m the Tools menu, choose Option s.

2. Click the Directories tab.

3. In the Show directories for list, choose Include files.

4. In the Directories toolbar, click the Add button.


5. Add the directory with Pro_ext.h .

6. In the Show directories for list, choose Lib rary files.

7. In the Directories toolbar, click the Add button.

8. Add the directory with Ocxapi.lib from the Visual FoxPro API directory (when creating a contro l) or add the Winapims.lib
from the Visu al FoxPro API directory (when creating an FLL)

9. In the Option s dialog box, choo se OK.

After you've specified the settings, you can compile and link your program.

To compile and link an .ocx file

 Fro m the Build menu, cho ose Build projname.ocx.

When you compile and link the .ocx file, Visual C++ automatically registers the control on the computer on which it was built. If for
any reason you must register the contro l manually, yo u can do so using the following procedure.

To register the ActiveX control

1. Fro m the Tools menu in the Microsoft Develo pment Env ironment, cho ose Register Control.

-or-

2. Declare and call DLLRegisterServer( ) fro m your program.

Debugging an ActiveX control or FLL library in the context of a full Visual FoxPro application is more difficult than deb ugging it
separately from the application. It's a good idea to create a simple test program to test the operation of your control or lib rary.

Debugging with the Microsoft Development Environme nt

Microsoft Visual C++ version 4.0 and hig her offers an integrated debugg ing environment that makes it easy to set break points and to
step thro ugh your code. You can even run Visual FoxPro from Visual C++.

To start debugging with Microsoft Visual C++

1. Fro m the Build menu, choose Settings .

2. In the Pro ject Settings dialog box, click the Debug tab.

3. In the Executable for debug session text box, type the path and name of the Visual FoxPro executab le (.exe) file. For example,
you can ty pe the following line with the appropriate substitution for the Visual FoxPro version nu mber:

C:\Program Files\Microsoft Visual FoxPro <versionNu mber>\Vfp< versionNu mber>.exe

4. Choose OK.

5. Set a break point in yo ur library.

6. Fro m the Build menu, choose Debug . Then, from the submenu choose Go .

7. When Visual Studio displays a message that says, " VFP9.exe does not contain debu gging information," choose Yes to
continue.

For more info rmation about debugging in Visual C++, see the Visual C++ do cumentation set.

Debugging with Other Debugger s

You should be able to debug a control or library with any debugger that correctly handles an INT 3 (_BreakPoint( )) embedded in
your program. You can use any debugger for symbolic debu gging as long as it can do all of the following:

 Make a symbol tab le from a map file.

 Load the symbol table independent of the p rogram.

 Relocate the symbols to a new add ress.

To debug a library

1. Add a _BreakPoint( ) call to the routine at the point where debugging will begin.

2. Build the control or library.

3. Invoke your debugger.

4. If your debugger supports symbols, load the symbol table for yo ur library.

5. Start Visual FoxPro.

6. Call your library routine from Visual FoxPro.

7. When the breakpoint is reached, make adjustments to the symbol base to align your symbols with the actual location where the
library was loaded.

8. Increment the instruction pointer (IP) reg ister by 1 to skip over the INT 3 instructio n.

9. Continue debuggin g as with a no rmal program.

Note:
Always remo ve any breakpoints specified in y our d ebugger before you release your product.

See Also
Concepts

How to: Manage Memory


Access to Visual FoxPro Variables and Fields
Accessing the Visual FoxPro API
Extending Visu al FoxPro with External Libraries
How to: Return Values from ActiveX Controls and FLL Libraries

a185d080 -15c9 -4187-a534-c105108dbd15 How to: Build and Debug Libraries and ActiveX Controls

c
d
e
f
g Visual Basic
g
c
d
e
f C#
c
d
e
f
g Visual C++
c J#
d
e
f
g
c JScript
d
e
f
g
Visual FoxPro 9.0 SP2
How to: Create Quit Routin es
See Also Send Feedback

You can create customized quit ro utines fo r you r application when the user wants to quit your application, Visual FoxPro, or
Microsoft Windows.

To create a quit routine

 Use the ON SHUTDOWN co mmand and inclu de a command or procedure to run.


The ON SHUTDOWN co mmand typically uses a DO co mmand to call a procedure or p rogram if a user tries to quit the application.
For example, the following line of code specifies a quit routine named My_QuitRoutine:

Copy Code
ON SHUTDOWN DO My_QuitRo utine

The quit routine typically includes a dialog box that prompts the user whether they want to quit the current application. If the user
wants to quit the app lication, the routine can close o pen files and clean up the enviro nment, and then call the QUIT co mmand. If the
user does not want to exit the current application, the routine can return control to the application.

For more info rmation, see ON SHUTDOWN Command.

See Also
Concepts

Working with Programs


Pro gramming in Visual FoxPro

1fcf06e4 -dd2e-4abf-9b5c-458cfde5832f How to: Create Quit Routin es

You might also like