Chapter 15

MFC Macros and Globals


CONTENTS

When you're writing programs, there are many types of data and operations that you must use again and again. Sometimes, you have to do something as simple as creating a portable integer data type. Other times, you need to do something a little more complex, like extracting a word from a long word value or storing the position of the mouse pointer. As you may know, Windows itself defines many constants and variables that you can use in your programs to help write programs faster. Using these previously defined constants and macros makes your programs more portable and more readable by other programmers. Besides the macros, global constants, and variables defined by Windows, Visual C++ adds its own set. In the following tables, you'll get a look at the most important of these globally available constants, macros, and variables.

Ten Categories of Macros and Globals

Because there are so many constants, macros, and globals, Visual C++ organizes its constants, macros, and globals into ten categories. Those categories are listed below. The following sections describe each of these categories and the symbols they define.

Application Information and Management Functions

Because a typical Visual C++ application contains only one application object but many other objects created from other MFC classes, you frequently need to get information about the application in different places in a program. Visual C++ defines a set of global functions that return this information to any class in a program. These functions, which are listed in Table 15.1, can be called from anywhere within an MFC program. For example, you frequently need to get a pointer to an application's main window. The following function call accomplishes that task.


CWnd* pWnd = AfxGetMainWnd();

Table 15.1  Application Information and Management

FunctionDescription
AfxBeginThread()Creates a new thread. (Please refer to Chapter 31, "Multitasking with Windows Threads," for more information on threads.)
AfxEndThread()Terminates a thread.
AfxGetApp()Gets the application's CWinApp pointer.
AfxGetAppName()Gets the application's name.
AfxGetInstanceHandle()Gets the application's instance handle.
AfxGetMainWnd()Gets a pointer to the application's main window.
AfxGetResourceHandle()Gets the application's resource handle.
AfxGetThreadGets a pointer to a CWinThread object.
AfxRegisterClass()Registers a window class in an MFC DLL.
AfxRegisterWndClass()Registers a Windows window class in an MFC application.
AfxSetResourceHandle()Sets the instance handle that determines where to load the application's default resources.
AfxSocketInit()Initializes Windows Sockets. (Please refer to Chapter 13, "Sockets, MAPI, and the Internet," for more information.)

ClassWizard Comment Delimiters

Visual C++ defines a number of delimiters that ClassWizard uses to keep track of what it's doing, as well as to locate specific areas of source code. Although you'll rarely, if ever, use these macros yourself, you will see them embedded in your AppWizard applications, so you might like to know exactly what they do. Table 15.2 fills you in.

Table 15.2  ClassWizard Delimiters

DelimiterDescription
AFX_DATAStarts and ends member variable declarations in header files that are associated with dialog data exchange.
AFX_DATA_INITIn a dialog class's constructor, starts and ends dialog data exchange variable initialization.
AFX_DATA_MAPIn a dialog class's DoDataExchange() function, starts and ends dialog data exchange function calls.
AFX_DISPStarts and ends OLE Automation declarations in header files.
AFX_DISP_MAPStarts and ends OLE Automation mapping in implementation files.
AFX_EVENTStarts and ends OLE event declarations in header files.
AFX_EVENT_MAPStarts and ends OLE events in implementation files.
AFX_FIELDStarts and ends member variable declarations in header files that are associated with database record field exchange.
AFX_FIELD_INITIn a record set class's constructor, starts and ends record field exchange member variable initialization.
AFX_FIELD_MAPIn a record set class's DoFieldExchange() function, starts and ends record field exchange function calls.
AFX_MSGStarts and ends ClassWizard entries in header files for classes that use message maps.
AFX_MSG_MAPStarts and ends message map entries.
AFX_VIRTUALStarts and ends virtual function overrides in header files.

Collection Class Helpers

Because certain types of data structures are so commonly used in programming, MFC defines collection classes that enable you to get these common data structures initialized quickly and manipulated easily. MFC includes collection classes for arrays, linked lists, and mapping tables. Each of these types of collections contains elements that represent the individual pieces of data that comprise the collection. In order to make it easier to access these elements, MFC defines a set of functions (created from templates; see Chapter 30, "Power-User C++ Features," for more information on templates), shown in Table 15.3, that you can override for a particular data type.

Table 15.3  Collection Class Helper Functions

FunctionDescription
CompareElements()Checks elements for equality.
ConstructElements()Constructs new elements (works similar to a class constructor).
DestructElements()Destroys elements (works similar to a class destructor).
DumpElements()Provides diagnostic output in text form.
HashKey()Calculates hashing keys.
SerializeElements()Saves or loads elements to or from an archive.

CString Formatting and Message-Box Display

