Sams Teach Yourself MFC in 24 Hours


Sams Teach Yourself MFC in 24 Hours provides an understanding of the fundamentals of MFC. Twenty four sessions of one hour or less show you how to create and cutomize user interfaces, develop complete applications for all versions of Windows, and organize and work with data. This straightforward, step-by-step approach also covers drawing graphics, managing and accessing databases, implementing printing, and creating DLLs and Custom Controls.
Read ...
See more details below
Available through our Marketplace sellers.
Other sellers (Paperback)
  • All (11) from $1.99   
  • Used (11) from $1.99   
Sort by
Page 1 of 2
Showing 1 – 10 of 11 (2 pages)
Note: Marketplace items are not eligible for any coupons and promotions
Seller since 2007

Feedback rating:



New — never opened or used in original packaging.

Like New — packaging may have been opened. A "Like New" item is suitable to give as a gift.

Very Good — may have minor signs of wear on packaging but item works perfectly and has no damage.

Good — item is in good condition but packaging may have signs of shelf wear/aging or torn packaging. All specific defects should be noted in the Comments section associated with each item.

Acceptable — item is in working order but may show signs of wear such as scratches or torn packaging. All specific defects should be noted in the Comments section associated with each item.

Used — An item that has been opened and may show signs of wear. All specific defects should be noted in the Comments section associated with each item.

Refurbished — A used item that has been renewed or updated and verified to be in proper working condition. Not necessarily completed by the original manufacturer.

Millions of satisfied customers and climbing. Thriftbooks is the name you can trust, guaranteed. Spend Less. Read More.

Ships from: Auburn, WA

Usually ships in 1-2 business days

  • Canadian
  • International
  • Standard, 48 States
  • Standard (AK, HI)
  • Express, 48 States
  • Express (AK, HI)
Seller since 2010

Feedback rating:


Condition: Good
This book has a light amount of wear to the pages, cover and binding. Blue Cloud Books ??? Hot deals from the land of the sun.

Ships from: Phoenix, AZ

Usually ships in 1-2 business days

  • Canadian
  • International
  • Standard, 48 States
  • Standard (AK, HI)
  • Express, 48 States
  • Express (AK, HI)
Seller since 2010

Feedback rating:


Condition: Good
Book has a small amount of wear visible on the binding, cover, pages. Selection as wide as the Mississippi.

Ships from: St Louis, MO

Usually ships in 1-2 business days

  • Canadian
  • International
  • Standard, 48 States
  • Standard (AK, HI)
  • Express, 48 States
  • Express (AK, HI)
Seller since 2009

Feedback rating:


Condition: Good
Minimal damage to cover and binding. Pages show light use. With pride from Motor City. All books guaranteed. Best Service, Best Prices.

Ships from: Brownstown, MI

Usually ships in 1-2 business days

  • Canadian
  • Standard, 48 States
  • Standard (AK, HI)
  • Express, 48 States
  • Express (AK, HI)
Seller since 2014

Feedback rating:


Condition: Good
Ex-Library Book - will contain Library Markings. Book shows minor use. Cover and Binding have minimal wear, and the pages have only minimal creases. Free State Books. Never ... settle for less. Read more Show Less

Ships from: Halethorpe, MD

Usually ships in 1-2 business days

  • Canadian
  • International
  • Standard, 48 States
  • Standard (AK, HI)
  • Express, 48 States
  • Express (AK, HI)
Seller since 2009

Feedback rating:


Condition: Good
Giving great service since 2004: Buy from the Best! 4,000,000 items shipped to delighted customers. We have 1,000,000 unique items ready to ship! Find your Great Buy today!

Ships from: Toledo, OH

Usually ships in 1-2 business days

  • Canadian
  • International
  • Standard, 48 States
  • Standard (AK, HI)
  • Express, 48 States
  • Express (AK, HI)
Seller since 2009

Feedback rating:


Condition: Good
Our feedback rating says it all: Five star service and fast delivery! We have shipped four million items to happy customers, and have one MILLION unique items ready to ship today!

Ships from: Toledo, OH

Usually ships in 1-2 business days

  • Canadian
  • International
  • Standard, 48 States
  • Standard (AK, HI)
  • Express, 48 States
  • Express (AK, HI)
Seller since 2010

Feedback rating:


Condition: Good
03/31/1999 Paperback Good **SHIPPED FROM UK** We believe you will be completely satisfied with our quick and reliable service. All orders are dispatched as swiftly as possible! ... Buy with confidence! *****PLEASE NOTE: This item is shipping from an authorized seller in Europe. In the event that a return is necessary, you will be able to return your item within the US. To learn more about our European sellers and policies see the BookQuest FAQ section***** Read more Show Less

Ships from: London, United Kingdom

Usually ships in 1-2 business days

  • Canadian
  • International
  • Standard, 48 States
  • Standard (AK, HI)
Seller since 2014

Feedback rating:


Condition: Good
Indianapolis, IN 1999 Trade paperback Good. The book has been read but remains in clean condition. All pages are intact and the cover is intact. Some minor wear to the spine. ... Trade paperback (US). Glued binding. 510 p. Contains: Illustrations. Sams Teach 24 Hours (Paperback). *****PLEASE NOTE: This item is shipping from an authorized seller in Europe. In the event that a return is necessary, you will be able to return your item within the US. To learn more about our European sellers and policies see the BookQuest FAQ section***** Read more Show Less

Ships from: Goring-By-Sea, United Kingdom

Usually ships in 1-2 business days

  • Canadian
  • International
  • Standard, 48 States
  • Standard (AK, HI)
Seller since 2014

Feedback rating:


Condition: Good
Possible retired library copy, some have markings or writing. May or may not include accessories such as CD or access codes.

Ships from: Chatham, NJ

Usually ships in 1-2 business days

  • Canadian
  • International
  • Standard, 48 States
  • Standard (AK, HI)
  • Express, 48 States
  • Express (AK, HI)
Page 1 of 2
Showing 1 – 10 of 11 (2 pages)
Sort by
Sending request ...


Sams Teach Yourself MFC in 24 Hours provides an understanding of the fundamentals of MFC. Twenty four sessions of one hour or less show you how to create and cutomize user interfaces, develop complete applications for all versions of Windows, and organize and work with data. This straightforward, step-by-step approach also covers drawing graphics, managing and accessing databases, implementing printing, and creating DLLs and Custom Controls.
Read More Show Less

Product Details

  • ISBN-13: 9780672315534
  • Publisher: Sams
  • Publication date: 3/11/1999
  • Series: Sams Teach Yourself Series
  • Pages: 510
  • Product dimensions: 7.38 (w) x 9.10 (h) x 1.24 (d)

Table of Contents

Introduction 1
Hour 1 Welcome to MFC 3
Win32 Basics 3
Windows 4
Window Procedures, Events, and Messages 5
Strange Data Types 6
The WinMain () Function 7
The MFC Alternative 7
A Skeletal MFC Application 8
The Application Object 11
The Main Frame Window 13
Application Resources 16
Hour 2 Building MFC Applications 21
Document-Centric Applications 22
The Structure of an MFC Application 23
Inside the Application Object 24
Modeling Data with Documents 25
Looking at Data with Views 26
MFC Naming Conventions 26
The Skeleton Application Revisited 28
The Document Object 28
The View Object 32
Other Document/View Changes 35
Hour 3 Creating and Using Application Resources 41
Understanding the Role of Resources 42
Types of Resources 44
Defining Resources in a Resource Script 45
Accelerators 45
Bitmaps 46
Cursors 46
Icons 47
Menus 47
Dialog Boxes 49
String Tables 50
Version Resources 51
Using Resources in an Application 51
Hour 4 Interacting with the User 59
The Importance of User Input 59
Working with Message Maps 60
Using Message Map Macros 61
Writing Message Handlers 62
Handling User Input Messages 63
Keyboard Messaging Basics 64
Handling Keyboard Messages 66
Mouse Messaging Basics 67
Handling Mouse Messages 69
Hour 5 Making Use of Controls 75
Understanding Controls 75
Traditional Windows Controls 76
Common Controls 78
Controls and MFC 80
Creating Controls with MFC 81
Handling Control Notifications 82
ActiveX Controls 85
Putting Controls to Work 86
Hour 6 Using Common Dialog Boxes 97
Origins of Common Dialog Boxes 98
Exploring the Common Dialog Boxes 98
MFC Common Dialog Box Classes 99
File Open and File Save As 100
Color Selection 101
Font Selection 102
Find Text and Replace Text 103
Page Setup 104
Print 105
Using Common Dialog Boxes 105
Opening Files 107
Selecting Color 109
Hour 7 Retrieving Information with Custom Dialog Boxes 113
Using Message Boxes 114
Modal and Modeless Dialog Boxes 115
MFC Dialog Box Support 117
Dialog Box Data 117
Dialog Box Messaging 118
Creating a CDialog Object 118
Dialog Box Resources 118
Building Simple Dialog Boxes 120
Creating the Dialog Box Resource 121
Creating the Dialog Box Class 123
Invoking the Dialog Box 126
Hour 8 Manipulating Menus 131
Responding to Menu Events 132
Analyzing the System Menu 132
Obtaining a System Menu Object 133
Adding a System Menu Item 133
Dynamically Modifying Menus 134
Getting Menus and Pop-up Menus 135
Adding Menu Items 135
Dynamic Menus and Animator3 136
Using Floating Pop-up Menus 140
Updating Menus 142
MFC's Command Update Message Handlers 142
Updating the Animator3 Menu 143
Hour 9 Drawing Graphics 149
Graphics Fundamentals 149
The Importance of Device Contexts 150
Basic Graphics Components 151
The Windows Graphics Coordinate System 152
Understanding Color 153
GDI and MFC 155
Painting Windows 156
Drawing Graphics Primitives 157
Lines 157
Rectangles 158
Ellipses 159
Drawing Text 160
Drawing Bitmaps 161
Loading a Bitmap 162
Painting a Bitmap 162
Putting It All Together 163
Hour 10 Managing Data with MFC 173
Getting a Handle on Data Structures 174
MFC's Data Classes 175
Basic Data Structures 175
Data Collections 176
Support Classes 177
A Serialization Primer 178
Working with Strings 179
Creating Strings 179
Accessing String Characters 180
Concatenating Strings 181
Comparing Strings 181
Strings and Char Pointers 182
Working with Time 182
Hour 11 Organizing Data with MFC's Collection Classes 187
Revisiting the MFC Collection Classes 188
Array 188
List 189
Map 189
Choosing Collections 190
Using the Collection Classes 191
Putting Arrays to Work 192
CArray 192
CTypedPtrArray 194
Organizing Data into Lists 194
CList 195
CTypedPtrList 196
Mapping Data 197
CMap 197
CTypedPtrMap 199
Enhancing the Doodle Application 199
Hour 12 Managing Application Data with Documents 207
Document Basics 208
MFC's Document Support 209
Documents and Serialization 210
Creating Documents 212
Applying Documents to Doodle 212
The Main Frame Window and Application Object 212
Application Resources 215
The Document Class 217
Serializing the CGraphic Class 221
What's Missing? 225
Hour 13 Viewing Application Data 227
Understanding Views 227
Printing and Views 228
View Windows 229
MFC's View Support 229
Creating Views 232
Adding a View to Doodle 232
Hour 14 Enhanced User Interfaces 241
Optimizing Views 241
Updating the View 242
Drawing the View 244
Scrolling Views 245
Sizing Up the Document 245
Scrolling the View 247
Using Multiple Views 251
Splitting the Views 251
An Alternative View for Doodle 253
Hour 15 Utilizing Control Bars 261
Understanding Control Bars 261
Using Toolbars 264
Using Status Bars 266
Showing and Hiding Control Bars 269
Working with ToolTips 270
Hour 16 Managing Multiple Documents 275
MDI Fundamentals 276
Inside MDI Applications 278
A Template for Multiple Documents 279
Framing an MDI Application 279
The MDI Client Window 279
Child Document Windows 280
Menus and MDI Applications 280
Building an MDI Application 280
Resources 281
The Application 284
The Main Frame Window 287
Hour 17 Inside Printing 293
Printing Basics 293
MFC's Support for Printing 294
Printing in the View 295
The PrintInfo Object 297
Standard Print Commands 298
Printing and GDI Mapping Modes 299
Printing Doodle Documents 301
Resources 301
The Application 304
The View 304
The Document 310
The Document's Final Stages 311
Hour 18 Accessing Databases with DAO 317
Databases and MFC 318
The DAO Object Model 319
The DBEngine Object 319
The Workspace Object 320
The Database Object 320
Internal Database Objects 320
The MFC DAO Classes 320
MFC, DAO, and Form-Based Applications 321
Creating a Custom Record Set Class 322
The Document and View 323
Building a Database Application 324
Resources 325
Database Support 329
The Document 337
The View 340
Hour 19 ADO and the Future of Databases 351
Getting a Handle on the Big Picture 352
ODBC 353
DAO 353
RDO 353
OLE DB 354
ADO 354
The Benefits of ADO 354
Digging into ADO Objects 355
The ADO Data Control 357
ADO and MFC 358
Hour 20 Connecting to the Web 361
Understanding Web-Enabled Applications 361
The WebBrowser Control 363
An HTML View 364
Using the CHtmlView Class 364
For Internet Explorer Only 366
Building a Simple Web Browser 366
Resources 367
The View 369
Hour 21 Multimedia and DirectX 377
Multimedia Basics 378
What Is DirectX? 378
DirectX Foundation 379
DirectX Media 380
The DirectX Media Player Control 381
MFC and the Media Player Control 383
Using the Media Player Control 384
Resources 385
The Application 389
The Main Window 391
Hour 22 Creating DLLs 399
DLL Fundamentals 399
To Dynamically Link or Not 402
DLL Mechanics 403
Managing DLLs with DLLMain () 404
Creating an MFC Extension DLL 405
Using an MFC Extension DLL 411
Hour 23 Creating Custom Controls 415
When Standard Controls Aren't Enough 416
Deriving from an Existing Control 417
Creating a Control from Scratch 420
Testing Controls 423
Hour 24 Creating Wizards 431
Simplifying Tasks with Wizards 431
Property Sheets, Property Pages, and Wizards 433
MFC's Support for Property Sheets and Wizards 435
The CPropertySheet Class 435
The CPropertyPage Class 437
Creating a Simple Wizard 438
The Resources 439
The Wizard Data 444
The Wizard Pages 445
The Wizard 450
Testing the Investment Wizard 452
Appendix A Quiz Answers 455
Appendix B MFC Information Resources 477
Online Resources 478
Periodicals 478
Appendix C MFC and Visual Development Tools 481
Read More Show Less

First Chapter

[Figures are not included in this sample chapter]

Sams Teach Yourself MFC in 24 Hours
- 2 -
Building MFC Applications

This hour opens a thorough discussion of application development with MFC by exploringMFC's document/view architecture. You not only learn about the basis of document-centricapplications in general, but also about MFC's specific support for building applicationswith documents and views. By the end of the hour you will have created a new SkeletonDVapplication that makes use of MFC's document/view architecture.

In this hour, you will learn about

  • The importance of document-centric applications
  • The overall structure of an MFC application
  • The naming conventions commonly used in MFC programming
  • How to build a skeletal application based on MFC's document/view architecture

Document-Centric Applications

One of the most important features provided by MFC is its document/view architecture,which makes a clear distinction between an application's data and user interface.The significance of the document/view architecture is that it allows applicationdevelopers to delineate between an application's data and the presentation of thatdata. It also benefits a user running an application because she i s free to focuson the information the application manipulates, as opposed to the application itself.Applications that make use of a document/view architecture are known as document-centricapplications.

NEW TERM: Document-centric is an application description implying thatan application makes use of a document/view architecture, which enables the userto focus on the manipulation of documents.

To better understand document-centric applications, consider a word processorsuch as WordPad, which ships with Windows 95/98. The WordPad application operatessolely on word processing documents, typically in the Word document format. If youdouble-click a .doc file in Windows Explorer, an instance of WordPad will be launchedwith the file opened as a document. Files of type .DOC are associated with the WordPadapplication because it is designed specifically to work with Word documents.

It's easy to see how WordPad could be a document-centric application because youalready tend to think of word processing files as documents. But what about othertypes of applications? There are a variety of different applications that could fitinto a document/view architecture if you just expand your notion of a document. Forexample, Paint and Solitaire can both be implemented as document-centric applications.It is not surprising that Paint can be implemented this way because thinking of animage as a document isn't too much of a stretch. Solitaire is a little different,however, because there is no data being directly modified by the user. The game stateinformation itself can be considered a document, though. In other words, the arrangementof the cards on the screen can be represented as a document.

In b oth of these examples, making distinctions between the documents and viewsimproves the organization of the applications. Consider the Paint application fora moment. Assuming the document is simply the image being painted, the view is theclient area that allows the user to view and modify the image. The view would communicatewith the document to properly display and manipulate the image. The loading and savingof images are tasks solely performed by the document. Likewise, the view is completelyresponsible for interacting with the user and communicating changes to the document.

In addition to documents and views, MFC document-centric applications employ adocument template that makes the association between the document, view, and applicationframe window. In MFC, you create the document, view, and frame window classes, andthen allow the standard MFC document template to connect them all together appropriately.You will learn a great deal more about the relationship between documents and viewslater in the book. Nonetheless, I wanted to give you a quick introduction here becauseyou'll be modifying the Skeleton application to be document-centric a little laterin the hour.

NEW TERM: A document template is a special object that associates a document,view, frame window, and application resources with each other.

The Structure of an MFC Application

Although I showed you the source code for the Skeleton application in the previoushour, I didn't spend much time explaining the overall structure of MFC applications.Let's take a moment to build a more solid foundation on how MFC applications arestructured. Regardless of whether an application uses MFC's document/view archi tecture,all MFC applications have a few things in common:

  • An application object
  • A main frame window
  • User interface elements
  • Application data
  • Resources

The application object is the foundation for all MFC applications. It works behindthe scenes to orchestrate the startup, execution, and termination of an application.The application object is responsible for creating a main frame window, which servesas the basis for an application's user interface. The main frame window houses theuser interface elements such as buttons and toolbars that are used to carry out applicationtasks.

Practically all MFC applications operate on some type of data, whether it is text,graphics, database records, or custom application-specific data. This data is typicallyviewed and manipulated within the client area of the main frame window. In additionto the application-specific data involved in the primary function of an application,there is also special data associated with all applications. This data comes in theform of application resources such as icons and menus. Application resources arecreated and associated with an application during development, then compiled directlyinto an application's executable .EXE file. You explore resources more thoroughlyin Hour 3, "Creating and Using Application Resources."

Inside the Application Object

You learned about the Application object in the last hour, but didn't dig intothe details of what it does for an application. The purpose of the application objectis to control the initialization, running, and termination of an application. Asidefrom encapsulating the Wi n32 WinMain() function for an application, the Applicationobject provides some important member functions that can be used to control the executionof an application:

  • InitInstance()
  • Run()
  • OnIdle()
  • ExitInstance()

Figure 2.1 shows the relationship between these member functions and the WinMain()function.

FIGURE 2.1 The relationship between application object member functions and the WinMain() function.

From Figure 2.1, it is apparent that WinMain() still runs the show behind thescenes in an MFC application. However, the application object neatly provides accessto important sections of the WinMain() function through its member functions. Thenext few sections examine each of these member functions.

The InitInstance() Member Function

The InitInstance() member function is called near the start of WinMain() to performinstance initialization, which occurs for each instance of an application that isexecuted. InitInstance() is without a doubt the most important member function inapplication objects because practically all applications are concerned with instanceinitialization. In fact, you are required to override the InitInstance() member functionin your own application classes. Typically, you override InitInstance() to constructyour main window object and set the inherited m_pMainWnd data member to point tothat window.

The Run() Member Function

In an application built solely with the Win32 API, the WinMain() function spendsthe vast majority of its time in a message loop that waits for and processes incomingmessages. This message loop is ultimately responsible for receiving messages anddispatching them to the main frame window of an application. In an MFC application,WinMain() delegates the message loop to the Run() member function. Run() loops continuallywait for a message. If no messages are available, which is often the case, Run()calls the OnIdle() member function to perform idle processing. When the applicationis terminated, Run() calls the ExitInstance() member function.

The OnIdle() Member Function

The OnIdle() member function is used to perform idle processing that isn't immediatelycritical to the operation of an application. You typically override OnIdle() to performbackground tasks such as a lengthy calculation. The default version of OnIdle() updatesthe state of user interface elements such as menu items and toolbar buttons.

The ExitInstance() Member Function

The ExitInstance() member function is called when an instance of an applicationis terminated. ExitInstance() is called by the Run() member function, usually inresponse to the user closing an application. You typically override ExitInstance()to perform the cleanup of objects created throughout the execution of an application.However, keep in mind that MFC automatically cleans up standard objects such as documents,views, and frame windows.

Modeling Data with Documents

The description of application structure thus far follows the Skeleton applicationexample from the previous hour. How does it change when an application is moved tothe document/view architecture? Surprisingly enough, things don't change too much.The primary change is organizational; the application object and main frame windowaren't very different in a document/view applicat ion. The first noticeable changeis the packaging of application-specific data into a document class. This documentclass derives from the MFC CDocument class, which provides features common to alldocuments.

The CDocument class supports standard operations such as creating a document,loading it, and saving it. You learn more about how to use the CDocument class tomodel application data with documents in Hour 12, "Managing Application Datawith Documents."

Looking at Data with Views

In MFC's document view/architecture, views take on the role of providing a userinterface for viewing and editing document data. A view typically takes up the clientarea of an application's main frame window, and can contain any number of user interfaceelements. However, standard application user interface elements such as the menuat the top of the frame window don't belong to a view. Neither do toolbars and statusbars. Views are allowed to use pop-up menus and floating tool palettes. A particularview on document data is implemented in a view class, which must be derived fromthe MFC CView class.

The CView class provides the basic windowing functionality necessary for creatingviews. View classes derived from CView are always attached to a document class, andcan be thought of as an intermediary between the user and the document. It's worthnoting that views are child windows of an application's main frame window. You learnhow to use the CView class to create interesting views of documents in Hour 13, "ViewingApplication Data."

Figure 2.2 sums up what you've learned by providing a look at the relationshipbetween the different parts of a document/view applica tion.

FIGURE 2.2 The relationship between the different parts of a document/ view application.

MFC Naming Conventions

Before I move on to tackle a new version of the Skeleton application that supportsdocuments and views, I'd like to clear up some of the naming conventions used inMFC programming. You've probably already caught on to some of these, such as MFCclass names always beginning with the letter C. However, to keep you from stumblinglater in the book, let's go over the most important of the naming conventions rightnow:

  • Functions are named as phrases with each word capitalized. Examples include WinMain(), MessageBox(), and GetWindowRect().
  • Classes are named like functions with the addition of a beginning letter C. Examples include CWnd, CDocument, and CMenu.
  • Variables are named like functions, but they have a lowercase prefix that identifies the data type. Additionally, instance members of classes use the prefix m_ to signify that they are members; static members don't use any special prefix. Examples include szText, m_hWnd, and bEnabled. Table 2.1 lists some of the more commonly used data prefixes.
  • Data types specific to Win32 are defined in all uppercase. Examples include HANDLE, HWND, and POINT.
  • Constants such as messages and resource identifiers are defined in all uppercase. Examples include WM_CREATE, IDR_MAINFRAME, and IDI_MYICON.
  • Win32 API functions are always called by explicitly using the scope resolution operator, ::. This is done to distinguish between calling Win32 API func tions and MFC member functions of the same name. An example of this is ::GetMessage().


Prefix Data Type
h A handle (HWND, HICON, and so on)
w A WORD (16-bit unsigned integer)
l A LONG (32-bit signed integer)
p A pointer
lp A long (far) pointer
sz A null-terminated string (terminated by a zero byte)
lpsz A long pointer to a null-terminated string
b A Boolean (BOOL)
rc A rectangle structure (RECT)
pt A point structure (POINT)

Programmers have long struggled with the problem of writing code that is easyto understand. Windows exacerbates this problem by introducing lots of differentdata types, which makes it difficult to keep up with which variables are of whichtype. Using the prefixes listed in Table 2.1 to name variables makes it easier todetermine the data type of a variable without having to reference the variable declaration.This naming convention is known as Hungarian notation, and is named after the HungarianMicrosoft programmer Charles Simonyi, who initially came up with the scheme.

NEW TERM: Hungarian notation is the variable-naming convention of beginninga variable name with a lowercase letter or letters that indicate the data type ofthe variable.

The Skeleton Application Revisited

You now have sufficient knowledge of the structure of MFC applications to revisitthe Skeleton application and apply MFC's document/view architecture to it. The newSkeleton application is called SkeletonDV. It will remain very minimal but will fullysupport the MFC document/view architecture. This is beneficial because you will thenhave starter code for the remainder of the sample applications covered throughoutthe book, whether or not they require documents and views.

The task of structuring the Skeleton application as a document/view applicationcan be broken down into four main parts:

  • Crea te a document class
  • Create a view class
  • Modify existing application code
  • Modify existing application resources

The next few sections tackle each of these tasks.

The Document Object

As you learned earlier in this hour, all document classes must derive from theCDocument class. Because the goal in the Skeleton application is to keep things minimal,you'll notice that there isn't a whole lot to do beyond deriving from CDocument.Listings 2.1 and 2.2 contain the source code for the SkeletonDoc.h and SkeletonDoc.cppfiles.


 1: #ifndef __SKELETONDOC_H__ 2: #define __SKELETONDOC_H__ 3:  4: //----------------------------------------------------------------- 5: // CSkeletonDoc Class - Skeleton Document Object
 6: //-----------------------------------------------------------------
 7: class CSkeletonDoc : public CDocument { 8:   // Public Constructor(s)/Destructor 9: public:10:                 CSkeletonDoc();11:   virtual       ~CSkeletonDoc();12: 13:   // Public Member Functions14: public:15:   virtual BOOL  OnNewDocument();16:   virtual void  Serialize(CArchive& ar);17: 18:   // Diagnostic Functions19: public:20: #ifdef _DEBUG21:   virtual void  AssertValid() const;22:   virtual void  Dump(CDumpContext& dc) const;23: #endif //_DEBUG24: 25:   // Message Map & Runtime Support26: protected:27:   DECLARE_MESSAGE_MAP()28:   DECLARE_DYNCREATE(CSkeletonDoc)29: };30: 31: #endif


 1: //------------------------------------------------------- ---------- 2: // Inclusions 3: //----------------------------------------------------------------- 4: #include "StdAfx.h" 5: //----------------------------------------------------------------- 6: #include "SkeletonDoc.h" 7:  8: //----------------------------------------------------------------- 9: // MFC Debugging Support10: //-----------------------------------------------------------------11: #ifdef _DEBUG12: #undef THIS_FILE13: static char BASED_CODE THIS_FILE[] = __FILE__;14: #endif15: 16: 17: //-----------------------------------------------------------------18: // Message Map & Runtime Support19: //-----------------------------------------------------------------20: BEGIN_MESSAGE_MAP(CSkeletonDoc, CDocument)21: END_MESSAGE_MAP()22: 23: IMPLEMENT_DYNCREATE(CSkeletonDoc, CDocument)24: 25: //-----------------------------------------------------------------26: // Public Constructor(s)/Destructor27: //-----------------------------------------------------------------28: CSkeletonDoc::CSkeletonDoc() {29: }30: 31: CSkeletonDoc::~CSkeletonDoc() {32: }33: 34: //-----------------------------------------------------------------35: // Public Member Functions36: //-----------------------------------------------------------------37: BOOL CSkeletonDoc::OnNewDocument() {38:   if (!CDocument::OnNewDocument())39:     return FALSE;40: 41:   // Initialize new document42:   // TODO43: 44:   return TRUE;45: }46: 47: void CSkeletonDoc::Serialize(CArchive& ar) {48:   if (ar.IsStoring()) {49:     // Store document data50:     // TODO51:   }52:   else {53:     // Load document data54:     // TODO55:   }56: }57: 58: //-----------------------------------------------------------------59: // Diag nostic Functions
60: //-----------------------------------------------------------------
61: #ifdef _DEBUG62: void CSkeletonDoc::AssertValid() const {63:   CDocument::AssertValid();64: }65: 66: void CSkeletonDoc::Dump(CDumpContext& dc) const {67:   CDocument::Dump(dc);68: }69: #endif //_DEBUG

Beyond providing an empty constructor and destructor, the CSkeletonDoc class definesmember functions named OnNewDocument() and Serialize().

The OnNewDocument() function is called in response to the user selecting New froman application's File menu. In other words, it is responsible for properly initializingan empty document. Because the CSkeletonDoc class doesn't actually define any documentdata, it isn't necessary for the OnNewDocument() function to do anything. Noticethat there is a commented placeholder for inserting code to perform the initializationof document data.

NOTE: You'll find comments in the code throughout the book that serve as placeholders for inserting code. These comments are clearly marked with the word TODO, which means this is something "to do" later. In the Skeleton application, the TODO comment is used to show where you would normally place application code. The Skeleton application is so minimal that it doesn't require code in places where other applications would require it.

The Serialize() function is called to load or save the document data. The If statementchecks to see whether the function is to load or save the document data. Again, Iused comments to show where you would normally place functioning code.

In addition to the OnNewDocument() and Serialize() mem ber functions, the CSkeletonDocclass also provides two diagnostic functions, AssertValid() and Dump(). I refer tothese functions as diagnostic functions because they are only used for testing purposesduring the development of the SkeletonDV application, which is why they are placedwithin the _DEBUG macro. Code placed within the _DEBUG macro is compiled into onlythe debug version of an application. You might have to set this up with your specificcompiler to work properly. Visual C++ defines the _DEBUG macro by default when thecompile target is set to debug.

The AssertValid() member function performs a validity check on an object by checkingits internal state. In addition to calling its base class AssertValid() function,a class should check the integrity of its own data members. The CSkeletonDoc classdoesn't define any data members of its own, which is why there isn't any additionalcode in its AssertValid() function.

The Dump() member function dumps the contents of an object so that its internalstate can be examined. A CDumpContext object is provided as the only argument tothe function. This dump context is what you use to actually dump the contents ofan object. Because the CSkeletonDoc class doesn't define any data members of itsown, it isn't necessary to dump anything in the Dump() function.

That wraps up the CSkeletonDoc document class. Let's move on to the view class.

The View Object

Similar to document classes, view classes must derive from a special MFC class;all view classes must derive from the CView class. Much like the CSkeletonDoc class,you'll notice that there isn't a whole lot of code in the view class beyond derivingfrom CView. Listings 2.3 and 2 .4 contain the source code for the SkeletonView.h andSkeletonView.cpp files.


 1: #ifndef __SKELETONVIEW_H__ 2: #define __SKELETONVIEW_H__ 3:  4: //----------------------------------------------------------------- 5: // CSkeletonView Class - Skeleton Document Object 6: //----------------------------------------------------------------- 7: class CSkeletonView : public CView { 8:   // Public Constructor(s)/Destructor 9: public:10:                 CSkeletonView();11:   virtual       ~CSkeletonView();12: 13:   // Public Member Functions14: public:15:   CSkeletonDoc* GetDocument();16:   virtual BOOL  PreCreateWindow(CREATESTRUCT& cs);17:   virtual void  OnDraw(CDC* pDC);18: 19:   // Diagnostic Functions20: public:21: #ifdef _DEBUG22:   virtual void  AssertValid() const;23:   virtual void  Dump(CDumpContext& dc) const;24: #endif //_DEBUG25: 26:   // Message Map & Runtime Support27: protected:28:   DECLARE_MESSAGE_MAP()29:   DECLARE_DYNCREATE(CSkeletonView)30: };31: 32: #ifndef _DEBUG33: inline CSkeletonDoc* CSkeletonView::GetDocument() {34:   return (CSkeletonDoc*)m_pDocument;35: }36: #endif //_DEBUG37: 38: #endif


 1: //----------------------------------------------------------------- 2: // Inclusions 3: //----------------------------------------------------------------- 4: #include "StdAfx.h" 5: //----------------------------------------------------------------- 6: #include "SkeletonDoc.h" 7: #include "SkeletonView.h" 8:  9: //----------------------------------------------------------- ------10: // MFC Debugging Support11: //-----------------------------------------------------------------12: #ifdef _DEBUG13: #undef THIS_FILE14: static char BASED_CODE THIS_FILE[] = __FILE__;15: #endif
17: 18: //-----------------------------------------------------------------19: // Message Map & Runtime Support20: //-----------------------------------------------------------------21: BEGIN_MESSAGE_MAP(CSkeletonView, CView)22: END_MESSAGE_MAP()23: 24: IMPLEMENT_DYNCREATE(CSkeletonView, CView)25: 26: //-----------------------------------------------------------------27: // Public Constructor(s)/Destructor28: //-----------------------------------------------------------------29: CSkeletonView::CSkeletonView() {30: }31: 32: CSkeletonView::~CSkeletonView() {33: }34: 35: //-----------------------------------------------------------------36: // Public Member Functions37: //-----------------------------------------------------------------38: BOOL CSkeletonView::PreCreateWindow(CREATESTRUCT& cs) {39:   // Initialize the view window properties40:   // TODO41: 42:   return CView::PreCreateWindow(cs);43: }44: 45: void CSkeletonView::OnDraw(CDC* pDC) {46:   // Get a pointer to the document47:   CSkeletonDoc* pDoc = GetDocument();48:   ASSERT_VALID(pDoc);49: 50:   // Draw the view51:   // TODO52: }53: 54: //-----------------------------------------------------------------55: // Diagnostic Functions56: //-----------------------------------------------------------------57: #ifdef _DEBUG58: void CSkeletonView::AssertValid() const {59:   CView::AssertValid();60: }61: 62: void CSkeletonView::Dump(CDumpContext& dc) const {63:   CView::Dump(dc);64: }65: 66: CSkeletonDoc* CSkeletonV iew::GetDocument() {67:   ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CSkeletonDoc)));68:   return (CSkeletonDoc*)m_pDocument;69: }70: #endif //_DEBUG

In addition to providing an empty constructor and destructor, the CSkeletonViewclass defines member functions named GetDocument(), PreCreateWindow(), and OnDraw().

The GetDocument() member function is called to get the document associated withthe view. The GetDocument() function performs an extremely important role becauseit is the only way a view can gain access to the document to which it is associated.The source code for the GetDocument() function is interesting in that there are twodifferent versions. The version in the SkeletonView.cpp file is a diagnostic debugversion because it takes on the responsibility of making sure the document classis of the correct type. The version of GetDocument() in the SkeletonView.h file isthe release version, and is more streamlined.

The PreCreateWindow() member function is called before the underlying Win32 windowobject is created for an MFC CWnd object. The significance of the function is thatyou can use it to tweak the styles for a window before the window is created. Classesderived from CWnd typically add functionality to the overridden version of PreCreateWindow().Because the CSkeletonView window is minimal, it isn't necessary to modify any ofits styles.

The OnDraw() member function is called whenever the document data is to be renderedon the view. This is a very important function because it is solely responsible forrendering a graphical representation of document data. Because the SkeletonDV applicationhas no document data, it isn't necessary to do anything special in the OnDraw() memberfunction. Notice, however, that there is code to get a pointer to the document objectand verify its validity.

NOTE: You might have noticed the use of the ASSERT and ASSERT_VALID macros throughout the Skeleton and SkeletonDV application sample code. These macros are used to perform validity tests during the development of an application. The ASSERT macro expects a Boolean result that is TRUE if the program operates normally and FALSE if there is an error. If the Boolean result is FALSE, the ASSERT macro halts the application with an error. It's important to note that all code used in the ASSERT macro is only compiled under debug mode. For the code to execute in both debug and release modes, use the VERIFY macro instead. It works just like ASSERT except that it still allows the test code to compile in release mode.
The ASSERT_VALID macro is similar to ASSERT except it is used to check the integrity of objects. The ASSERT_VALID macro first checks to make sure an object pointer is non-NULL, and it then calls the object's AssertValid() member function. Any failure results in the application halting with an error.

Other Document/View Changes

In addition to creating document and view classes for the SkeletonDV application,you must also modify some of the original Skeleton application code to support thedocument/view architecture. First off is the application class, which requires anew and improved InitInstance() member function, as shown in Listing 2.5.


 1: BOOL CSkeletonA pp::InitInstance() { 2:   // Register the application's document templates 3:   CSingleDocTemplate* pDocTemplate; 4:   pDocTemplate = new CSingleDocTemplate(IDR_SKELETON, 5:     RUNTIME_CLASS(CSkeletonDoc), 6:     RUNTIME_CLASS(CMainFrame), 7:     RUNTIME_CLASS(CSkeletonView)); 8:   AddDocTemplate(pDocTemplate); 9:
10:   // Parse command line for standard shell commands
11:   CCommandLineInfo cmdInfo;12:   ParseCommandLine(cmdInfo);13: 14:   // Dispatch commands specified on the command line15:   if (!ProcessShellCommand(cmdInfo))16:     return FALSE;17: 18:   // Show and update the main window19:   m_pMainWnd->ShowWindow(SW_SHOW);20:   m_pMainWnd->UpdateWindow();21: 22:   return TRUE;23: }

This version of InitInstance() is a little busier than the one you saw last hourin the Skeleton application. The main difference between the two is the additionof code for establishing the document/view connection. A document template is createdthat associates the document class, view class, and main frame window class together.It also uses a resource string identified by the IDR_SKELETON constant to specifyadditional application attributes. You learn about this resource string in a moment.

The command related code in the InitInstance() function makes the applicationa little more extensible by allowing it to process command-line arguments. Command-linearguments enable you to specify what document to open when you launch an application,which is sometimes convenient. You can also define application-specific options thatare passed as command-line arguments.

Next on the agenda of SkeletonDV application changes is the removal of the Create()member function and the additio n of the PreCreateWindow() member function. The Create()member function isn't necessary in document/view applications because MFC handlesthe details of creating the main frame window for you. However, you still might wantto modify the frame window properties, which is where the PreCreateWindow() functioncomes into play. Listing 2.6 contains the source code for PreCreateWindow().


1: BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) {2:   // Initialize the frame window properties3:   // TODO4: 5:   return CFrameWnd::PreCreateWindow(cs);6: }

As you can see, this function is really just a placeholder for functionality thatyou would add in a more interesting application. Nonetheless, it gives you a headstart toward tweaking the properties of frame windows.

In addition to the code changes you've already made, there are a few resourcesthat must be added to the SkeletonDV application for it to fully support MFC's document/viewarchitecture. The first of these resources is a string that defines document informationfor the application. Listing 2.7 contains both of the string resources used in theSkeletonDV application, including the new IDR_SKELETON document string.


1: //-----------------------------------------------------------------2: // Strings3: //-----------------------------------------------------------------4: STRINGTABLE5: BEGIN6:   AFX_IDS_APP_TITLE  "Skeleton"7:   IDR_SKELETON       "Skeleton\n\n\n\n\n\n"8: END

The IDR_SKELETON document string contains a collection of substring s that definedocument properties. The substrings are separated from each other with newline characters(\n). Following is the format of the document string:


Table 2.2 lists the meanings of each of the parts of the document string format.


String Component Meaning
App The application name
DocName The default document name for new documents
DocType A descriptive name for the document type
FileType A descriptive name for the document file type
.Ext The file extension for document files
RegType The document file type used by Windows for file association
RegName The readable name of th e document file type

A quick examination of the IDR_SKELETON document string shows that it only specifiesthe App substring, which identifies the application name. It's OK to leave the othersubstrings blank because the SkeletonDV application doesn't really define its owndocument type; the CSkeletonDoc class is too minimal to be classified as a functioningdocument type.

If you recall, the whole point of creating the IDR_SKELETON document string wasto create the document template, which ties the document and view together with theframe window. This was performed back in the InitInstance() method of the CSkeletonAppclass. Along with using the IDR_SKELETON document string to identify document properties,the document template also looks for standard application resources such as an icon,menu, and accelerator table. If resources of these types are provided in the resourcefile with the IDR_SKELETON identifier, the document template will automatically findthem and associate them with the application. Listing 2.8 contains the code for theSkeletonDV menu, which uses the IDR_SKELETON identifier.


 1: //----------------------------------------------------------------- 2: // Menus 3: //----------------------------------------------------------------- 4: IDR_SKELETON MENU 5: BEGIN
 6:   POPUP "&File"
 7:   BEGIN 8:     MENUITEM "E&xit",            ID_APP_EXIT 9:   END10: END

You don't really learn about the ins and outs of menus until Hour 8, "ManipulatingMenus," but it's worth taking a quick look at the SkeletonDV menu. Even thoughthe Skelet onDV application is designed to be minimal, I decided to give it a menubecause document/view applications are expected to have one. The menu resource forthe application defines a File pop-up menu much like you are accustomed to seeingin Windows applications. There is one menu item within the pop-up menu named Exitthat is used to exit the application. The standard MFC identifier ID_APP_EXIT isused to tie the menu item to code that exits the application.


This hour built on the previous hour by digging deeper into application developmentwith MFC. More specifically, you learned about document-centric applications andMFC's document/view architecture. You studied the application object a little closer,and then learned about the MFC classes that enable you to create documents and views.From there you learned about the naming conventions commonly used in MFC programming.Finally, you wrapped up the hour by creating a new SkeletonDV application that utilizesMFC's document/view architecture.


Q When is it necessary to add code to the PreCreateWindow() member function?
A Any time you want to modify frame window styles. More specifically, if you wanted to set the initial size or position of a frame window, you could do so in the PreCreateWindow()function (see the Exercises). You can also set styles that alter window properties such as whether the window is sizeable.

Q What is the significance of building both the Skeleton and SkeletonDV applications?
A To have the option of selectively using MFC's document/view architecture. Although the document/view architecture is often beneficial, it isn't necessary in all applications. By having two types of skeletal applications, you can keep from using the document/view architecture unnecessarily. You will use both Skeleton and SkeletonDV throughout the rest of the book as the basis for other sample applications.


The Workshop is designed to help you anticipate possible questions, review whatyou've learned, and begin thinking ahead to put your knowledge into practice. Theanswers to the quiz are in Appendix A, "Quiz Answers."


1. What is the significance of MFC's document/view architecture?

2. What is the special object that associates documents, views, frame windows, and application resources with each other?

3. What works behind the scenes to orchestrate the startup, execution, and termination of an application?

4. What member function is called near the start of WinMain() to perform instance initialization for an application?

5. What member function is used to perform idle processing that isn't immediately critical to the operation of an application?

6. From what MFC class must all document classes derive?

7. What is Hungarian notation?

8. Why is the scope resolution operator (::) used to call Win32 API functions in MFC applications?

9. What is the purpose of the AssertValid() member function?

10. What is the difference between the ASSERT and VERIFY diagnostic macros?


1. Insert the following code in the C MainFrame::PreCreateWindow() member function to size the frame window to half the screen size and center it. = ::GetSystemMetrics(SM_CXSCREEN) / 2; = ::GetSystemMetrics(SM_CYSCREEN) / 2;cs.x = (( * 2) - / 2;
cs.y = (( * 2) - / 2;
2. Fill in the missing substrings of the IDR_SKELETON document string so that the Skeleton document properties are fully defined.
Read More Show Less

Customer Reviews

Be the first to write a review
( 0 )
Rating Distribution

5 Star


4 Star


3 Star


2 Star


1 Star


Your Rating:

Your Name: Create a Pen Name or

Barnes & Review Rules

Our reader reviews allow you to share your comments on titles you liked, or didn't, with others. By submitting an online review, you are representing to Barnes & that all information contained in your review is original and accurate in all respects, and that the submission of such content by you and the posting of such content by Barnes & does not and will not violate the rights of any third party. Please follow the rules below to help ensure that your review can be posted.

Reviews by Our Customers Under the Age of 13

We highly value and respect everyone's opinion concerning the titles we offer. However, we cannot allow persons under the age of 13 to have accounts at or to post customer reviews. Please see our Terms of Use for more details.

What to exclude from your review:

Please do not write about reviews, commentary, or information posted on the product page. If you see any errors in the information on the product page, please send us an email.

Reviews should not contain any of the following:

  • - HTML tags, profanity, obscenities, vulgarities, or comments that defame anyone
  • - Time-sensitive information such as tour dates, signings, lectures, etc.
  • - Single-word reviews. Other people will read your review to discover why you liked or didn't like the title. Be descriptive.
  • - Comments focusing on the author or that may ruin the ending for others
  • - Phone numbers, addresses, URLs
  • - Pricing and availability information or alternative ordering information
  • - Advertisements or commercial solicitation


  • - By submitting a review, you grant to Barnes & and its sublicensees the royalty-free, perpetual, irrevocable right and license to use the review in accordance with the Barnes & Terms of Use.
  • - Barnes & reserves the right not to post any review -- particularly those that do not follow the terms and conditions of these Rules. Barnes & also reserves the right to remove any review at any time without notice.
  • - See Terms of Use for other conditions and disclaimers.
Search for Products You'd Like to Recommend

Recommend other products that relate to your review. Just search for them below and share!

Create a Pen Name

Your Pen Name is your unique identity on It will appear on the reviews you write and other website activities. Your Pen Name cannot be edited, changed or deleted once submitted.

Your Pen Name can be any combination of alphanumeric characters (plus - and _), and must be at least two characters long.

Continue Anonymously

    If you find inappropriate content, please report it to Barnes & Noble
    Why is this product inappropriate?
    Comments (optional)