0% found this document useful (0 votes)
171 views

What Is A Carchive Object: Visual C++ Material

The document discusses several key classes in Visual C++ and MFC including CArchive, CWinApp, CFile, CException, CDialog, CEdit, and CListBox. CArchive provides serialization of objects to files. CWinApp is the main application class and handles initialization and termination. CFile represents disk files that can be read from and written to. CException is the base class for exceptions. CDialog is the base class for dialog boxes. CEdit represents an edit control. CListBox represents a list box control.

Uploaded by

rajeshmanam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
171 views

What Is A Carchive Object: Visual C++ Material

The document discusses several key classes in Visual C++ and MFC including CArchive, CWinApp, CFile, CException, CDialog, CEdit, and CListBox. CArchive provides serialization of objects to files. CWinApp is the main application class and handles initialization and termination. CFile represents disk files that can be read from and written to. CException is the base class for exceptions. CDialog is the base class for dialog boxes. CEdit represents an edit control. CListBox represents a list box control.

Uploaded by

rajeshmanam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Visual C++ Material

What Is a CArchive Object


A CArchive object provides a type-safe buffering mechanism for writing or reading serializable
objects to or from a CFile object. Usually the CFile object represents a disk file; however, it can also
be a memory file (CSharedFile object), perhaps representing the Clipboard.
A given CArchive object either stores (writes, serializes) data or loads (reads, deserializes) data, but
never both. The life of a CArchive object is limited to one pass through writing objects to a file or
reading objects from a file. Thus, two successively created CArchive objects are required to serialize
data to a file and then deserialize it back from the file.
When an archive stores objects to a file, the archive attaches the CRuntimeClass name to the objects.
Then, when another archive loads objects from a file to memory, the CObject-derived objects are
dynamically reconstructed based on the CRuntimeClass of the objects. A given object may be
referenced more than once as it is written to the file by the storing archive. The loading archive,
however, will reconstruct the object only once.

CWinApp: The Application Class


The main application class in MFC encapsulates the initialization, running, and termination of an
application for Windows. An application built on the framework must have one (and only one) object
of a class derived from . This object is constructed before windows are created. (CWinApp is derived
from CWinThread, which represents the main thread of execution for your application, which might
have one or more threads. In recent versions of MFC, the InitInstance, Run, ExitInstance, and
OnIdle member functions are actually in class CWinThread. These functions are discussed here as if
they were CWinApp members instead, since the discussion concerns the object's role as application
object rather than as primary thread.)

Like any program for Windows, your framework application has a WinMain function. In a
framework application, however, you don't write WinMain. It is supplied by the class library and is
called when the application starts up. WinMain performs standard services such as registering
window classes. Then it calls member functions of the application object to initialize and run the
application. (You can customize WinMain by overriding the CWinApp member functions that
WinMain calls.)
Teams Global Village Academy

Page 1

Visual C++ Material


To initialize the application, WinMain calls your application object's InitApplication and InitInstance
member functions. To run the application's message loop, WinMain calls the Run member function.
On termination, WinMain calls the application object's ExitInstance member function. The figure
Sequence of Execution below shows the sequence of execution in a framework application.

CWinApp and AppWizard


When it creates a skeleton application, AppWizard declares an application class derived from .
AppWizard also generates an implementation file that contains the following items:

A message map for the application class

An empty class constructor

A variable that declares the one and only object of the class

A standard implementation of your InitInstance member function

The application class is placed in the project header and main source files. The names of the class and
files created are based on the project name you supply in AppWizard. The easiest way to view the
code for these classes is through the Class View in the Project Workspace window.
The standard implementations and message map supplied are adequate for many purposes, but you
can modify them as needed. The most interesting of these implementations is the InitInstance member
function. Typically you will add code to the skeletal implementation of InitInstance.

CFile

CFile is the base class for Microsoft Foundation file classes. It directly provides unbuffered, binary
disk input/output services, and it indirectly supports text files and memory files through its derived
classes. CFile works in conjunction with the CArchive class to support serialization of Microsoft
Foundation Class objects.
The hierarchical relationship between this class and its derived classes allows your program to operate
on all file objects through the polymorphic CFile interface. A memory file, for example, behaves like
a disk file.
Use CFile and its derived classes for general-purpose disk I/O. Use ofstream or other Microsoft
iostream classes for formatted text sent to a disk file.
Normally, a disk file is opened automatically on CFile construction and closed on destruction. Static
member functions permit you to interrogate a files status without opening the file.

Teams Global Village Academy

Page 2

Visual C++ Material


CException

CException is the base class for all exceptions in the Microsoft Foundation Class Library. The
derived classes and their descriptions are listed below:
CMemoryException

Out-of-memory exception

CNotSupportedException

Request for an unsupported operation

CArchiveException

Archive-specific exception

CFileException

File-specific exception

CResourceException

Windows resource not found or not createable

COleException

OLE exception

CDBException

Database exception (that is, exception conditions arising for


MFC database classes based on Open Database Connectivity)

COleDispatchException

OLE dispatch (automation) exception

CUserException

Exception that indicates that a resource could not be found

CDaoException

Data access object exception (that is, exception conditions


arising for DAO classes)

CInternetException

Internet exception (that is, exception conditions arising for


Internet classes).

CDialog

The CDialog class is the base class used for displaying dialog boxes on the screen. Dialog boxes are
of two types: modal and modeless. A modal dialog box must be closed by the user before the
application continues. A modeless dialog box allows the user to display the dialog box and return to
another task without canceling or removing the dialog box.
Teams Global Village Academy

Page 3

Visual C++ Material


A CDialog object is a combination of a dialog template and a CDialog-derived class. Use the dialog
editor to create the dialog template and store it in a resource, then use ClassWizard to create a class
derived from CDialog.
A dialog box, like any other window, receives messages from Windows. In a dialog box, you are
particularly interested in handling notification messages from the dialog boxs controls since that is
how the user interacts with your dialog box. ClassWizard browses through the potential messages
generated by each control in your dialog box, and you can select which messages you wish to handle.
ClassWizard then adds the appropriate message-map entries and message-handler member functions
to the new class for you. You only need to write application-specific code in the handler member
functions.

CEdit

The CEdit class provides the functionality of a Windows edit control. An edit control is a rectangular
child window in which the user can enter text.
You can create an edit control either from a dialog template or directly in your code. In both cases,
first call the constructor CEdit to construct the CEdit object, then call the Create member function to
create the Windows edit control and attach it to the CEdit object.
Construction can be a one-step process in a class derived from CEdit. Write a constructor for the
derived class and call Create from within the constructor.
CEdit inherits significant functionality from CWnd. To set and retrieve text from a CEdit object, use
the CWnd member functions SetWindowText and GetWindowText, which set or get the entire
contents of an edit control, even if it is a multiline control. Also, if an edit control is multiline, get
and set part of the controls text by calling the CEdit member functions GetLine, SetSel, GetSel, and
ReplaceSel.
If you want to handle Windows notification messages sent by an edit control to its parent (usually a
class derived from CDialog), add a message-map entry and message-handler member function to the
parent class for each message.
Following is a list of potential message-map entries and a description of the cases in which they
would be sent to the parent:

ON_EN_CHANGE The user has taken an action that may have altered text in an edit
control. Unlike the EN_UPDATE notification message, this notification message is sent after
Windows updates the display.

ON_EN_ERRSPACE The edit control cannot allocate enough memory to meet a specific
request.

ON_EN_HSCROLL The user clicks an edit controls horizontal scroll bar. The parent
window is notified before the screen is updated.

Teams Global Village Academy

Page 4

Visual C++ Material

ON_EN_KILLFOCUS The edit control loses the input focus.

ON_EN_MAXTEXT The current insertion has exceeded the specified number of characters
for the edit control and has been truncated. Also sent when an edit control does not have the
ES_AUTOHSCROLL style and the number of characters to be inserted would exceed the
width of the edit control. Also sent when an edit control does not have the
ES_AUTOVSCROLL style and the total number of lines resulting from a text insertion
would exceed the height of the edit control.

ON_EN_SETFOCUS Sent when an edit control receives the input focus.

ON_EN_UPDATE The edit control is about to display altered text. Sent after the control
has formatted the text but before it screens the text so that the window size can be altered, if
necessary.

