Sei sulla pagina 1di 15

7.

5 SCOPE
Scope refers to the portion of a program within which a procedure definition (or a variable or named
constant definition) is recognized. The scope of a sub procedure is determined by the identifier Public
or Private, which precedes the procedure name; e.g.,
Public Sub procedure name (arguments)
or
Private Sub procedure name (arguments)
Similarly, the scope of a function procedure is determined as
Public Function procedure name (arguments) As data type
or
Private Function procedure name (arguments) As data type
A Public procedure can be accessed from any module or form within a program, whereas a Private
procedure will be recognized only within the module or form within which it is defined. The default is
Public. Hence, if a programmer-defined procedure does not include a Public/Private specification (as
in the examples presented earlier in this chapter), it is assumed to be Public. Note, however, that event
procedures automatically include the designation Private when they are created. When a Public
procedure is accessed from a module or form other than the module or form containing the module
definition, the procedure name must be preceded by the form name containing the definition; e.g.,
Call form name.procedure name (arguments)
for a sub procedure access. Function procedures are accessed similarly, with the form name
containing the function definition preceding the function name; e.g.,
variable = form name. function name (arguments)

Variables and named constants that are defined within a procedure are local to that procedure.
However, variables and named constants can also be declared within a module, external to any
procedures defined within the module. Such variables (or named constants) can be declared Public or
Private; e.g.,
Private variable name As data type
or
Public variable name As data type
In the first example (Private), the variable will be recognized anywhere within the module in which it
is declared, but not in other modules. If a different (local) variable with the same name is declared
within a procedure, then the local variable can be referenced within the procedure simply by its name.
The (global) variable declared outside of the procedure can also be referenced within the procedure,
by prefixing its name with the form name; e.g.,
form name.variable name
EXAMPLE 7.9

Now consider two different modules that contain public variables. The following skeletal outline
illustrates how these variables can be utilized within each module.
Form Module 1 Form Module 2
Public Red
Private Sub FirstSub()
.....
Red = 3

Public Green
Private Sub SecondSub()
.....
Form1.Red = 7

or Form1.Red = 3
Form2.Green = 6
End Sub

Green = 2
or Form2.Green = 2
End Sub

7.3 EVENT PROCEDURES


An event procedure is a special type of sub procedure.
It is accessed by some specific action, such as clicking on an object, rather than by the Call statement
or by referring to the procedure name. The particular action
associated with each event procedure is selected from the upper-right drop-down menu within the
Code Editor Window.
The object name and the activating event collectively make up the event procedure name. Thus,
Command1_Click().
the name of an event procedure that is activated by clicking on command button Command1. Like
any other sub procedure, arguments may be used to transfer information into an event procedure.
An empty pair of parentheses must follow the procedure name if arguments are not present.
EXAMPLE 7.4 DEFINING AN EVENT PROCEDURE
Returning to the project presented in Example 7.3, suppose we double click on command button
Command1 within the Form Design Window. The Code Editor Window will then be displayed
The object in this case is Command1 and the desired action is a mouse click, as indicated by the two
menu selections at the top of Fig. 7.9. If a different action is desired, it can be selected by clicking on
the down arrow in the upper right window and then selecting from the resulting menu, as shown in
Once the object and the action have been selected, the first and last lines of the event procedure are
generated automatically within the Code Editor Window.
The user must then provide the
remaining Visual Basic statements, thus completing the event procedure. The term Private appearing
in the first line determines the scope of the event procedure; i.e., the portion of the program in which
the event procedure is recognized. We will discuss this further later in this chap
The complete event procedure Command1_Click(), originally shown in Example 7.3, is shown within
the Code Editor Window in Fig. 7.11. The reader is again reminded that the indented statements are
provided by the programmer. Note that this event procedure accesses the sub procedure Smallest
twice.

CObject Class
Syntax
class AFX_NOVTABLE CObject

Members
Protected Constructors
Name

Description

CObject::CObject

Default constructor.

Public Methods
Name

Description

CObject::AssertValid

Validates this object's integrity.

CObject::Dump

Produces a diagnostic dump of this object.

CObject::GetRuntimeClas Returns the CRuntimeClass structure


s
corresponding to this object's class.
CObject::IsKindOf

Tests this object's relationship to a given class.

CObject::IsSerializable

Tests to see whether this object can be serialized.

CObject::Serialize

Loads or stores an object from/to an archive.

Public Operators
Name

Description

CObject::operator delete

Special delete operator.

CObject::operator new

Special new operator.

Remarks
It serves as the root not only for library classes such
as CFile and CObList, but also for the classes that you
write. CObject provides basic services, including
Serialization support
Run-time class information
Object diagnostic output
Compatibility with collection classes

Note that CObject does not support multiple inheritance. Your


