1. Trang chủ
  2. » Khoa Học Tự Nhiên

Programming microsoft visual c++ 5ed 1998

2K 73 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 1.965
Dung lượng 3,93 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Ever since Microsoft released the Active Template Library ATL as part of Visual C++, Windows developers have speculatedthat the Microsoft Foundation Class Library MFC was no longer "en v

Trang 1

Copyright© 1998 by David J Kruglinski

Trang 3

CIPPrinted and bound in the United States of America.

Trang 4

I first met David Kruglinski at a software development

conference I had just quit my job and started a new company,and I approached David at an author signing for an earlier

edition of this book Our new company was going to focus onMicrosoft Foundation Class (MFC)/Microsoft Visual C++ classlibraries I hoped that David would listen to our ideas and

maybe provide some feedback on our products and their

usefulness to the Visual C++ development community—a

community that he had both helped to build and understood likethe back of his own hand

Much to my surprise, David was very excited about the productideas and asked if I could send him evaluation copies of our

products I did, and we started a long e-mail conversation aboutour products and ideas for improvements David gave his time,expertise, and great opinions freely, without ever asking for anycompensation—he genuinely wanted to help us make productsfor the Visual C++ developer that would make MFC/Visual C++better

I first heard about David's fatal paragliding accident via a

posting on a newsgroup and initially thought it was some kind

of cruel hoax I called David's agent, who checked into the

story, and much to my shock it was true With David's passing,the Visual C++ community has lost one of its brightest and

most giving stars Talk to any Visual C++ developers about howthey first learned Visual C++ and invariably they will say, "theKruglinski book!" The Visual C++ community owes David

greatly for what he gave us and taught us about Visual C++over the years It goes without saying that he should receivespecial acknowledgment for this book, and our thoughts go out

to his family and friends for their loss

It is a great honor to carry on the Kruglinski tradition with this

fifth edition of Inside Visual C++ (now called Programming

Trang 5

stay true to David's vision of this book, following his format andstyle as closely as possible

Thanks to my wife Kris and to my son, Sean, for putting up withall of the late nights and weekends of writing Many thanks also

go to my coauthor, George Shepherd, who always helps me getmotivated for a late night of book writing with his upbeat,

wacky, and great personality Thanks to Claire Horne, our

agent, for helping us get on board with the project

Visual C++, and therefore this book, wouldn't exist if not forthe many members of the Visual C++ team Special thanks toMike Blaszczak, Walter Sullivan, Dean McCrory, Rick Laplante,Marie Huwe, Christian Gross, and Jim Springfield for all of thehelp they have provided over the years

Finally, but not least, thanks to the folks at Microsoft Press whoworked on this project—especially Kathleen Atkins, Jim Fuchs,Becka McKay, John Pierce, Jean Ross, Eric Stroo, and the entireproduction team who worked extremely hard to get this largebook out and into your hands with the highest quality possible

—Scot Wingo

Much work goes into writing books—even revisions of existingwork I'd like to acknowledge the following people for helping

me get this work out the door: First I'd like to thank my wifeSandy for sticking with me while I worked to get the pages andchapters out Sandy has been an invaluable source of

encouragement throughout my software endeavors Thanks to

my son, Teddy, for being patient with me as I bowed out onvarious activities every once in a while I wish to thank my

mother Betsy for engendering in me a desire to write and mytwin brother Patrick for being a great Java foil for me—and forarguing cogently with me about various hardware and software

Trang 6

Getting a book out involves more than just authors I wish tothank everyone at Microsoft Press who helped kick

Programming Microsoft Visual C++, Fifth Edition out the door,

especially Eric Stroo for his kindness and patience, KathleenAtkins and Becka McKay for sifting through our text and making

it ever more readable, Jean Ross for balancing out the technicalreview to catch even the most minute error, and John Pierce forkeeping everything on track

Finally, thanks to David Kruglinski for starting this project

While I never had the opportunity to meet David, his writinghad a measuable impact on me when first learning MFC I hopeScot and I did justice to the work you began

—George Shepherd

Trang 7

IntelliSense, AutoComplete, and code tips These features takeVisual C++ to a new level We have tried to make sure that thisbook keeps you up to speed on the latest technologies beingintroduced into Visual C++

Trang 8

Ever since Microsoft released the Active Template Library (ATL)

as part of Visual C++, Windows developers have speculatedthat the Microsoft Foundation Class Library (MFC) was no longer

"en vogue" at Microsoft and that future efforts would focus onnewer libraries such as ATL Recently, Microsoft released

another class library, Windows Foundation Classes (WFC), forJava Windows developers, which has unfortunately helped tofan the rumors that "MFC is dead."

The rumors of MFC's demise are definitely premature VisualC++ 6.0 has added significant functionality to MFC and ATL inparallel, which indicates that both libraries will receive equalattention moving forward Part of the problem is that the designgoals of each library are sometimes not clearly stated and

therefore are not clearly understood by the Visual C++

developer MFC is designed to be a great class library for

creating graphically rich, sophisticated Windows applications.ATL is designed to make it easy to create extremely lightweightCOM objects and ActiveX controls Each of these design goalshas resulted in a different library to empower the developer

Another common misconception is that MFC and ATL are

mutually exclusive This is definitely not the case! In fact, it isvery easy to create ATL-based COM objects that use MFC Theonly issue is that since many developers choose ATL for its

lightweight nature, using MFC, which is feature-rich and

"heavy," seems to contradict the reason for choosing ATL Whilethis might be the case for some developers, it doesn't make ATLand MFC mutually exclusive

While ATL does not replace MFC, we do think it is an important

part of Visual C++, so in this edition of Programming Microsoft

Visual C++ we have added two chapters that cover the ATL

class libraries

Trang 9

In the last couple of years, there has been a great deal of

interest in the Java programming language Why should youchoose C++ over Java? In the first place, a compiled programwill always be faster than an interpreted program Think about

a high-performance spreadsheet program with cell formulas andmacros Now imagine the Java virtual machine interpreting thecode that, in turn, interprets the formulas and macros Not

pretty, is it? With just-in-time compilation, it's necessary to

compile the program every time you load it Will that code be asgood as the optimized output from a C++ compiler?

Execution speed is one factor; access to the operating system isanother For security reasons, Java applets can't perform suchtasks as writing to disk and accessing serial ports In order to

be platform-independent, Java application programs are limited

to the "lowest common denominator" of operating system

features A C++ program for Microsoft Windows is more flexiblebecause it can call any Win32 function at any time

Java will be an important language, but we believe it's just

another language, not a revolution If you need an Internet

applet or a truly platform-independent application, choose Java

If you need efficiency and flexibility, choose C++

Trang 10

The product name "Visual C++" misleads some people Theythink they've bought a pure visual programming system similar

to Microsoft Visual Basic, and for the first few days the illusionpersists However, people soon learn that they must actuallyread and write C++ code The Visual C++ wizards save timeand improve accuracy, but programmers must understand thecode that the wizards generate and, ultimately, the structure ofthe MFC library and the inner workings of the Windows

operating system

Visual C++, with its sophisticated application framework, is forprofessional programmers, and so is this book We assume that

you're proficient in the C language—you can write an if

statement without consulting the manual And we assume thatyou've been exposed to the C++ language—you've at least

taken a course or read a book, but maybe you haven't writtenmuch code Compare learning C++ to learning the French

language You can study French in school, but you won't be able

to speak fluently unless you go to France and start talking topeople Reading this book is like taking your trip to France!

We won't assume, however, that you already know Windowsprogramming We're sure that proficient C programmers canlearn Windows the MFC way It's more important to know C++than it is to know the Win32 application programming interface(API) You should, however, know how to run Windows and

Windows-based applications

What if you're already experienced with the Win32 API or withthe MFC library? There's something in this book for you too.First you'll get some help making the transition to Win32

programming Then you'll learn about new features such as

Data Access Objects (DAO), ActiveX control container support,and the controls introduced with Windows 95 If you haven'talready figured out the Component Object Model (COM), this

Trang 11

on understanding ActiveX Controls You'll also learn about theATL class library, the new Microsoft Internet Explorer 4.0

common controls, and OLE/DB database programming Finally,you'll learn C++ programming for the Internet (including thehot new topic Dynamic HTML) We've even included coverage

on how to make your Visual C++ programs work on the newWindows CE operating system

Trang 12

It's not possible to cover every aspect of Windows-based

programming in a single book We exclude topics that depend

on special-purpose hardware and software, such as MAPI, TAPI,and communications port access We do cover using ActiveXcontrols in an application, but we'll defer the subject of writing

Internals by George Shepherd and Scot Wingo (Addison-Wesley,

1996)

Trang 13

When you're starting with Visual C++, you can use this book as

a tutorial by going through it sequentially Later you can use it

as a reference by looking up topics in the table of contents or inthe index Because of the tight interrelationships among manyapplication framework elements, it wasn't possible to cleanlyisolate each concept in its own chapter, so the book really isn't

an encyclopedia When you use this book, you'll definitely want

to keep the online help available for looking up classes and

member functions

If you're experienced with the Win16 version of Visual C++,scan Part I for an overview of new features Then skip the firstthree chapters of Part II, but read Chapters 6 through 12, whichcover elements specific to Win32

Trang 14

As the table of contents shows, this book has six parts and anappendix section

Trang 15

Framework Fundamentals

In this part, we try to strike a balance between abstract theoryand practical application After a quick review of Win32 and theVisual C++ components, you'll be introduced, in a gentle way,

to the MFC application framework and the document-view

architecture You'll look at a simple "Hello, world!" program,built with the MFC library classes, that requires only 30 lines ofcode

Trang 16

The MFC library documentation presents all the application

framework elements in quick succession, with the assumptionthat you know the original Windows API In Part II, you're

confined to one major application framework component—theview, which is really a window You'll learn here what

experienced Windows programmers know already, but in thecontext of C++ and the MFC library classes You'll use the

Visual C++ tools that eliminate much of the coding drudgerythat early Windows programmers had to endure

Part II covers a lot of territory, including graphics programmingwith bitmaps, dialog data exchange, ActiveX control usage, 32-bit memory management, and multithreaded programming Theexercises will help you to write reasonably sophisticated

Windows-based programs, but those programs won't take

advantage of the advanced application framework features

Trang 17

This part introduces the real core of application framework

programming—the document-view architecture You'll learn

what a document is (something much more general than a wordprocessing document), and you'll see how to connect the

document to the view that you studied in Part II You'll be

amazed, once you have written a document class, at how theMFC library simplifies file I/O and printing

Along the way, you'll learn about command message

processing, toolbars and status bars, splitter frames, and

context-sensitive help You'll also be introduced to the MultipleDocument Interface (MDI), the current standard for Windows-based applications

Part III also contains a discussion of dynamic link libraries

(DLLs) written with the MFC library You'll learn the distinctionbetween an extension DLL and a regular DLL If you're used toWin16 DLLs, you'll notice some changes in the move to Win32

Trang 18

COM by itself deserves more than one book Part IV will get youstarted in learning fundamental COM theory from the MFC point

of view You'll progress to Automation, which is the link

between C++ and Visual Basic for Applications (VBA) You'llalso become familiar with uniform data transfer and structuredstorage, and you'll learn the basics of compound documentsand embedded objects

Trang 19

Windows-based programs often need access to information inlarge databases Visual C++ now supports two separate

database management options: Open Database Connectivity(ODBC) and Data Access Objects (DAO) Part V offers a chapter

on each option You'll learn about the extensive MFC and wizardsupport for both options, and you'll see the differences betweenand similarities of ODBC and DAO We'll also cover a new dataaccess technology, OLE/DB, which is supported by ATL OLE/DBconsumer and providers

Trang 20

This part starts with a technical Internet tutorial that covers theTCP/IP protocol plus the Winsock and WinInet APIs You'll learnhow to write C++ server and client programs for the Internetand the intranet, you'll learn how to write ISAPI DLLs that

extend the Microsoft Internet Information Server, and you'lllearn how to program for Dynamic HTML We've also includedcoverage on Windows CE in this section

Trang 21

Appendix A contains a list of message map macros and theircorresponding handler function prototypes ClassWizard usuallygenerates this code for you, but sometimes you must makemanual entries

Appendix B offers a description of the MFC application

framework's runtime class information and dynamic creationsystem This is independent of the RTTI (runtime type

information) feature that is now a part of ANSI C++

Trang 22

Lots of old computers out there are still running Windows 3.1.However, there's not much point in spending money writing new

programs for obsolete technology This edition of Programming

Microsoft Visual C++ is about 32-bit programming for Microsoft

Windows 95, Microsoft Windows 98, and Microsoft Windows NTusing the Win32 API If you really need to do 16-bit

programming, find an old copy of the second edition of this

book

Trang 23

Windows NT

Visual C++ version 6.0 requires either Windows 95, Windows

98, or Windows NT version 4.0 or later, all of which have thesame user interface We recommend that you use Windows NT

as your development platform because of its stability—you canoften go for months without rebooting your computer If youuse only the MFC programming interface, your compiled

programs will run under Windows 95, Windows 98, and

Windows NT, but a program can include Win32 calls that usespecific Windows 98 or Windows NT features

Trang 24

throughout the text, help you make the connection to low-levelprogramming for Windows These specially formatted boxeshelp experienced C programmers relate new MFC library

concepts to principles they're already familiar with If you'reunfamiliar with low-level programming, you should skip thesenotes the first time through, but you should read them on yoursecond pass through the book Even though you may never

write a low-level Windows-based program with a WinMain

function, for example, you eventually need to know how theWindows operating system interacts with your program

Trang 25

The companion CD-ROM bound inside the back cover of thisbook contains the source code files for all the sample programs.The executable program files are included, so you won't have tobuild the samples that you're interested in To install the

companion CD-ROM's files, insert the disc in your CD-ROM driveand run the Setup program Follow the on-screen instructions

The Setup program copies about 30 MB of files to your

hard disk If you prefer, you can manually install only thefiles for individual projects Simply tree-copy the

Trang 26

With a conventional C-language program using the WindowsAPI, the source code files tell the whole story With the MFClibrary application framework, things are not so simple

AppWizard generates much of the C++ code, and the resourcesoriginate in the resource editors The examples in the early

chapters of this book include step-by-step instructions for usingthe tools to generate and customize the source code files You'd

be well advised to walk through those instructions for the firstfew examples; there's very little code to type For the middlechapters, use the code from the companion CD-ROM but readthrough the steps in order to appreciate the role of the resourceeditors and the wizards For the final chapters, not all the

ROM's files for those examples

source code is listed You'll need to examine the companion CD-For Win32 Programmers: Unicode

Until recently, Windows-based programs have used onlythe ANSI character set, which consists of 256 single-bytecharacters Developers targeting the Asian software

Trang 27

declare character pointers and arrays—for example,

TCHAR and _T.

You'll hit a snag, though, if you try to run your MFC

Unicode applications under Windows 95 or Windows 98,because they don't support Unicode internally Even

though Windows 95 and Windows 98 have wide-character versions of Win32 functions, those functionsreturn a failure code Windows NT, on the other hand,uses Unicode internally and has two versions of the

Win32 functions that deal with characters If you call asingle-byte version, Windows NT makes the necessaryconversions to and from wide characters

None of the sample programs in this book are configuredfor Unicode All the programs use single-byte types such

as char and single-byte string constants, and they do not define _UNICODE If you run the samples under

Windows NT, the operating system will do the necessarysingle-to-wide conversions; if you run them under

byte

Windows 95 or Windows 98, the interface is pure single-One area in which you're forced to deal with wide

characters is COM All non-MFC COM functions (exceptDAO functions) that have string and character

Trang 29

The MSDN Library for Visual Studio 6.0 contains technical notesand sample programs that are referenced in this book The

technical notes, identified by number, are available from theContents tab under the heading:

Visual C++ Documentation

Samples

MFC Samples

Trang 30

Every effort has been made to ensure the accuracy of this bookand the contents of the companion disc Microsoft Press

provides corrections for books through the Web at:

http://mspress.microsoft.com/mspress/support/

If you have comments, questions, or ideas regarding this book

or the companion disc, please send them to Microsoft Pressusing postal mail or e-mail:

Microsoft Visual C++, you can call the technical support line at(425) 635-7007 weekdays between 6 a.m and 6 p.m Pacifictime Microsoft also provides information about Visual C++ at

http://www.microsoft.com/visualc/ and about the Microsoft

Developer Network at http://www.microsoft.com/MSDN/

Trang 31

Chapter 1

Trang 33

No matter which development tools you use, programming forWindows is different from old-style batch-oriented or