If you've done much Visual C++ programming, you know that MFC features a special string class, called CString, that makes string handling under C++ less cumbersome. CString objects are used extensively throughout MFC programs. Even when dealing with strings in a resource's string table, CString objects can come in handy, as the following global functions, which replace format characters in string tables, show (see Table 15.4). There's also a global function for displaying a message box.

Table 15.4  CString Formatting and Message-Box Functions

FunctionDescription
AfxFormatString1()Replaces the format characters (i.e., %1) in a string resource with a given string.
AfxFormatString2()Replaces the format characters "%1" and "%2" in a string resource with the given strings.
AfxMessageBox()Displays a message box.

Data Types

The most commonly used constants are those that define a portable set of data types. You've seen tons of these constants, which are named using all uppercase letters, used in Windows programs. You'll recognize many of these from the Windows SDK. Others, are included only as part of Visual C++. You use these constants exactly as you would any other data type. For example, to declare a Boolean variable, you'd write something like this:


BOOL flag;

Table 15.5 lists the most commonly used data types defined by Visual C++ for Windows 95 and NT.

Table 15.5  Commonly Used Data Types

ConstantData Type
BOOLBoolean value.
BSTR 32-bit pointer to character data.
BYTE8-bit unsigned integer.
COLORREF32-bit color value.
DWORD32-bit unsigned integer.
LONG32-bit signed integer.
LPARAM32-bit window-procedure parameter.
LPCRECT32-bit constant RECT structure pointer.
LPCSTR32-bit string-constant pointer.
LPSTR32-bit string pointer.
LPVOID32-bit void pointer.
LRESULT32-bit window-procedure return value.
POSITIONThe position of an element in a collection.
UINT32-bit unsigned integer.
WNDPROC32-bit window-procedure pointer.
WORD16-bit unsigned integer.
WPARAM32-bit window-procedure parameter.

Using Diagnostic Services

Once you have your program written, you're far from done. Then comes the grueling task of testing, which means rolling up your sleeves, cranking up your debugger, and weeding out all the gotchas hiding in your code. Luckily, Visual C++ provides many macros, functions, and global variables that you can use to incorporate diagnostic abilities into your projects. Using these tools, you can do everything from printing output to a debugging window to checking the integrity of memory blocks. Table 15.6 lists these valuable diagnostic macros, functions, and global variables.

Table 15.6  Diagnostic Macros, Functions, and Global Variables

SymbolDescription
AfxCheckMemory()Verifies the integrity of allocated memory.
AfxDoForAllClasses()Calls a given iteration function for all classes that are derived from CObject and that incorporate run-time type checking.
AfxDoForAllObjects()Calls a given iteration function for all objects that were derived from CObject and that were allocated with the new operator.
AfxDumpA global CDumpContext object that enables a program to send information to the debugger window.
AfxDump()Dumps an object's state during a debugging session.
AfxEnableMemoryTracking()Toggles memory tracking.
AfxIsMemoryBlock()Checks that memory allocation was successful.
AfxIsValidAddress()Checks that a memory address range is valid for the program.
AfxIsValidString()Checks string pointer validity.
AfxMemDFA global variable that controls memory-allocation diagnostics. Can be set to allocMemDF, DelayFreeMemDF, or checkAlwaysMemDF.
AfxSetAllocHook()Sets a user-defined hook function that is called whenever memory allocation is performed.
AfxTraceEnabledA global variable that enables or disables TRACE output.
AfxTraceFlagsA global variable that enables the MFC reporting features.
ASSERTPrints a message and exits the program if the assert expression is false.
ASSERT_VALIDValidates an object by calling the object's AssertValid() function.
DEBUG_NEWUsed in place of the new operator in order to trace memory-leak problems.
TRACECreates formatted strings for debugging output.
TRACE0Same as TRACE but requires no arguments in the format string.
TRACE1Same as TRACE but requires one argument in the format string.
TRACE2Same as TRACE but requires two arguments in the format string.
TRACE3Same as TRACE but requires three arguments in the format string.
VERIFYLike ASSERT, but VERIFY evaluates the assert expression in both the Debug and Release versions of MFC. If the assertion fails, a message is printed and the program halted only in the Debug version.

Exception Processing

One of the newest elements of the C++ language is exceptions, which give a program greater control over how errors are handled. (Please refer to Chapter 30, "Power-User C++ Features," for more information on exceptions.) Visual C++ increases the value of exceptions by defining a set of macros and functions that you can use to better handle errors in your applications. These macros and functions are listed in Table 15.7.

Table 15.7  Exception Macros and Functions

