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.
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.
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();
Function | Description |
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. |
AfxGetThread | Gets 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.) |
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.
Delimiter | Description |
AFX_DATA | Starts and ends member variable declarations in header files that are associated with dialog data exchange. |
AFX_DATA_INIT | In a dialog class's constructor, starts and ends dialog data exchange variable initialization. |
AFX_DATA_MAP | In a dialog class's DoDataExchange() function, starts and ends dialog data exchange function calls. |
AFX_DISP | Starts and ends OLE Automation declarations in header files. |
AFX_DISP_MAP | Starts and ends OLE Automation mapping in implementation files. |
AFX_EVENT | Starts and ends OLE event declarations in header files. |
AFX_EVENT_MAP | Starts and ends OLE events in implementation files. |
AFX_FIELD | Starts and ends member variable declarations in header files that are associated with database record field exchange. |
AFX_FIELD_INIT | In a record set class's constructor, starts and ends record field exchange member variable initialization. |
AFX_FIELD_MAP | In a record set class's DoFieldExchange() function, starts and ends record field exchange function calls. |
AFX_MSG | Starts and ends ClassWizard entries in header files for classes that use message maps. |
AFX_MSG_MAP | Starts and ends message map entries. |
AFX_VIRTUAL | Starts and ends virtual function overrides in header files. |
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.
Function | Description |
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. |
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.
Function | Description |
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. |
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.
Constant | Data Type |
BOOL | Boolean value. |
BSTR | 32-bit pointer to character data. |
BYTE | 8-bit unsigned integer. |
COLORREF | 32-bit color value. |
DWORD | 32-bit unsigned integer. |
LONG | 32-bit signed integer. |
LPARAM | 32-bit window-procedure parameter. |
LPCRECT | 32-bit constant RECT structure pointer. |
LPCSTR | 32-bit string-constant pointer. |
LPSTR | 32-bit string pointer. |
LPVOID | 32-bit void pointer. |
LRESULT | 32-bit window-procedure return value. |
POSITION | The position of an element in a collection. |
UINT | 32-bit unsigned integer. |
WNDPROC | 32-bit window-procedure pointer. |
WORD | 16-bit unsigned integer. |
WPARAM | 32-bit window-procedure parameter. |
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.
Symbol | Description |
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. |
AfxDump | A 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. |
AfxMemDF | A 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. |
AfxTraceEnabled | A global variable that enables or disables TRACE output. |
AfxTraceFlags | A global variable that enables the MFC reporting features. |
ASSERT | Prints a message and exits the program if the assert expression is false. |
ASSERT_VALID | Validates an object by calling the object's AssertValid() function. |
DEBUG_NEW | Used in place of the new operator in order to trace memory-leak problems. |
TRACE | Creates formatted strings for debugging output. |
TRACE0 | Same as TRACE but requires no arguments in the format string. |
TRACE1 | Same as TRACE but requires one argument in the format string. |
TRACE2 | Same as TRACE but requires two arguments in the format string. |
TRACE3 | Same as TRACE but requires three arguments in the format string. |
VERIFY | Like 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. |
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.
Symbol | Description |
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_CATCH | Begins code that will catch specified exceptions not caught in the preceding TRY block. |
AND_CATCH_ALL | Begins code that will catch all exceptions not caught in the preceding TRY block. |
CATCH | Begins code for catching an exception. |
CATCH_ALL | Begins code for catching all exceptions. |
END_CATCH | Ends CATCH or AND_CATCH code blocks. |
END_CATCH_ALL | Ends CATCH_ALL code blocks. |
THROW | Throws a given exception. |
THROW_LAST | Throws the most recent exception to the next handler. |
TRY | Starts code that will accommodate exception handling. |
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.
Macro | Description |
BEGIN_MESSAGE_MAP | Begins a message-map definition. |
DECLARE_MESSAGE_MAP | Starts a message-map declaration. |
END_MESSAGE_MAP | Ends a message-map definition. |
ON_COMMAND | Begins a command-message message-map entry. |
ON_COMMAND_RANGE | Begins a command-message message-map entry that maps multiple messages to a single handler. |
ON_CONTROL | Begins a control-notification message-map entry. |
ON_CONTROL_RANGE | Begins a control-notification message-map entry that maps multiple control IDs to a single handler. |
ON_MESSAGE | Begins a user-message message-map entry. |
ON_REGISTERED_MESSAGE | Begins a registered user-message message-map entry. |
ON_UPDATE_COMMAND_UI | Begins a command-update message-map entry. |
ON_UPDATE_COMMAND_UI_RANGE | Begins a command-update message-map entry that maps multiple command-update messages to a single handler. |
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.
Macro | Description |
DECLARE_DYNAMIC | Used in a class declaration to enable run-time class information access. |
DECLARE_DYNCREATE | Used in a class declaration to allow the class (derived from CObject) to be created dynamically. Also, allows run-time class information access. |
DECLARE_OLECREATE | Used in a class declaration to allow object creation with OLE automation. |
DECLARE_SERIAL | Used in a class declaration to allow object serialization, as well as run-time class information access. |
IMPLEMENT_DYNAMIC | Used in a class implementation to enable run-time class information access. |
IMPLEMENT_DYNCREATE | Used in a class implementation to allow dynamic creation of the object and run-time information access. |
IMPLEMENT_OLECREATE | Used in a class implementation to enable object creation with OLE. |
IMPLEMENT_SERIAL | Used in a class implementation to allow object serialization and run-time class information access. |
RUNTIME_CLASS | Returns a CRuntimeClass structure for the given class. |
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.
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: