Foxpro
Foxpro
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.
Introduces how to create and work with Visual FoxPro programs, which are text files contain ing instructions using the Visual
FoxPro language.
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.
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).
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.
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.
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}
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"
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.
Command Description
DELETE Marks specified records in a table for deletion.
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 .
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:
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:
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.
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
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
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.
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 you can set formatting options and apply them to code in programs.
Describes how to save the programs after you create and edit them.
Related Sections
Working with Projects
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.
Describes Visual FoxPro developer tools that you can use for application develop ment within the FoxPro application and the
FoxPro language.
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
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.
2. In the New dialog box, click Pro gram, and then New File.
1. Open the project for y our application in the Pro ject Manager.
In the Command window, use the MODIFY COMMAND to open an editin g window.
See Also
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
How to: Edit Programs
See Also Send Feedback
2. In the Open dialog box, choo se Pro gram in the Files of type list to show only program files.
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.
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
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.
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.
See Also
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
How to: Save Programs
See Also Send Feedback
To save a program
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
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
2. In the Do dialog box, browse for and select the program you want.
3. Click Do.
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 .
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
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 .
Explains how to call native functions as well as user-defined functions and procedures.
Describes ways to verify that correct data passes to pro ced ures and function s.
Reference
Functions
Related Sections
Passing Data to Parameters
Describes aspects of programming, such as basic programming concepts, working with programs, object-oriented
programming, and optimizing application s, in Visual FoxPro.
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
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:
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.
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.
See Also
Concepts
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
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.
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.
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
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
-OR-
-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
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)
See Also
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
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.
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
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
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())
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
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
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.
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
Preface the variable or array name with an at sign (@) as shown in the following example:
Copy Code
myFunc(@var1, var2)
See Also
Concepts
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.
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.
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
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.
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.
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).
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.
Pro vides an overview of subclasses in Visual FoxPro and provides possible uses for them.
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.
Describes how to modify a class using the Class Designer and when it is in a project.
Describes how you can create new Access and Assign Methods for p roperties.
Describes how to ad d or ed it th e description for classes and attributes for cu stom properties and methods.
Describes how you can specify the appearance of non -visual classes in design -time.
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.
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 vides an overview about designating properties and methods as hidden or protected.
Pro vides an overview about overriding the default setting of a property for a user-defined class.
Pro vides an overview about how to call or override parent class code.
Related Sections
Working with Objects in Visual Fox Pro
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.
Describes how understanding object -oriented prog ramming techniques and the ev ent-driven model can maximize your
programming productivity.
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:
For more info rmation about objects in Visual FoxPro, see Working with Objects in Visual Fox Pro .
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
Inheritance
These features help you create and maintain code more easily and quickly.
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.
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
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.
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
ClassLibrary Property
ParentClass Property
See Also
Concepts
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
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.
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.
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.
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
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.
2. In the New dialog box, choo se Class, and then click New File.
3. In the Class Name box of the New Class dialog box, type the name of the 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.
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.
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.
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
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 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:
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.
See Also
Concepts
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
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 .
-OR-
For information about openin g class libraries, see How to: Open Class Lib raries .
2. In the Project Manager, select the class you want, and click Modify.
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
See Also
Concepts
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.
When the class opens in the Class Desig ner, the Class menu app ears.
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.
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 .
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.
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
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.
1. In the New Property dialog box, select the Access Method box, the Assign Method box, or both.
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.
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.
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.
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 .
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 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
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
1. On the Form menu in the Form Designer or on the Class Men u in the Class Desig ner, choose New Method.
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.
Use the DEFINE CLASS co mmand and inclu de the THIS_ACCESS keyword.
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
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.
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.
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.
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.
Use the DEFINE CLASS co mmand and inclu de the FUNCTION clause when you create a class.
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.
For more info rmation about opening classes, see How to: Modify Classes .
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.
Use the DEFINE CLASS co mmand and inclu de the FUNCTION or PROCEDURE clause.
See Also
Concepts
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.
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.
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.
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.
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.
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
For more info rmation about opening class libraries,, see How to: Open Class Lib raries .
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
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
Caution:
Use caution when removing properties and metho ds from classes. Chang es yo u make affect code that references those properties and
methods.
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.
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
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.
For more info rmation about opening classes, see How to: Modify Classes .
3. In the Properties window, sp ecify an image file, such as a bitmap (.bmp) file, for the Picture prop erty.
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.
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.
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.
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.
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.
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.
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
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.
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-
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 .
1. Open a form.
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 .
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.
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
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.
You can create a p ublic interface for a class or object that sep arates the interface from the implementation.
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
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
The Visual FoxPro sample, Display a Stop Watch Sample, also illustrates the use of protected properties and methods in a class.
See Also
Concepts
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
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:
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
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
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 the process to copy a class from one class library to another class library.
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.
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
Related Sections
Managing Classes and Class Libraries
Introduces classes in Visu al FoxPro and how to use them to create ob jects.
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.
For more info rmation, see Class Browser Window an d Class Browser Buttons .
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)
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.
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.).
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
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.
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
2. In the class list of the Class Browser, select the class library.
Copy Code
_oBrowser.SetDefaultFile
You can specify class libraries to open by default in addition to the default library.
2. In the class list of the Class Browser, select the class library.
Copy Code
_oBrowser.SetDefaultFile (.T.)
1. In the class list of the Class Browser, select the class library.
Copy Code
_oBrowser.ResetDefaultFi le
To remove all libraries from the Class Browser list
Copy Code
_oBrowser.ResetDefaultFi le(.T.)
See Also
Concepts
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.
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.
Right -click the class, and on the shortcut menu, choose Select ParentClass .
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
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.
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.
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.
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
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.
For information about openin g the Class Browser, see How to: Run the Class Browser.
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.
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
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.
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 .
-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
See Also
Concepts
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 classes using the Class Browser, the Project Manager when the class library is part of a project, or programmatically.
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.
3. Select the class library you want to open and click Modify .
-OR-
For more info rmation, see SET CLASSLIB Command an d RELEASE CLASSLIB Command .
See Also
Concepts
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.
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.
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.
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.
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.
For example, the following line of code adds the class MyClass to MyClassLibrary:
Copy Code
ADD CLASS MyClass TO MyC lassLibrary2
See Also
Concepts
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.
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.
1. Open the project containing the class library with the class you wan t to rename.
3. Expand the class library containing the class you want to rename.
5. In the To: box of the Rename File dialog box, type a new name for the class.
6. Click OK.
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
See Also
Concepts
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.
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.
3. Expand the class library containing the class you want to copy and the destination class library.
The mouse pointer changes into a class library icon wh en you move it over a valid destination library.
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
See Also
Concepts
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.
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.
4. In the As list of the Redefine dialog box, select the name of the new parent class.
-OR-
5. Click Redefine.
See Also
Concepts
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
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.
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.
3. Expand the class library containing the class you want to remove.
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
See Also
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
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.
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.
In the Files of type drop -down list in the Open dialog box, choo se Application, *.dll, *.ocx, * .olb, or *.tlb .
The ty pe library informatio n for the selected file is display ed in the Classes & Members list.
See Also
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 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
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 .
Pro vides an explanation of how to design and build table navigation b uttons th rough code.
Defining a Grid Control
Describes how to set the properties of an object at run time or design time.
Describes how objects are referenced in the container hierarchy and explains the importance of identifying objects in relation
to the container hierarchy.
Explains how to make a reference to an object, an d describes the benefits of creating references over making copies of objects.
Describes how to create arrays containing objects and to define class members as arrays.
Describes how to call the methods of an object from anywhere in an app lication once it has been created.
Describes how to create a new instance o f a class u sing the Class Browser.
Reference
Objects, Collections, and Classes
Related Sections
Managing Classes and Class Libraries
Discusses how to create and modify classes and class libraries with in Visual FoxPro.
Discusses methods to use, modify, and create classes within Visual FoxPro.
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.
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.
See Also
Concepts
Object-Oriented Programming
How to: Create Classes and Subclasses
Manipulating Objects
Working with 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
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.
See Also
Concepts
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.
2. Click and drag the class from the Project Manager window to an op en Form Designer.
See Also
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
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
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
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.
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
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.
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.
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.
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.
Top = 3
ADD OBJECT cmdTop
AS navTop ;
WITH Left = 0
WITH Left = 25
Add the navigation buttons.
ADD OBJECT cmdNex t
AS navNext ;
WITH Left = 50
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.
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.
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.
Copy Code
DEFINE CLASS NavForm AS Form
ADD OBJECT oVCR AS vc r
ENDDEFINE
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
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.
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.
THIS.Column1.Width = 175
THIS.Column2.Width = 68
THIS.Column1.Header1.Caption
=;
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.
Width = 33 0
ADD OBJECT
grid1 AS
grdProducts
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
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.
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
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( )
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
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:
The following table provides examples of using THISFORMSET, THISFORM, THIS, and Parent to set object properties:
See Also
Concepts
Object-Oriented Programming
Working with 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
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.
Copy Code
*--NEWINV.PRG
*--Returns a reference to a new invoice form.
frmInv = CREATEOBJECT("I nvoiceForm")
RETURN frmInv
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.
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
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
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.
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
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.
Copy Code
loForm = CREATEOBJECT("F orm")
loForm.AddObject("cntBut tons", "ButtonList")
loForm.cntButtons.SetAll ("Visible", .T.)
loForm.cntButtons.Visibl e = .T.
loForm.Show(1)
DIMENSION aChoices[3]
See Also
Concepts
Arrays
Objects in Visual FoxPro
Adding Objects to a Container Class
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
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
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
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
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
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.
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.
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
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.
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.
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.
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))
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
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
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.
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.
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
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.
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
A sample form
In this example, the user performs the following actions:
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.
The user pastes the text into the text box, Text2, by pressing CTRL+V.
Object Event
Text2 InteractiveChange
Action 6
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
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.
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
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
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.
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.
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
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.
Related Sections
Understanding the Event Model
Pro vides an overview of events, how ev ents occur, and how to track events.
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.
Includes Visual FoxPro general, programming language, user interface, and error message reference topics.
Contains Visual FoxPro code samples and step -by-step walkthroughs th at you can u se for experimenting with and learning
Visual FoxPro features.
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( )
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.
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.
See Also
Concepts
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
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.
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.
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.
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.
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.
If the functionality you require is available in a DLL, y ou can link to the library and call its functions.
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).
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.
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
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.
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
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).
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
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)
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
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.
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
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.
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.
Describes how to integrate your external library with Visual FoxPro usin g Visual FoxPro API routines.
How to: Return Values from ActiveX Controls and FLL Libraries
Explains how Visual FoxPro API routines require parameters of a particular Visual FoxPro data structure.
Explains accessing Visu al FoxPro variables or field values in your ActiveX control or FLL fu nction.
Pro vides an overview about managing memory usin g the Visual FoxPro API.
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).
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.
Pro vides reference material about API Library routines, system events, and key codes.
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:
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.
Is encapsulated, and can be called (instantiated) multiple times without complex environment management to preserve user
states.
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.
Is encapsulated, and can be called (instantiated) multiple times without complex environment management to preserve user
states.
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
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.
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.
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
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++.
#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 can print this file to see the fu nction declarations, typedefs, and structs used in the Visual FoxPro API.
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>
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>
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
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.
Copy Code
FoxInfo arrayname [ ] = {
{funcName1 , FPFI function1, parmCount1 , parmTypes1}
{funcName2 , FPFI function2, parmCount2 , parmTypes2}
. . .
{funcNameN , FPFI functionN, parmCountN , parmTypesN}
};
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.
INTERNAL
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.
""
No parameter.
"?"
"C"
"D"
parmTypes "I"
"L"
"N"
"R"
Reference.
"T"
"Y"
"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
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.
Copy Code
FoxTable _FoxTable = { nextLibrary, infoCount ,infoPtr};
Parameter Description
Specifies a pointer used internally by Visual
nextLibrary FoxPro and should be initialized to 0.
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
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.
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
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)
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;
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;
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.
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.
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;
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)
FoxInfo myFoxInfo[] = {
{"STRCAT", Example, 2 , "CC"},
};
FoxTable _FoxTable = {
(FoxTable *) 0, sizeo f(myFoxInfo)/sizeof(FoxI nfo), myFoxInfo
};
See Also
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
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.
The following example returns uses a RETURN statement to return the version number stored in VERSION:
Copy Code
#define VERSION 101
long CPyCtrl::GetVersion ()
{
// set the version nu mber here in variable fV ersion
return VERSION;
}
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.
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);
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
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.
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);
See Also
Concepts
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.
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.
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
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.
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>
See Also
Concepts
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.
3. Choose OK.
2. Under Settings For, choose whether you're creating a debug o r release version of the program.
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.
6. Choose OK.
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)
After you've specified the settings, you can compile and link your program.
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.
1. Fro m the Tools menu in the Microsoft Develo pment Env ironment, cho ose Register Control.
-or-
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.
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++.
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:
4. Choose OK.
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.
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:
To debug a library
1. Add a _BreakPoint( ) call to the routine at the point where debugging will begin.
4. If your debugger supports symbols, load the symbol table for yo ur library.
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.
Note:
Always remo ve any breakpoints specified in y our d ebugger before you release your product.
See Also
Concepts
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.
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.
See Also
Concepts