SymbolDescription
AfxAbort()Terminates an application upon a fatal error.
AfxThrowArchiveException()Throws an archive exception.
AfxThrowDAOException()Throws a CDaoException.
AfxThrowDBException()Throws a CDBException.
AfxThrowFileException()Throws a file exception.
AfxThrowMemoryException()Throws a memory exception.
AfxThrowNotSupportedException() Throws a not-supported exception.
AfxThrowOleDispatchException() Throws an OLE automation exception.
AfxThrowOleException()Throws an OLE exception.
AfxThrowResourceException()Throws a resource-not-found exception.
AfxThrowUserException()Throws an end-user exception.
AND_CATCHBegins code that will catch specified exceptions not caught in the preceding TRY block.
AND_CATCH_ALLBegins code that will catch all exceptions not caught in the preceding TRY block.
CATCHBegins code for catching an exception.
CATCH_ALLBegins code for catching all exceptions.
END_CATCHEnds CATCH or AND_CATCH code blocks.
END_CATCH_ALLEnds CATCH_ALL code blocks.
THROWThrows a given exception.
THROW_LASTThrows the most recent exception to the next handler.
TRYStarts code that will accommodate exception handling.

Using Message-Map Macros

Windows is an event-driven operating system, which means that every Windows application must handle a flood of messages that flow between an application and the system. MFC does away with the clunky switch statements that early Windows programmers had to construct in order to handle messages and replaces those statements with a message map. A message map is nothing more than a table that matches a message with its message handler. (For more information on message maps, please refer to Chapter 5 "Messages and Commands.") In order to simplify the declaration and definition of these tables, Visual C++ defines a set of message-map macros. Many of these macros, which are listed in Table 15.8, will already be familiar to experienced MFC programmers.

Table 15.8  Message-Map Macros

MacroDescription
BEGIN_MESSAGE_MAPBegins a message-map definition.
DECLARE_MESSAGE_MAPStarts a message-map declaration.
END_MESSAGE_MAPEnds a message-map definition.
ON_COMMANDBegins a command-message message-map entry.
ON_COMMAND_RANGEBegins a command-message message-map entry that maps multiple messages to a single handler.
ON_CONTROLBegins a control-notification message-map entry.
ON_CONTROL_RANGEBegins a control-notification message-map entry that maps multiple control IDs to a single handler.
ON_MESSAGEBegins a user-message message-map entry.
ON_REGISTERED_MESSAGEBegins a registered user-message message-map entry.
ON_UPDATE_COMMAND_UIBegins a command-update message-map entry.
ON_UPDATE_COMMAND_UI_RANGEBegins a command-update message-map entry that maps multiple command-update messages to a single handler.

Run-Time Object Model Services

Frequently in your programs, you need access to information about classes at run-time. MFC supplies a macro for obtaining this type of information in a CRuntimeClass structure. In addition, the MFC application frameworks relies on a set of macros to declare and define run-time abilities (such as object serialization and dynamic object creation). If you've used AppWizard at all, you've seen these macros used in the generated source-code files. If you're an advanced MFC programmer, you may have even used these macros yourself. Table 15.9 lists the run-time macros and their descriptions.

Table 15.9  Run-Time Services Macros

MacroDescription
DECLARE_DYNAMICUsed in a class declaration to enable run-time class information access.
DECLARE_DYNCREATEUsed in a class declaration to allow the class (derived from CObject) to be created dynamically. Also, allows run-time class information access.
DECLARE_OLECREATEUsed in a class declaration to allow object creation with OLE automation.
DECLARE_SERIALUsed in a class declaration to allow object serialization, as well as run-time class information access.
IMPLEMENT_DYNAMICUsed in a class implementation to enable run-time class information access.
IMPLEMENT_DYNCREATEUsed in a class implementation to allow dynamic creation of the object and run-time information access.
IMPLEMENT_OLECREATEUsed in a class implementation to enable object creation with OLE.
IMPLEMENT_SERIALUsed in a class implementation to allow object serialization and run-time class information access.
RUNTIME_CLASSReturns a CRuntimeClass structure for the given class.

Standard Command and Window IDs

There are myriad standard messages that can be generated by a user of a Windows application. For example, whenever the user selects a menu command from a standard menu like File or Edit, the program sends a message. Each of these standard commands is represented by an ID. In order to relieve the programmer of having to define the dozens of IDs that are often used in a Windows application, Visual C++ defines these symbols in a file called AFXRES.H. Some of these IDs have obvious purposes (for example, ID_FILE_OPEN), but many others are used internally by MFC for everything from mapping standard Windows messages to their handlers to defining string-table IDs to assigning IDs to toolbar and status-bar styles. There are far too many of these identifiers to list here. However, if you're interested in seeing them, just load the AFXRES.H file from your Visual C++ installation folder.

From Here...

Thanks to the many constants, macros, and global functions and variables defined by Visual C++, common programming tasks are easy to perform in your applications. You should take the time to look over the tables given in this chapter in order to become more familiar with the tools Visual C++ has to offer. If you look up the listed functions, constants, macros, and global variables in your Visual C++ online documentation, you can find even more information about these valuable tools.

For more information on related topics, please consult the following chapters: