in addition to techniques such as database creation, networking systems and COM programming, all source code from the book is available enabling the reader to build their own application
Trang 1MFC Programming with Visual C++ 6 Unleashed
by David White, Kenn Scribner, Eugene Olafsen
ISBN:0672315572
Sams © 1999 (1306 pages)
This title demonstrates how to apply MFCs to many common programming problems in addition to techniques such as database creation, networking systems and COM programming, all source code from the book is available enabling the reader to build their own applications.
CDocumentSummary
MFC Dialogs, Controls, and Data InteractionCreating an Application
Starting and Using MFC AppWizardThe AppWizard-Generated Code
Trang 3CProgressCtrl Class Methods
Creating and Initializing a CProgressCtrl ObjectUsing a Progress Control
Image Lists: Class CImageList
CImageList Class Methods
Creating and Initializing a CImageList ControlList View Controls: Class CListCtrl
Trang 7Message Routing
Trang 8Idle Processing
OnIdleIdle Processing for Dialogs
The Splash Screen Component
Summary
Documents, Views, and Applications That Use ThemThe Document/View Architecture
Documents, Frames, and Views
Document TemplatesCreating New Documents
Opening New FilesSingle Versus Multiple Document TemplatesViews
The CView ClassThe CScrollView ClassThe CFormView ClassThe Database View ClassesThe Control Views
Changing Views in an SDIUsing the MDI
Summary
Extending the User Interface
Responding to the User
Trang 10Pagination
Printing with a Known Page CountPrinting with an Unknown Page CountPrinting Page Numbers
Stopping and Aborting Print Jobs
Halting a Print Job in OnPrepareDC()Halting a Print Job in OnPrint()
Servers, Clients, and Classes
The COM Runtime Environment
Defining the Class FactoryHow Are COM Objects Reused?
Marshaling and Threading
MarshalingThreading
Trang 11IDispatch
Automation Servers, Objects, and ControllersSupporting Both IDispatch and IUnknownPersisting COM Data
Trang 13MFC OLE Clients
IDispatch and Its Place in Automation
Trang 15ActiveX Container
Control Containment and Events
Trang 16Using MFC and ATL
What Is ATL and Why Is It Important for Programming inMFC?
Helpful ATL COM Support for MFC Applications
COM Pointers the Smart WayOther ATL COM SupportAdvanced ATL Support for MFC Applications
Begin with Your MFC ApplicationAdd the Required ATL SupportSummary
Scripting Your MFC Application
Scripting Basics
Scripting InterfacesDual Interfaces
Object Models
Implementing a Scripted Application
Object ImplementationSummary
MFC Database Programming
MFC Database Processing
Relational Database Concepts
TablesColumns
Trang 18CDataSourceCSessionAccessorsRowsetsAccessing Datasource DataUsing the ADO C++ Interfaces
ADOConnectionADORecordsetADOCommandADOField
ADOPropertyADOParameterADOError
Collections
Inside Collection ClassesTemplated CollectionsThe UNL_MultiEd Application
Overview
Trang 19C++ Exceptions
Defining a C++ Exception Class
MFC Exceptions
Trang 20CNotSupportedExceptionCArchiveException
CFileExceptionCResourceExceptionCOleException
CDbExceptionCOleDispatchExceptionCUserException
CDaoExceptionCInternetException
Deriving Your Own MFC-Compliant Exception ObjectsDeleting Exceptions
CHtmlView and the Document/View RelationshipCHtmlView and COM
Using the Internet Explorer ActiveX Control in a DialogBox
Using DHTML
The DHTML Object ModelThe Document ObjectOther DHTML ObjectsCollection Objects
Trang 21Obtaining the Document DHTML InterfaceObtaining the DHTML Collections InterfacesUsing the DHTML Interface
The DHTML Element Interface MethodsDocument Navigation
Sending and Receiving
Ending the Connection
Summary
WinInet Programming
Trang 22Change the Form
Change the Parse Map
Trang 23Summary
MAPI and MFC
The Messaging Application Programming InterfaceClient Applications
Trang 24Using Assisted Telephony
Using Basic Telephony
Configuring TAPIConnecting with TAPITransmitting Data with TAPIDisconnection with TAPITerminating a TAPI SessionSummary
OpenGL DatatypesOpenGL Function Naming ConventionsOpenGL Render Function ScopingThe OpenGL Matrix Stack
The OpenGL Rendering ContextMinimal OpenGL Program and a Custom View
Creating Your Basic MFC ApplicationAdding the Custom OpenGL Base ClassIntegrate the Custom View Class into Your Application
Trang 25Add the OpenGL Libraries to Your Project’s Link List2D and 3D Models
DirectDraw Basics
Trang 26Surfaces and BitmapsWindowed RenderingError Handling
DirectDraw ShutdownSummary
Multimedia and MFC
Multimedia Fundamentals
The DirectX Media Player Control
Media Formats Supported by the Media Player ControlInside the Media Player Control
The CMediaPlayer Class
Using the Media Player Control
Playing Sound
Working with WavesRevisiting DirectSoundUsing DirectSound to Play Sound EffectsSummary
Advanced MFC
Inside the Registry
Registry Usage
Trang 28Other DLL Issues
AfxLoadLibrary and AfxFreeLibrary
Designing for Extensibility and ReuseResource Location
Multiple Module Definition FilesLoad Addresses and the LinkerSummary
Creating Custom Wizards
Property Sheets and Property Pages
The CPropertySheet and CPropertyPage ClassesThe Wizard Walk and the Property Sheet ConnectionCreating a Wizard
Setting the Wizard ModeEnabling the Wizard ButtonsDisplaying the Wizard
Wizard Notification MessagesSample Program: Off to See the Wizard (WIZARD1.EXE)
Creating Wizard Page Dialog Template ResourcesCreate a Dialog Class for Each Dialog ResourceExploring the Welcome Page: Class CIntroPageExploring the About You Page: Class CPage1Updating Wizard Information for CPage2 and CPage3Creating and Displaying the Wizard
Summary
Index
Trang 29Absolutely not If by now you aren’t convinced that this is the best MFCprogramming book on the market, this introduction won’t sway you
However, this is the best MFC programming book on the market today.
Why? Simply because the information contained within these pages
represents decades of collective MFC programming experience—not thehobby-shop kind of programming, but rather the hard-core, schedule-pressure, “we need it now” kind of programming From the basic to theintricate, every page contains more experience per page than any otherMFC book out there today
Programmers of all levels will benefit from the information you find here.You don’t understand the Document/View architecture? It’s explainedhere You want to extend and go beyond the Document/View
Trang 30Programming with Visual C++ 6 Unleashed.
How This Book Is Organized
This book is designed to be the most comprehensive MFC programmingresource available anywhere today As you work from chapter to chapter,you’ll not only learn what makes MFC tick, but you’ll also learn how tosupercharge MFC, customize it, and take the architecture and make itwork the way you want it to work You’ll go way beyond the wizard-
generated code and see how experienced MFC programmers do their magic Soon, it’ll be your magic, too:
• Part I, “Core MFC,” covers the core MFC concepts Here, you see
how MFC was crafted to be a tremendous general-purpose
application framework When you understand the basic mechanics,you’ll see how to tailor MFC to better fit your programming
requirements Chapter 1 shows you the MFC architecture and
introduces you to the major MFC classes you need to understand toget the most from the tool Chapter 2 initiates your journey through
Trang 314 shows you how to manage GDI resources using MFC, as well ashow you work with fonts, brushes, and so on After you know how todeal with standard controls and paint screen items, you have whatyou need to tackle Chapter 5, which shows you how to create
Document/View architecture Chapter 8 shows you how to extendyour application’s user interface Finally, Chapter 9 blows the coveroff using the printer from your MFC application, allowing you to move
past the basic wizard-based code to really use the printer.
• Part III, “MFC and COM Programming,” describes MFC and COM
programming, as most of today’s Windows applications use COM toprovide at least some of their functionality Chapter 10 introducesyou to COM, and Chapter 11 provides an explanation of MFC’s
implementation of COM Chapters 12 and 13 discuss OLE serversand clients, and Chapter 14 shows you how to write feature-packedActiveX controls that the containers you’ll develop in Chapter 15 canuse to their advantage Chapter 16 gives you the facts about mixingMFC and ATL, a templated COM framework Chapter 17 shows youhow to add scripting capabilities to your MFC applications
• Part IV, “MFC Database Programming,” shows you how MFC and
databases work together Chapter 18 looks at MFC and various
database programming concepts and technologies Chapter 19
moves past the basics and shows you the current technologies inMFC (and COM) database processing
• Part V, “MFC Utility Classes,” nails down the details regarding the
MFC utility classes Chapter 20 covers MFC string and collectionmanagement Chapter 21 shows you how to work with files usingMFC Chapter 22 provides the critical details you need to processexceptional runtime conditions
• Part VI, “MFC and the Web,” marries MFC and the Web Chapter
Trang 32advanced MFC network programming Chapter 26 describes MFCISAPI programming Need to add telephonic or electronic mail
support to your MFC application? Then Chapters 27 and 28 are herefor you
• Part VII, “MFC and Graphics Programming,” introduces you to the
fascinating area of MFC graphics programming Chapter 29
describes OpenGL and how you can exploit that technology in yourMFC applications Chapter 30 similarly describes MFC and DirectX.Chapter 31 goes a step further by adding full-fledged multimediasupport to your MFC applications
• Part VIII, “Advanced MFC,” gives you a wealth of insight born of
experience Chapter 32 shows you how to work with the WindowsRegistry database Chapter 33 describes using MFC from withinDLLs And the final chapter, Chapter 34breaks open the secrets ofDeveloper Studio AppWizard programming
Who Should Read This Book?
Actually, this book is perfect for just about anyone interested in
programming Windows applications using MFC Whether you are justbeginning or have weathered MFC programming from its inception, thereare valuable nuggets for you here:
Beginners—The basic concepts are clearly and concisely covered.More important than that, however, is the valuable coverage you’llfind regarding pitfalls and potential optimizations You’ll learn thebasics, but you’ll also learn how to avoid common beginning MFCprogrammer mistakes
Casual and accomplished MFC programmers—Use this book as areference to delve into topics of specific interest You will be able toreuse much of the code you find here to enhance your ongoing
Windows programming tasks You’ll also find detailed coverage ofthe latest Microsoft technologies with specific use from within MFC-based applications
programmer information you won’t find elsewhere Our goal was to
Trang 33of accomplishing intricate programming tasks If you need it, it’s herefor you
We have worked exceptionally hard to provide you with the definitive
work to date regarding MFC programming Enjoy!
Trang 34The Microsoft Foundation Classes are a excellent example of how anobject-oriented approach to packaging software functionality can lead tocode reuse, reduced application complexity, and in the end, a more
efficient software development environment
MFC has been around for about seven years now The first version ofMFC was released with version 7 of Microsoft’s 16-bit C/C++ compiler,and it represented little more than a wrapper around the Window GDIcalls (Visual C++ version 1 followed Microsoft C/C++ version 7.)
For those who had been developing applications using the Windows API,MFC promised an immense gain in programming productivity Ratherthan write Petzold-style WinMain procedures, message loops, and switch
statements to dispatch messages, you could create an instance of a
class that would take care of much of the drudgery Rather than createGDI objects, write many lines of code to initialize and use the objects,carefully track their lifetimes, and be sure to release them properly, youcould instantiate an MFC class, often simply use the default values, andthen let the destructor worry about cleaning up system resources
Indeed, to truly comprehend the advantages of using MFC, you shouldwrite a significant graphics application first using MFC and then usingstrictly the Windows API Then compare war stories
But although MFC made the programmer’s life easier, early versionswere not without cost MFC applications were much larger than a non-MFC equivalent They tended to run slower as well (probably becausethey were so much larger ) And whenever it was necessary to stretchthe MFC envelope a bit, a working knowledge of the Windows API wasstill a prerequisite
MFC has gone through many iterations since version 1 was released.The current revision of MFC is version 6 MFC added the Document/Viewarchitecture in version 2, ODBC and drag-and-drop support in version2.5, and multithreading and Unicode support in version 3 Subsequentreleases have added support for socket classes, Internet classes, OLE
Trang 35collection of support classes such as arrays, lists, and strings, to name afew
Over the years, I’ve used MFC on many projects One of the most
rewarding of those endeavors was being part of the software
development team for Qualcomm’s Eudora versions 3 and 4 We usedMFC extensively in the creation of the Windows version of that product
The real world still holds challenges for programmers! MFC has not
changed that; MFC is still supplied with source code for good reason Butwithout MFC, I believe developing Eudora would have been a much moredifficult and time-consuming task MFC allowed us to build a product thatconformed to Windows GUI standards, incorporated new and improveduser interface metaphors, and ran with a high degree of independence onmany versions of operating systems and hardware platforms MFC alsosaved time when constructing non-GUI data structures and objects used
by the internals of Eudora
This book is an authoritative reference document that describes MFC:what it is and how to get the most out of it This book is written by
programmers for programmers It is filled with sample applications andcode snippets to clarify and demonstrate the use of MFC 6 If you arenew to MFC, this book will get you up to speed quickly If you are familiarwith MFC but need to drill down into the details of a specific MFC class,this book will be quite valuable as well This book can also be used as acompanion to the Microsoft documentation, which is typically quite goodbut perhaps a bit terse in spots
Trang 36Eugene Olafsen has been working with Microsoft Windows since the 3.0
release At that time, he was attempting to build a product using DigitalResearch’s GEM (Graphics Environment Manager), decided to port toWindows, and has never looked back He has worked with MFC/OLEsince its humble beginnings Gene has worked to develop applicationsranging from engine test simulators for Boeing to search and publishingsystems for Reuters He is an independent consultant and a principalpartner in Stratton & Associates, Ltd (www.strattonassociates.com), asoftware-engineering firm His current projects include application
development that leverages COM and Web technologies
Kenn Scribner actually began his career in computers in 1980 as a
pizzeria manager After he realized he didn’t want to make pizzas for aliving, he joined the Air Force as a computer operator Two degrees and acommission later, he found himself designing silicon-based Fast FourierTransform processors and running a research flight simulation facility Asthe Air Force downsized, he retired and began writing Windows
applications (He’s delighted to earn a living with his previous hobby!)Kenn has written several commercial Windows applications, and he nowfinds himself writing all the client user interface code and major ATL-
based COM components for a large-scale n-tier client/server application.Kenn also started his own company, the EnduraSoft Corporation
(http://www.endurasoft.com), writes the “Windows Programming” columnfor “TechTalk”—the newsletter of the Small Computer Book Club
(http://www.booksonline.com)—and acts as a Windows programmingtechnical reviewer for several publishers In his dwindling spare time,Kenn enjoys the company of his lovely wife and two wonderful children,works with his horse, remodels parts of his house, and generally acts asEnduraSoft’s chief groundskeeper Kenn can be reached at
kenn@endurasoft.com
K David White has been developing software since 1981, using a wide
variety of products, platforms, and languages During this time, Daveimplemented several systems, ranging from a facilities security systembased on DEC MACRO-32 to several large supervisory control systems
Trang 37Michael Morrison is a writer, developer, toy inventor, and author of a
variety of books including Sams Teach Yourself MFC in 24 Hours (Sams Publishing, 1999), Windows 95 Game Developer’s Guide Using the
Game SDK (Sams Publishing, 1997), Complete Idiot’s Guide to Java 1.2
(Que Corporation, 1998), and Java 1.1 Unleashed (Sams Publishing,
1997) Michael is also the instructor of several Web-based courses,
including DigitalThink’s Win32 Programming series, the Introduction toJava 2 series, and the JavaBeans for Programmers series Michael cuthis teeth on Windows programming by codeveloping one of the first
action games for Windows, Combat Tanks When not glued to his
computer, risking life and limb on his skateboard, or watching movies withhis wife, Mahsheed, Michael enjoys hanging out by his koi pond
of software design and development, with a strong emphasis on the
practical application of client/server technology Davis is the lead author
of Sams Teach Yourself Visual C ++ 6 in 21 Days, Web Development with Visual Basic 5, and Building Internet Applications with Delphi 2 Davis is
also a contributing author on Special Edition Using Active Server Pages and Running a Perfect Web Site, Second Edition He has been a
consultant working and living in Dallas, Texas, for the past ten years and
Trang 38Keith McIntyre has been developing software since the days of 4-bit
processors He has watched and participated in the personal computer,local area network, client/server, and Internet evolutions During his years
as a consultant/contract engineer, Keith has worked on a myriad of
technologies, including turbine engineer control systems, satellite
communication systems, tape drive firmware, UNIX and Windows devicedrivers, imaging and document management software, and custom
application development Keith has contributed to many shrink-wrap
software products including those published by Optigraphics, EmeraldSystems, Compton’s New Media, and Qualcomm Keith is currently vicepresident of engineering for Stellcom’s Internet Systems division Keith
Trang 39Rob McGregor began exploring computer programming in BASIC as a
teenager in 1978 Since then, Rob has worked as a programmer,
software consultant, and 3D computer artist; he has written a variety ofprograms for Microsoft and numerous other companies Rob lives in
—Gene Olafsen
If there was a time not to write a book, it was while I was writing this one.
My wife was studying for medical school entrance, my current project atwork wanted to consume all my time and then some, and my children
were very, very young (miss a day and you miss a lot) I couldn’t forget to
thank them for their sacrifice so that I could make this effort I would alsolike to thank the terrific team at MCP, especially Chris Webb, who put upwith this cranky author (I was, too; just ask him.) I would like to extendmost heartfelt thanks to Keith Davenport, Dana Lesh, and Margaret
Berson, all at MCP It was they who had to read my raw material and fire
it in the crucible of experience to produce the fine product you hold inyour hands And thanks to the nameless (to me) crew, who tirelessly setthe type, adjusted the margins, and actually put my words to paper From
Trang 40dollar I hope you enjoy reading it and find it tremendously useful in yourdaily work
—Kenn Scribner
There are so many people that have been supportive through the writing
of this book I want to thank Chris Webb of Macmillan Publishing for
being extremely patient during this ordeal Writing a book about a topicthat has a plethora of coverage already is no easy task Coupling thatwith the demands of a job and family leads to very long nights and
extended schedules Even though the publishing deadlines loomed large
in the rear-view mirror, Chris remained supportive during the entire effort
He was also responsible for tracking down contributing authors Anotherperson that needs recognition is my mother I would like to thank her forhelping me through school all those years ago Her sacrifices to her
family have paid off in dividends that cannot be described by mere words.Thanks, Mom! I would also like to thank Kenn Scribner for his
contribution to this effort and his insight into helping me put together thetable of contents His daily support and encouragement helped me copewith the daily pressures If you need an ActiveX guru, Kenn is your man!But, most of all, I want to thank the love of my life, my wife, for allowing
me to put myself into this work The late nights and missed opportunitiescan never be regained, and I just want to tell my family how much I lovethem!
—K David White
Dedication
To my wife, Donna, for her love, encouragement, and understanding— and to my children, Ashley and Eric, for the insight and wisdom they offer, beyond their years.
—Gene Olafsen
This, my first book, is lovingly dedicated to my wife, Judi, and to my
children, Aaron and Katie.