transaction-oriented programming To get started, you need toknow some Windows fundamentals As a frame of reference,we'll use the well-known MS-DOS programming model Even ifyou don't currently program for plain MS-DOS, you're probablyfamiliar with it

Trang 34

When you write an MS-DOS-based application in C, the only

absolute requirement is a function named main The operating system calls main when the user runs the program, and from

program written for MS-DOS and a program written for

Windows is that an MS-DOS-based program calls the operatingsystem to get user input, but a Windows-based program

processes user input via messages from the operating system

Many development environments for Windows, includingMicrosoft Visual C++ version 6.0 with the Microsoft

Trang 35

WM_CLOSE message is sent when the user closes a window Allmessages have two 32-bit parameters that convey informationsuch as cursor coordinates, key code, and so forth Windowssends WM_COMMAND messages to the appropriate window inresponse to user menu choices, dialog button clicks, and so on.Command message parameters vary depending on the

window's menu layout You can define your own messages,which your program can send to any window on the desktop.These user-defined messages actually make C++ look a littlelike Smalltalk

Don't worry yet about how these messages are connected toyour code That's the job of the application framework Be

aware, though, that the Windows message processing

requirement imposes a lot of structure on your program Don'ttry to force your Windows programs to look like your old MS-DOS programs Study the examples in this book, and then beprepared to start fresh

Trang 36

Many MS-DOS programs wrote directly to the video memoryand the printer port The disadvantage of this technique wasthe need to supply driver software for every video board andevery printer model Windows introduced a layer of abstractioncalled the Graphics Device Interface (GDI) Windows providesthe video and printer drivers, so your program doesn't need toknow the type of video board and printer attached to the

system Instead of addressing the hardware, your program callsGDI functions that reference a data structure called a devicecontext Windows maps the device context structure to a

physical device and issues the appropriate input/output

instructions The GDI is almost as fast as direct video access,and it allows different applications written for Windows to sharethe display

Trang 37

To do data-driven programming in MS-DOS, you must eithercode the data as initialization constants or provide separatedata files for your program to read When you program for

Windows, you store data in a resource file using a number ofestablished formats The linker combines this binary resourcefile with the C++ compiler's output to generate an executableprogram Resource files can include bitmaps, icons, menu

definitions, dialog box layouts, and strings They can even

include custom resource formats that you define

You use a text editor to edit a program, but you generally usewysiwyg (what you see is what you get) tools to edit resources

If you're laying out a dialog box, for example, you select

elements (buttons, list boxes, and so forth) from an array oficons called a control palette, and you position and size theelements with the mouse Microsoft Visual C++ 6.0 has

graphics resource editors for all standard resource formats

Trang 38

With each new version of Windows, memory management getseasier If you've heard horror stories about locking memoryhandles, thunks, and burgermasters, don't worry That's all inthe past Today you simply allocate the memory you need, andWindows takes care of the details Chapter 10 describes currentmemory management techniques for Win32, including virtualmemory and memory-mapped files

Trang 39

In the MS-DOS environment, all of a program's object modulesare statically linked during the build process Windows allowsdynamic linking, which means that specially constructed

libraries can be loaded and linked at runtime Multiple

applications can share dynamic link libraries (DLLs), which

saves memory and disk space Dynamic linking increases

program modularity because you can compile and test DLLsseparately

Designers originally created DLLs for use with the C language,and C++ has added some complications The MFC developerssucceeded in combining all the application framework classesinto a few ready-built DLLs This means that you can statically

or dynamically link the application framework classes into yourapplication In addition, you can create your own extensionDLLs that build on the MFC DLLs Chapter 22 includes

information about creating MFC extension DLLs and regularDLLs

Trang 40

Early Windows programmers wrote applications in C for the

Win16 application programming interface (API) Today, if youwant to write 32-bit applications, you must use the new Win32API, either directly or indirectly Most Win16 functions have

Win32 equivalents, but many of the parameters are different—16-bit parameters are often replaced with 32-bit parameters,for example The Win32 API offers many new functions,

including functions for disk I/O, which was formerly handled byMS-DOS calls With the 16-bit versions of Visual C++, MFC

programmers were largely insulated from these API differencesbecause they wrote to the MFC standard, which was designed towork with either Win16 or Win32 underneath

Ngày đăng: 25/03/2019, 17:11

TỪ KHÓA LIÊN QUAN