ON_EN_VSCROLL The user clicks an edit controls vertical scroll bar. The parent
window is notified before the screen is updated.

If you create a CEdit object within a dialog box, the CEdit object is automatically destroyed when
the user closes the dialog box.
If you create a CEdit object from a dialog resource using the dialog editor, the CEdit object is
automatically destroyed when the user closes the dialog box.
CListBox

The CListBox class provides the functionality of a Windows list box. A list box displays a list of
items, such as filenames, that the user can view and select.
In a single-selection list box, the user can select only one item. In a multiple-selection list box, a range
of items can be selected. When the user selects an item, it is highlighted and the list box sends a
notification message to the parent window.
You can create a list box either from a dialog template or directly in your code. To create it directly,
construct the CListBox object, then call the Create member function to create the Windows list-box
control and attach it to the CListBox object. To use a list box in a dialog template, declare a list-box
variable in your dialog box class, then use DDX_Control in your dialog box class's
DoDataExchange function to connect the member variable to the control. (ClassWizard does this for
you automatically when you add a control variable to your dialog box class.)
Following is a list of potential message-map entries and a description of the cases in which they
would be sent to the parent:

ON_LBN_DBLCLK The user double-clicks a string in a list box. Only a list box that has
the LBS_NOTIFY style will send this notification message.

Teams Global Village Academy

Page 5

Visual C++ Material

ON_LBN_ERRSPACE The list box cannot allocate enough memory to meet the request.

ON_LBN_KILLFOCUS The list box is losing the input focus.

ON_LBN_SELCANCEL The current list-box selection is canceled. This message is only


sent when a list box has the LBS_NOTIFY style.

ON_LBN_SELCHANGE The selection in the list box is about to change. This notification
is not sent if the selection is changed by the CListBox::SetCurSel member function. This
notification applies only to a list box that has the LBS_NOTIFY style. The
LBN_SELCHANGE notification message is sent for a multiple-selection list box whenever
the user presses an arrow key, even if the selection does not change.

ON_LBN_SETFOCUS The list box is receiving the input focus.

ON_WM_CHARTOITEM An owner-draw list box that has no strings receives a


WM_CHAR message.

ON_WM_VKEYTOITEM A list box with the LBS_WANTKEYBOARDINPUT style


receives a WM_KEYDOWN message.

If you create a CListBox object within a dialog box (through a dialog resource), the CListBox object
is automatically destroyed when the user closes the dialog box.

Working with Resources


If you have been developing Windows applications for a while, you are probably familiar with
resource scripts. These are files that define all of the resources used by your application, including
dialog boxes, icons, and menus. In the old days, you often had to move back and forth between your
source editor and your resource editor, the C compiler, and the resource compiler. Developer Studio
makes this much simpler by providing a visual editor for your resources that is fully integrated with
the rest of Developer Studio.
The Resource View
In programming for Windows, you will use several different types of resources. Most of these
correspond directly to graphics objects such as bitmaps, cursors, and icons, as well as more
complicated types such as menus, toolbars, and dialog box templates. In addition, you will have a
string table and version resource, as well as any custom resources you might define.
In the bad old days, all resources were defined in a text resource script (.rc) file. You then had to
compile the .rc file with a separate resource compiler and explicitly link your resources to your
executable. Visual C++ 6.0 still uses the .rc file, but you will most likely never have to edit it directly.
Developer studio allows you to edit your resources graphically, and will automatically take the
necessary steps to compile your resource script and link it to your application.
The Resource editors share techniques and interfaces to create and modify application resources
quickly and easily. You can use the Resource editors to create new resources, modify existing
resources, copy existing resources, and delete old resources. The Resource editors are functionally
consistent for ease of use.
You can edit all of the Microsoft Windows resources that your application uses. These resources
include:
Teams Global Village Academy

Page 6

Visual C++ Material

Accelerator tables

Binary data information

Bitmaps, icons, and other image files

Cursors

Dialog boxes

HTML pages

Menus

String tables

Toolbar resources

Version information

Menus: Overview
MFC supplies two elements to help you work with menus:

Class CMenu for manipulating your programs menus at run time. Use the documentation for
CMenu and the sample to learn how to use CMenu effectively.

A mechanism for updating menus and toolbar buttons: enabling or disabling them on the fly
to suit current program conditions.

Menus allow you to arrange commands in a logical, easy-to-find fashion. With the Menu editor, you
can create and edit menus by working directly with a menu bar that closely resembles the one in your
finished application.
With the Menu editor, you can:

Create standard menus and commands.

Move menus or commands from one place to another.

Edit the properties of several menu items at the same time.

To create a menu on the menu bar


1. Select the new-item box (an empty rectangle) on the menu bar. Or move the new-item box to
a blank spot with the RIGHT ARROW and LEFT ARROW keys.
2. Type the name of the menu.
When you start typing, focus automatically shifts to the Menu Item property page, and the
text you type appears both in the Caption box and in the Menu editor window.

Teams Global Village Academy

Page 7

Visual C++ Material


You can define a mnemonic key that allows the user to select the menu with the keyboard.
Type an ampersand (&) in front of a letter to specify it as the mnemonic. Make sure all the
mnemonics on a menu bar are unique.
Once you have given the menu a name on the menu bar, the new-item box shifts to the right,
and another new-item box opens below for adding menu items.
Note To create a single-item menu on the menu bar, clear the Pop-up check box on the
Menu Item property page.
To select a menu and display its menu items

Click the menu caption on the menu bar or the parent item of the cascading menu. Then click
the menu item you want.

To select one or more menu items


1. Click the menu or cascading menu you want.
2. Click to select a menu item, or press the SHIFT key while clicking to select multiple menu
items. Hold down the SHIFT key and click a selected menu item to deselect it.
or
With the pointer outside the menu, drag to draw a selection box around the menu items you
want to select.

Accelerator Editor
An accelerator table is a Windows resource that contains a list of accelerator keys (also known as
shortcut keys) and the command identifiers that are associated with them. A program can have more
than one accelerator table.
Normally, accelerators are used as keyboard shortcuts for program commands that are also available
on a menu or toolbar. However, you can use the accelerator table to define key combinations for
commands that dont have a user-interface object associated with them.
With the Accelerator editor, you can:

Add, delete, change, and browse the accelerator key assignments in your project.

View and change the resource identifier associated with each entry in the accelerator table.
The identifier is used to reference each accelerator table entry in program code.

Associate an accelerator key with a menu item.

Find one or more accelerator keys in the accelerator table, and use regular expressions with
the Find command to locate an accelerator key that matches a pattern.

Select multiple accelerator keys and change their properties at one time.

To add an entry to an accelerator table


Teams Global Village Academy

Page 8

Visual C++ Material


1. Select the new-item box at the end of the list.
2. Type the key you want to use as an accelerator.
The Accel Properties page appears, with the focus in the Key box.
3. Select an ID from the drop-down list in the ID box.
4. Change the modifier and type, if necessary.
The modifier specifies whether the key you chose is a combination formed with CTRL, ALT,
or SHIFT. The type indicates whether the key is an ASCII or a virtual key value.
5. Press ENTER.

Dialog Editor
Use the Dialog editor to create or edit dialog boxes. You can store a dialog box as a template so you
can reuse it. And you can easily switch between designing the dialog box and editing the code that
implements it.
With the Dialog editor, you can:

Add, arrange, or edit controls.

Change the tab order.

Use guides in the dialog box layout.

Test a dialog box.

Create Windows message handlers for the dialog box or its controls.

Jump to the code that implements the dialog box and its controls.

You add controls to a dialog box by using the Controls toolbar, which enables you to choose the
control you want and to drag it to the dialog box. When displayed, the toolbar stays positioned above
other open windows in your workspace. You can add ActiveX controls to the Controls toolbar. You
can also add ActiveX controls, which may not be on the toolbar, directly to a dialog box by using the
Insert ActiveX Controls command from the Dialog editor shortcut menu.
The fastest way to add controls to a dialog box, reposition existing controls, or move controls from
one dialog box to another is to use the drag-and-drop method. The controls position is outlined in a
dotted line until it is dropped into the dialog box. When you add a control to a dialog box with the
drag-and-drop method, the control is given a standard height appropriate to that type of control.
When you add a control to a dialog box or reposition it, its final placement may be determined by
guides or margins, or whether you have the layout grid turned on.

Teams Global Village Academy

Page 9

Visual C++ Material


Once you have added a control to the dialog box, you can change properties such as its caption by
using its property page. You can select multiple controls and change their properties all at once.

Version Information Editor


Version information consists of company and product identification, a product release number, and
copyright and trademark notification. The Version Information editor is a tool for creating and
maintaining this data. Although the version information resource is not required by an application, it
is a useful place to collect this information that identifies the application.
A single version information resource can contain multiple string blocks, each representing a different
language or character set. All you need to do is define the character sets and languages that are
specific to your product.
With the Version Information editor, you can add or delete string blocks, search for values, and
modify individual string values.

Bitmaps
Without graphics images, Microsoft Windows-based applications would be pretty dull. Some
applications depend on images for their usefulness, but any application can be spruced up with the
addition of decorative clip art from a variety of sources. Windows bitmaps are arrays of bits mapped
to display pixels. That might sound simple, but you have to learn a lot about bitmaps before you can
use them to create professional applications for Windows. This module starts with the "old" way of
programming bitmaps, creating the device-dependent GDI bitmaps that work with a memory device
context. You need to know these techniques because many programmers are still using them and
you'll also need to use them on occasion.
Next you'll graduate to the modern way of programming bitmaps, creating device-independent
bitmaps (DIBs). If you use DIBs, you'll have an easier time with colors and with the printer. In some
cases you'll get better performance. The Win32 function CreateDIBSection() gives you the benefits of
DIBs combined with all the features of GDI bitmaps. Finally, you'll learn how to use the MFC
CBitmapButton class to put bitmaps on pushbuttons. Using CBitmapButton to put bitmaps on
pushbuttons has nothing to do with DIBs, but it's a useful technique that would be difficult to master
without an example.
Loading a GDI Bitmap from a Resource
The easiest way to use a bitmap is to load it from a resource. If you look in ResourceView in the
Workspace window, you'll find a list of the project's bitmap resources. If you select a bitmap and
examine its properties, you'll see a filename as shown below.

Teams Global Village Academy

Page 10

Visual C++ Material


Messages
Windows defines hundreds of different message types. Most messages have names that begin with the
letters "WM_", as in WM_CREATE and WM_PAINT. These messages can be classified in various
ways, but for the moment classification is not nearly as important as realizing the critical role
messages play in the operation of an application. The following table shows 10 of the most common
messages. A window receives a WM_PAINT message, for example, when its interior needs
repainting. One way to characterize a Windows program is to think of it as a collection of message
handlers. To a large extent, it is a program's unique way of responding to messages that gives it its
personality.
Common Windows Messages
Message
WM_CHAR

Sent When
A character is input from the keyboard.
The user selects an item from a menu, or a
WM_COMMAND
control sends a notification to its parent.
WM_CREATE
A window is created.
WM_DESTROY
A window is destroyed.
WM_LBUTTONDOWN The left mouse button is pressed.
WM_LBUTTONUP
The left mouse button is released.
WM_MOUSEMOVE
The mouse pointer is moved.
WM_PAINT
A window needs repainting.
WM_QUIT
The application is about to terminate.
WM_SIZE
A window is resized.
Table 1: Windows messages example.
A message manifests itself in the form of a call to a window's window procedure. Bundled with the
call are four input parameters:
1. The handle of the window to which the message is directed,
2. A message ID, and
3. Two 32-bit parameters known as wParam and lParam.
The window handle is a 32-bit value that uniquely identifies a window. Internally, the value
references a data structure in which Windows stores relevant information about the window such as
its size, style, and location on the screen. The message ID is a numeric value that identifies the
message type: WM_CREATE, WM_PAINT, and so on. wParam and lParam contain information
specific to the message type. When a WM_LBUTTONDOWN message arrives, for example, wParam
holds a series of bit flags identifying the state of the Ctrl and Shift keys and of the mouse buttons.
lParam holds two 16-bit values identifying the location of the mouse pointer when the click occurred.
Together, these parameters provide the window procedure with all the information it needs to process
the WM_LBUTTONDOWN message.
A large portion of programming for the Windows environment involves message handling. Each time
an event such as a keystroke or mouse click occurs, a message is sent to the application, which must
then handle the event. The Microsoft Foundation Class Library offers a programming model
optimized for message-based programming. In this model, "message maps" are used to designate
which functions will handle various messages for a particular class. Message maps contain one or
more macros that specify which messages will be handled by which functions. For example, a
message map containing an ON_COMMAND macro might look something like this:
BEGIN_MESSAGE_MAP(CMyDoc, CDocument)
ON_COMMAND(ID_MYCMD, OnMyCommand)
Teams Global Village Academy

Page 11

Visual C++ Material


// ... More entries to handle additional commands
END_MESSAGE_MAP( )
The ON_COMMAND macro is used to handle command messages generated by menus, buttons, and
accelerator keys. Macros are available to map the following:
Windows Messages
Control notifications.
User-defined messages.
Command Messages
Registered user-defined messages.
User-interface update messages.
Ranges of Messages
Commands.
Update handler messages.
Control notifications.
Although message-map macros are important, you generally won't have to use them directly. This is
because the ClassWizard window automatically creates message-map entries in your source files
when you use it to associate message-handling functions with messages. Any time you want to edit or
add a message-map entry, you can use the ClassWizard. The ClassWizard does not support messagemap ranges. You must write these message-map entries yourself.
Message Categories Details
There are three main categories of messages that you will write in Windows programming later:
1. Windows messages
This includes primarily those messages beginning with the WM_ prefix, except for
WM_COMMAND. Windows messages are handled by windows and views. These messages
often have parameters that are used in determining how to handle the message.
2. Control notifications
This includes WM_COMMAND notification messages from controls (buttons, list boxes,
scroll bars etc.) and other child windows to their parent windows. For example, an edit
control sends its parent a WM_COMMAND message containing the EN_CHANGE controlnotification code when the user has taken an action that may have altered text in the edit
control. The window's handler for the message responds to the notification message in some
appropriate way, such as retrieving the text in the control. The framework routes controlnotification messages like other WM_ messages. One exception, however, is the
BN_CLICKED control-notification message sent by buttons when the user clicks them. This
message is treated specially as a command message and routed like other commands.
3. Command messages
This includes WM_COMMAND notification messages from user-interface objects: menus,
toolbar buttons, and accelerator keys. The framework processes commands differently from
other messages, and they can be handled by more kinds of objects.
Windows Messages and Control-Notification Messages
Messages in categories 1 and 2
Windows messages and control notifications are handled by windows: objects of classes derived from
class CWnd. This includes CFrameWnd, CMDIFrameWnd, CMDIChildWnd, CView, CDialog, and
your own classes derived from these base classes. Such objects encapsulate an HWND, a handle to a
Windows window.
Teams Global Village Academy

Page 12

Visual C++ Material


Messages in category 3 commands
Can be handled by a wider variety of objects: documents, document templates, and the application
object itself in addition to windows and views. When a command directly affects some particular
object, it makes sense to have that object handle the command. For example, the Open command on
the File menu is logically associated with the application: the application opens a specified document
upon receiving the command. So the handler for the Open command is a member function of the
application class.
Message Handling and Mapping
In traditional programs for Windows, Windows messages are handled in a large switch statement in a
window procedure. MFC instead uses message maps to map direct messages to distinct class member
functions. Message maps are more efficient than virtual functions for this purpose, and they allow
messages to be handled by the most appropriate C++ object such as application, document, view, and
so on. You can map a single message or a range of messages, command IDs, or control IDs.
WM_COMMAND messages - usually generated by menus, toolbar buttons, or accelerators, also use
the message-map mechanism. MFC defines a standard routing of command messages among the
application, frame window, view, and Active documents in your program. You can override this
routing if you need to. Message maps also supply a way to update user-interface objects (such as
menus and toolbar buttons), enabling or disabling them to suit the current context.

Creating Your Own Message Maps


When you create a class with AppWizard or ClassWizard, Visual C++ will produce the code to create
a message map for your class. If you create your own CCmdTarget- derived class outside of
ClassWizard, you need to create the message map yourself. You should start by adding the following
line to the end of your class declaration:
DECLARE_MESSAGE_MAP()
This macro is defined in AFXWIN.H in the \DevStudio\VC\mfc\include directory. It declares the
array that will hold your message map entries and some pointers used to find the message map of the
base class. You should be aware, though, that the structures for your class's message map are defined
static const. This means that you can have only one message map for all objects of your class, not a
different map for each object. This also means that you cannot change a class's message map at
runtime, at least not with methods that are discussed here. (It can be done with overrides of
PreTranslateMessage() or the functions hidden in the message map itself.)

Next, you add a message map to your class implementation. To see how this is done, let's take a look
at the message map implementation created for the CHiMomApp class in HiMom.cpp:

// CHiMomApp
BEGIN_MESSAGE_MAP(CHiMomApp, CWinApp)
//{{AFX_MSG_MAP(CHiMomApp)
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
Teams Global Village Academy

Page 13

Visual C++ Material


//}}AFX_MSG_MAP
// Standard file based document commands
ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
// Standard print setup command
ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()
As you can see in this example, message maps are created by a set of macros, beginning with
BEGIN_MESSAGE_MAP() and ending with END_MESSAGE_MAP(). To start the definition of
your message map, use the BEGIN_MESSAGE_MAP() macro, which takes the name of your class
and the name of its base class as parameters.
The BEGIN_MESSAGE_MAP() macro (defined in AFXWIN.H) actually defines the
_messageEntries array, leaving the initializer list open, to be filled by additional macros. If you forget
to include the END_MESSAGE_MAP() macro, which closes the initializer list, the compiler will
become quite lost, so make sure you end your message map with END_MESSAGE_MAP().
Populating the Message Map
In the previous example, you will see a DO NOT EDIT message from ClassWizard. It is a good idea
to avoid editing these sections if you don't have to, but you can make changes here. However, you
should be aware that changes to these blocks have the potential to confuse ClassWizard so that you
cannot edit your class or must regenerate the .clw file, or ClassWizard may just overwrite your new
changes. If you make changes to these blocks yourself, try to model your code after other
ClassWizard-generated code and check the function of ClassWizard right after making your changes.
That said, you will be populating your message map by using several different macros for different
types of messages, including message ranges.

Visual C++ Support for Document/View


MFC and AppWizard use the Document/View architecture to organize programs written for
Windows. Document/View separates the program into four main classes:

A document class derived from CDocument

A view class derived from CView

A frame class derived from CFrameWnd

An application class derived from CWinApp

Each of these classes has a specific role to play in an MFC Document/View application. The
document class is responsible for the program's data. The view class handles interaction between the
document and the user. The frame class contains the view and other user interface elements, such as
the menu and toolbars. The application class is responsible for actually starting the program and
handling some general-purpose interaction with Windows. Figure 9.1 shows the four main parts of a
Document/View program.

Teams Global Village Academy

Page 14

Visual C++ Material

Although the name "Document/View" might seem to limit you to only word-processing applications,
the architecture can be used in a wide variety of program types. There is no limitation as to the data
managed by CDocument; it can be a word processing file, a spreadsheet, or a server at the other end
of a network connection providing information to your program. Likewise, there are many types of
views. A view can be a simple window, as used in the simple SDI applications presented so far, or it
can be derived from CFormView, with all the capabilities of a dialog box.
SDI and MDI Applications
There are two basic types of Document/View programs:

SDI, or Single Document Interface

MDI, or Multiple Document Interface

An SDI program supports a single type of document and almost always supports only a single view.
Only one document can be open at a time. An SDI application focuses on a particular task and usually
is fairly straightforward.
Several different types of documents can be used in an MDI program, with each document having one
or more views. Several documents can be open at a time, and the open document often uses a
customized toolbar and menus that fit the needs of that particular document.
Why Use Document/View?
The first reason to use Document/View is that it provides a large amount of application code for free.
You should always try to write as little new source code as possible, and that means using MFC
classes and letting AppWizard and ClassWizard do a lot of the work for you. A large amount of the
code that is written for you in the form of MFC classes and AppWizard code uses the Document/View
architecture.
The Document/View architecture defines several main categories for classes used in a Windows
program. Document/View provides a flexible framework that you can use to create almost any type of
Windows program. One of the big advantages of the Document/View architecture is that it divides the

Teams Global Village Academy

Page 15

Visual C++ Material


work in a Windows program into well-defined categories. Most classes fall into one of the four main
class categories:

Controls and other user-interface elements related to a specific view

Data and data-handling classes, which belong to a document

Work that involves handling the toolbar, status bar, and menus, usually belonging to the
frame class

Interaction between the application and Windows occurring in the class derived from
CWinApp

Dividing work done by your program helps you manage the design of your program more effectively.
Extending programs that use the Document/View architecture is fairly simple because the four main
Document/View classes communicate with each other through well-defined interfaces. For example,
to change an SDI program to an MDI program, you must write little new code. Changing the user
interface for a Document/View program impacts only the view class or classes; no changes are needed
for the document, frame, or application classes.
Using AppWizard
Use AppWizard to create SDI and MDI applications. In earlier chapters, you use AppWizard to create
the SDI programs used as examples. Although doing so is more complicated, you can use AppWizard
to create an MDI application almost as easily as an SDI.
The basic difference between an SDI application and an MDI application is that an MDI application
must manage multiple documents and, usually, multiple views. The SDI application uses only a single
document, and normally only a single view.
Both SDI and MDI applications use an object called a document template to create a relationship
between a view, a document, and a frame class, as well as an identifier used for the program's menu,
icon, and other resources. You use the CSingleDocTemplate class for SDI applications and the
CMultiDocTemplate class for MDI applications. These two classes share a common base class,
CDocTemplate. Listing 9.1 is an example of a document template used for an SDI program.
Program Examples 1
Let go straight to the program example using MFC. This is a Single Document Interface (SDI)
"Hello, world!" classic example. The application has only one window, an object of a class derived
from CFrameWnd. All drawing occurs inside the frame window and all messages are handled there.
This just a warm up session and we are using AppWizard that can automate most of our task in
building Windows application. Follow the steps one-by-one.
Launch your Visual C++, click the File menu and click the New sub menu. Click the Projects tab
for the AppWizard as shown below. Select the MFC AppWizard (exe), type your project name and
set the project location as needed. Leave other setting as default and click the OK button.

Teams Global Village Academy

Page 16

Visual C++ Material

Figure 19: AppWizard dialog.

The wizard has 6 steps and you can exit at any step. Select the Single document radio button and
uncheck the Document/View architecture support then click Next button.

Figure 20: Visual C++ AppWizard step 1 of 6.

Teams Global Village Academy

Page 17

Visual C++ Material


Select the None radio button for database support. Click the Next button. We are going to create the
simplest project.

Figure 21: Visual C++ AppWizard step 2 of 6.


Uncheck the ActiveX Controls. Just to make our code simpler.

Figure 22: Visual C++ AppWizard step 3 of 6.


Accept the defaults and click the Next button.

Teams Global Village Academy

Page 18

Visual C++ Material

Figure: Visual C++ AppWizard step 4 of 6.


Accept the defaults and click Next button.

Figure: Visual C++ AppWizard step 5 of 6.

Teams Global Village Academy

Page 19

Visual C++ Material


The following are the classes that will be generated (also the related files created) for our project.
Click the Next button.

Figure: Visual C++ AppWizard step 6 of 6.


Finally the summary of the project settings. Click the OK button.

Figure: Visual C++ AppWizard project summary.


Expand all folders in the FileView and double click the ChildView.cpp. FileView displays all the
project files that can be edited, logically. Physically, there are more projects files.

Teams Global Village Academy

Page 20

Visual C++ Material

Visual C++ FileView.


Add code to paint in the dialog. Add the following code to the CChildView::OnPaint function in the
ChildView.cpp source code file:
void CChildView::OnPaint()
{
CPaintDC dc(this); // device context for painting
dc.TextOut(0, 0, "Hello, world!");
// Do not call CWnd::OnPaint() for painting messages
}

Compile and run. You now have a complete SDI application that has no dependencies on the
document-view architecture.

Teams Global Village Academy

Page 21

You might also like