derived classes can have only one CObject base class, and
that CObject must be leftmost in the hierarchy. It is
permissible, however, to have structures and non-CObjectderived classes in right-hand multiple-inheritance branches.
You will realize major benefits from CObject derivation if you
use some of the optional macros in your class implementation
and declarations.
The first-level
macros, DECLARE_DYNAMIC and IMPLEMENT_DYNAMIC, permit
run-time access to the class name and its position in the
hierarchy. This, in turn, allows meaningful diagnostic dumping.
The second-level
macros, DECLARE_SERIAL and IMPLEMENT_SERIAL, include all
the functionality of the first-level macros, and they enable an
object to be "serialized" to and from an "archive."

CWinApp Class

Syntax
class CWinApp : public CWinThread

Members
Public Constructors
Name

Description

CWinApp::CWinApp

Constructs a CWinApp object.

An application object provides member functions for initializing


your application (and each instance of it) and for running the
application.
Each application that uses the Microsoft Foundation classes can
only contain one object derived from CWinApp. This object is
constructed when other C++ global objects are constructed
and is already available when Windows calls
the WinMain function, which is supplied by the Microsoft
Foundation Class Library. Declare your derived CWinApp object
at the global level.

When you derive an application class from CWinApp, override


the InitInstance member function to create your application's
main window object.
In addition to the CWinApp member functions, the Microsoft
Foundation Class Library provides the following global functions
to access yourCWinApp object and other global information:

AfxGetApp Obtains a pointer to the CWinApp object.

AfxGetInstanceHandle Obtains a handle to the current application


instance.

AfxGetResourceHandle Obtains a handle to the application's


resources.

AfxGetAppName Obtains a pointer to a string containing the


application's name. Alternately, if you have a pointer to
the CWinAppobject, use m_pszExeName to get the application's
name.

See CWinApp: The Application Class for more on the CWinApp class,
including an overview of the following:

CWinApp-derived code written by the Application Wizard.


CWinApp's role in the execution sequence of your
application.
CWinApp's default member function implementations.
CWinApp's key overridables.
CONTROL ARRAYS

Similar to arrays of variables, you can group a set of controls together as an array.
The following facts apply to control arrays:

The set of controls that form a control array must be all of the same type (all
textboxes, all labels, all option buttons, etc.)

You set up a control array by naming one or more controls of the same type
the same name and set the Index property of each control in the array to a
non-negative value (i.e., the controls in the control array are usually indexed
from 0 to one less than the number of controls in the array).

The properties of the controls in the control array can vary: i.e., some
members can be visible or not, they can be sized differently, they can have
different fonts or colors, etc.

To refer to a member of a control array, the syntax is:


ControlName(Index)[.Property]
For example, to refer to the Text property of the first element of an array of
textboxes called txtField, you would use:
txtField(0).Text

All the members of the control array share the same event procedure for
example, if you have a control array of 10 textboxes call txtField, indexed 0 to
9, you will not have 10 different GotFocus events you will just haveone that
is shared amongst the 10 members. To differentiate which member of the
control array is being acted upon, VB will automatically pass
an Index parameter to the event procedure. For example, the GotFocus event
procedure for the txtField control array might look like this:
Private Sub txtField_GotFocus(Index As Integer)
txtField(Index).SelStart = 0
txtField(Index).SelLength =
Len(txtField(Index).Text)
End Sub
- or Private Sub txtField_GotFocus(Index As Integer)
With txtField(Index)
.SelStart = 0
.SelLength = Len(.Text)
End With
End Sub
For events where VB already passes a parameter (for example, the textbox's
KeyPress event where VB passes the KeyAscii parameter), VB will add
"Index" as the first parameter, followed by the parameters that are usually
passed to the event. For example, the procedure header of the KeyPress
event of the txtField control array would look like this:
Private Sub txtField_KeyPress(Index As Integer,
KeyAscii As Integer)

Overview of Member
Functions
Member functions are either static or nonstatic. The behavior of static member functions
differs from other member functions because static member functions have no
implicit this argument. Nonstatic member functions have a this pointer. Member
functions, whether static or nonstatic, can be defined either in or outside the class
declaration.
If a member function is defined inside a class declaration, it is treated as an inline
function, and there is no need to qualify the function name with its class name. Although
functions defined inside class declarations are already treated as inline functions, you
can use the inline keyword to document code.
An example of declaring a function within a class declaration follows:
// overview_of_member_functions1.cpp
class Account
{
public:
// Declare the member function Deposit within the declaration

// of class Account.
double Deposit( double HowMuch )
{
balance += HowMuch;
return balance;
}
private:
double balance;
};
int main()
{
}
If a member function's definition is outside the class declaration, it is treated as an inline
function only if it is explicitly declared as inline. In addition, the function name in the
definition must be qualified with its class name using the scope-resolution operator (::).
The following example is identical to the previous declaration of class
that the Deposit function is defined outside the class declaration:

Account, except

// overview_of_member_functions2.cpp
class Account
{
public:
// Declare the member function Deposit but do not define it.
double Deposit( double HowMuch );
private:
double balance;
};
inline double Account::Deposit( double HowMuch )
{
balance += HowMuch;
return balance;
}
int main()
{
}

Note

Although member functions can be defined either inside a class declaration or separately,
no member functions can be added to a class after the class is defined.

MFC MEMBER FUNCTIONS-Most of the functions an application will call are members
of an MFC
class.
Examples: ShowWindow()--a member of CWnd class.
TextOut()--a member of CDC.
LoadBitmap()--a member of CBitmap.
Applications can also call API functions directly, but it's
more
convenient to use MFC member functions.

MFC class framework makes possible to work easily with global variables and functions. Let's declare a static
member variable or function in the CWinApp derived class. It is accessible from all classes.
Example:
1. // MyApp.h
1. class CMyApp : public CWinApp
2. {
3. public:
4.

CMyApp();

5.
6.

static int g_nMyVariable;

// declaration

7.

static void g_MyFunction();

// declaration

8.

...

9.

etc

10.

...

11. };

MFC GLOBAL FUNCTIONS-MFC also defines important "global" functions that are not
members of any
MFC class.
They always begin with Afx prefix (From Application
FrameworKS).
Example: AfxMessageBox()--since message boxes are predefined
windows,
it's possible to activate one independently from the rest of
an
application.

Afx functions are either independent of or span the MFC


class hierarchy.
MFC class framework makes possible to work easily with global variables and functions. Let's declare a static
member variable or function in the CWinApp derived class. It is accessible from all classes.
Example:
1. // MyApp.h
1. class CMyApp : public CWinApp
2. {
3. public:
4.

CMyApp();

5.
6.

static int g_nMyVariable;

// declaration

7.

static void g_MyFunction();

// declaration

8.

...

9.

etc

10.

...

11. };

Create Project
Following are the steps to create a project using project templates available in
Visual Studio.
Step 1: Open the Visual studio and click on the File -> New -> Project menu
option.
Step 2: You can now see that the New Project dialog box is open.
Step 3: From the left pane, select Templates -> Visual C++ -> MFC Step 4: In
the middle pane, select MFC Application. Step 5: Enter the project name
MFCDemo in the Name field and click OK to continue. You will see the
following dialog.
4. MFC - Getting Started
Microsoft Foundation Classes
10
Step 6: Click Next.
Microsoft Foundation Classes

11
Step 7: Select the options which are shown in the dialog box given above and
click Next.
Microsoft Foundation Classes
12
Step 8: Uncheck all options and click Finish button.
Microsoft Foundation Classes
13
You can now see that the MFC wizard creates this Dialog Box and the project
files by default.
Step 9: Run this application, you will see the following output.

Different Types of Files

Random-access data files


Files designed to facilitate future retrieval of individual records in
an arbitrary order.
Retrieving a record requires determining its location
Hashing
Index (ISAM)
Thus, it is logically used like an array but data resides on disk

Binary data files


A machine-readable format that can contain almost anything
Unreadable if loaded in a word processor or text editor

Program files
Special type of binary file that the OS can interpret with the
right OCXs, DLLs, EXEs.

Sequential data files


Data elements stored and retrieved one after another, in order
Examples
Text files (Report-Record or Display-Formatted format)
Simple documents such as README files created
with ASCII text editor like Notepad
Designed to be read, so there are no field delimiters
Carriage return and line feed mark the end of each
line
Comma-separated value (CSV) files
Common means for transferring data across
applications
Contains variable length records separated by
commas
Certain types of data are surrounded by special
characters
Carriage return and line feed mark the end of each
line/record
Fixed-width data files
Commonly created from/for COBOL programs

1)

Assign a file number

To refer to file in subsequent file access statements


2) Open the file

Identify file name & path, purpose, reference number, and record
length if random file
3)

Read/Write the file (possibly within a loop)

Specify reference number, action, and data elements


Read retrieves data from the file into specified memory
locations (variables)
Write copies data in specified memory locations (variables)
to current location in file
4)

Close the file

Specify reference number to release the number and the file

Before using Sequential Files


You must determine or plan its structure
Number of records
To determine type of loop processing & size of
array(s) needed
Number, order, and type of fields per record
To determine the fields (generally on one line)
if different types: for the user-defined array
if same type: number of columns for 2-d array
Pre-data
Generally the number of following records (counting
loop)
Post-data (Sentinel data)
If present, to flag when the last good data set has
been reached

If no pre-data or post-data, may use EOF function or write


error handler to determine when end of file reached

Potrebbero piacerti anche