1. Trang chủ
  2. » Kỹ Thuật - Công Nghệ

Software Solution for Engineers and Scientist Episode 6 pdf

90 340 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

Tiêu đề Software Solution for Engineers and Scientist Episode 6
Thể loại Tài liệu
Định dạng
Số trang 90
Dung lượng 1,05 MB

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

Nội dung

16.3 The C++ Console Application Microsoft Visual C++ provides a text-based program type that is useful in developingC++ programs that do not require a graphical user interface.. Since W

Trang 1

oriented facilities The enhancement ended up including classes, virtual functions,

a single line comment style, operator overloading, improved type-checking, ple inheritance, template functions, and some degree of exception handling TheC++ programming was standardized in 1998 as ISO/IEC 14882:1998 The current ver-sion dates from 2003

multi-During its evolution many libraries have been added to the C++ language One

of the first ones was (named iostream) provided much needed stream-level inputand output functions The new operators named cin() and cout() replaced themore awkward C functions named printf() and scanf()

16.0.2 Advantages of the C++ Language

The following are the most often cited advantages of C language:

1 C++ is not a specialized programming language, therefore, it is suitable for ing a wide range of applications, from major system program to minor utilities

develop-2 Although C++ is a relatively small language it contains all the necessary operators,data types, and control structures to make it generally useful

3 The language includes an abundant collection of library functions for dealing withinput/output, data and storage manipulations, system interface, and other primi-tives not directly implemented in the language

4 C++ data types and operators closely match the characteristics of the computerhardware This makes C++ programs efficient as well as easy to interface with as-sembly language programs

5 The C++ language is not tied to any particular environment or operating system Thelanguage is available on machines that range from microcomputers to mainframes.For this reason, C++ programs are portable, that is, they are relatively easy to adapt

to other computer systems

6 Object orientation is optional in C++ Applications that do not require object tation can turn-off this feature

orien-16.0.3 Disadvantages of the C++ Language

The following are the most often noted disadvantages of C++:

1 Because C++ is not a language of very high level, it is not the easiest to learn ners find that some constructions in C++ are complicated and difficult to grasp

Begin-2 The rules of C++ language are not very strict and the compiler often permits erable variations in the coding This allows some laxity in style which often leads toincorrect or inelegant programming habits

consid-3 Instead of being line C, a small and compact language, C++ has become large andcomplex

4 C++ library functions are devised to operate on a specific machine This sometimescomplicates the conversion of C++ software to other implementations or systems

5 The insecurities of C were not resolved in C++

Trang 2

16.1 PC Implementations of C and C++

Several software companies have developed C and C++ compilers for the PC Some ofthese products have gained and lost popular favor as other new versions or implemen-tations were introduced to the market Historically some of the better known imple-mentations of C for the PC were the Microsoft C and Quick C compilers, IBM C 2compiler (which is a version of Microsoft C licensed to IBM), Intel iC 86 and iC 286compilers, Borland Turbo C, Turbo C Professional, Lattice C, Aztec C, Zortech C, andMetaware High C

Currently C++ development systems have almost completely replaced the old Ccompilers The most popular ones are the Microsoft versions furnished as part ofDeveloper’s Studio usually referred to as Visual C++ The last version of Visual C++that did not include NET support was version 6 After version 6, the NET suffix wasadded to C++ compiler versions, thus Visual C++ NET in Developer’s Studio Ver-sion 7, Visual C++ NET 2003 and Visual C++ NET 2005 However, in the 2005 ver-sion the NET designation was removed and there is a Visual C++ 2005 version.Microsoft’s explanation for the name change is that the NET designation had leduser’s to believe that the 7.0 and 7.1 compilers were intended exclusively for NETdevelopment, which is not the case

Borland Corporation had developed and marketed several C++ systems for the

PC over the years The current version is Borland C++ Builder 2006 for MicrosoftWindows Two variations are available in the Borland product: the Professional andthe Enterprise editions

16.2 Flowcharts and Software Design

A set of logical instructions designed to perform a specific task is called a program.The document containing a set of instructions for starting a computer system could bedescribed as a power up program for a human operator By the same token, a computerprogram is a set of logical instructions that will make the computer perform a certainand specific task Note that in both cases the concept of a program requires a set of in-structions that follow a logical pattern and a predictable result A set of haphazard in-structions that lead to no predictable end can hardly be considered a program.Programmers have devised logical aids that help them make certain that com-puter programs follow an invariable sequence of options and their associated ac-tions One of the most useful of these aids is called a flowchart A flowchart is agraphical representation of the options and actions that form a program Flowchartsuse graphic symbols to enclose different types of program operations The mostcommon ones are:

1 Rectangle Used to represent processing operations such as arithmetic calculationsand data manipulations

2 Parallelogram Represents input and output functions, such as keyboard input, play, and printing operations

dis-3 Diamond Indicates a decision or logical comparison whose result is a yes or no

Trang 3

4 Circle Used to represent a program termination point such as the end of execution

Figure 16.1 A Machine Start-Up Flowchart

1 All computer components are directly connected to individual wall outlets

2 All computer components are connected to a power strip and the power strip is nected to the wall outlet

con-3 Some components are connected to a power strip and some are connected directly

to the wall outlets

Note in the flowchart of Figure 16.1 that the diamond flowchart symbols areused to represent program decisions These decisions correspond to the princi-ples of Aristotelian logic, therefore, there must be two and not more than two an-swers to the question These possible answers are usually labeled YES and NO in

to power strip

?

Turn-on individual component switches

Turn-on power strip and individual component switches Turn-on power

strip switch

Trang 4

the flowchart Decisions are the crucial points in the program’s logic A programthat requires no decisions or comparisons consists of such simple logic that aflowchart would be trivial and unnecessary For instance, a flowchart that consists

of three processing steps: start, solve problem, and end, is logically meaningless.Computing machines of the present generation are not equipped with humanlikeintelligence Therefore some assumptions that are obvious when dealing with hu-man beings are invalid regarding computers Computer programs can leave no looseends and make no assumptions of reasonable behavior You cannot tell a computer

“well, you know what I mean.” The programmer uses flowcharts to make certainthat each processing step is clearly specified

Regarding the flowchart graphics it should be noted that arrowheads are optional

in flowcharts if execution proceeds from the top down, as in Figure 16.1 However,

if execution flows up, to a higher flowchart level, then the connecting lines shouldhave arrowheads indicating the direction of program flow

16.3 The C++ Console Application

Microsoft Visual C++ provides a text-based program type that is useful in developingC++ programs that do not require a graphical user interface For example, an engineerrequires a small program to perform a set of numerical calculations If the application

is not to be distributed to other users and does not require graphics output, then theconsole application provides a simple way of developing a C++ program

To create a console application you must first start Visual C++ in Developer’s dio Once the development environment is displayed, select the New command inthe File menu This command displays the selection box shown in Figure 16.2

Stu-Figure 16.2 Visual C++ New File Command

Trang 5

Once the New File box is displayed you must make sure that the Project tab isactive and select the Win32 Console Application option towards the bottom of theProject Screen Next you enter the name of your project and its location in the ma-chine’s file system In this example we have named our project demo1 The button

to the right of the input box labeled “location:” allows browsing the machine’s filesystem

Once you click the OK button, the following screen contains several radio tons which allow selecting between an empty project, a simple application, a

but-“Hello, World” application, or an application that support MFC (Microsoft dation Classes) In this example we will select “A Simple Application” as shown inFigure 16.3

Foun-Figure 16.3 Selecting “A Simple Application” Option

Clicking the button labeled “Finish” produces a notification screen thatinforms the user that a skeleton project has been created, its name, and the pres-ence of two precompiled headers named “Stdafx.h” and “StdAfx.cpp.” Figure 16.4

is a screen capture of this notification

When you press the OK button execution returns to the main Visual Studioscreen This screen is divided into three panes The one on the right is the editor.The one at the bottom shows development operations and is called the Buildpane The pane at the left, called the Workspace pane shows the program compo-nents

The Workspace pane now shows two buttons on its bottom margin One, beled Class View, is currently selected This mode of the Workspace pane is used

la-in object-oriented development At this time you should click the button labeledFile View and then the plus sign (+) control to the left of the project files entry

Trang 6

This action will display the source, header, and resource files currently in the ject Also a ReamMe.txt file that contains information about the components of theconsole application that you have just created.

pro-Figure 16.4 Visual C++ New Project Information Screen

If you now expand the Source Files entry by clicking on its plus sign button a list

of two text files will be displayed The first one, named demo.cpp (assuming thatyou named your program “demo”) will be the source file created by Visual Studio.You can use this file as a start point for your program The file named StdAfc.cppcontains a single statement to include stdafx.h with your source You can viewstdafx.h by opening the Header Files group and double clicking the filename Figure16.5, on the following page, shows the Visual Studio screen at this point

You should now edit the source file to suit your own programming style and startcoding the console application The Build menu contains command to build the pro-gram (named Rebuild All) and to execute the code within the development environ-ment For example, the following code listing shows a modification of the simpleapplication file into a Hello, World program

Trang 7

Figure 16.5 Visual C++ Screen for a New Project

// demo.cpp

// First demonstration program for a console application

// Coded by: Julio Sanchez

Trang 8

17.0 Graphical Operating Systems

The operating systems used in the first generation of digital computers required thatthe user toggle a series of binary switches, each one with an attached light, in order toenter data into the machine In these systems, the bootstrap sequence consisted of apredefined sequence of switch-toggling and button-pressing actions which the opera-tor memorized and executed in a ritual-like fashion To handle one of these machinesyou had to belong to a select class of binary-speaking, hexadecimal-minded expertswho devoted most of their life to deciphering the arcane mysteries of hardware andsoftware

In the years that followed, several inventions and adaptations simplified puter input and output IBM Corporation, that had developed punched cards for itsbusiness machines, adapted this technology to its first line of computers Teletypemachines (called TTYs) had been invented for use in the communications industrybut were soon adapted for use as computer devices With the TTY, the typewriterkeyboard found its way into computing Next came the use of Cathode Ray Tubes,from commercial television, as a way of displaying text without having to print it onpaper An added bonus was that the CRT could also be used to display pictures.Other devices followed suit Some have become standard elements of the tech-nology while others have disappeared They include the lightpen, the touch screen,the graphic tablet, the joystick, and the mouse The common element in all of these

com-431

Trang 9

devices is that they allow the user to visually interact with the machine The ideafor an interactive input device came from the work of Allan Kay at the Xerox PaloAlto Research Center in the early 1970s Dr Kay was attempting to design a com-puter that could be used by preschool children, who were too young to read or totype commands in text form A possible approach was to use small screen objects,called icons, that represented a familiar thing A mechanical device (the mouse)allowed moving these graphics objects on the screen in order to interact with thesystem Interactive graphics and the graphical user interface were the result.Steve Wozniak, one of the founders of Apple computers, relates that he visitedXerox PARC and saw the mouse and the graphical user interface He immediatelyconcluded that the interactive way of controlling a computer was the way of thefuture Back at Apple, Wozniak started the development of an operating systemthat supported graphical, mouse-controlled, icon-based, user interaction Afterone or two unsuccessful tries, the Macintosh computer was released Soon there-after, Microsoft delivered a graphical operating system for the PC, called Win-dows.

17.1 Enter Windows

Many realized the advantages of a more reasonable and physical interaction with acomputing machine However, it took many years for the actual implementation ofthis idea in an effective operating system that would be preferred by the majority ofusers Douglas Engelbart demonstrated a viable mouse interface in 1968, but it tookfifteen years for the mouse to become a standard computer component In order toimplement a graphical user interface (GUI) it was necessary to have not only apointing device that worked but also a graphics-capable video terminal In addition,the software would have to provide a set of graphics services in a device indepen-dent manner

In the PC world, the evolution of hardware and software components into agraphical operating system took approximately one decade The first versionswere rather crude and achieved little popular acceptance It was not until Win-dows 95 that Microsoft’s graphical operating system for the PC became the stan-dard

Originally, the development of a graphical operating system for the PC was ajoint effort between Microsoft and IBM But soon, the two companies had majorstrategic and tactical differences IBM’s efforts resulted in a product called Oper-ating System/2, or OS/2 It seemed that Windows and OS/2 would share the PC op-erating system market However, for reasons unrelated to its technical merits,OS/2 quickly lost ground to Windows OS/2 Warp version 4.0 was on the marketuntil 2005 but is no longer sold by IBM

17.1.1 Text-Based and Graphical Programs

To a programmer, DOS and Windows are in different worlds DOS programs havecomplete and unrestricted access to the machine’s hardware Once the code gainscontrol it can do whatever it pleases Its only limitations are the hardware capabili-

Trang 10

ties and the programmer’s skills Although the designers of DOS-like operating tems often list rules that “well behaved programs” should follow, there is no way ofenforcing these rules Intentionally or by error a DOS program can raise havoc withthe system by deleting files from storage and even attempting to physically destroy ahardware device Each DOS application has total control over all system resources Itcan allocate all memory to itself, set whatever video mode is convenient, control theprinter and the communications lines, and manage the mouse and the keyboard Re-sources need not be shared since the operating system is dormant while an application

sys-is in the foreground In thsys-is environment, more than one application rarely execute multaneously

si-Windows applications must share resources between themselves and with the erating system Memory, CPU, display hardware, communications lines and devices,mouse, keyboard, and disk storage are all shared Each program operates in its pri-vate address space and has limited access to other memory areas Code cannot ac-cess the hardware devices directly but must to do so through operating systemservices called the Application Program Interface (API) This mechanism ensuresthat all programs are well behaved

op-Windows and DOS graphics programming are quite different Because all source are shared, Windows must control access to all devices and resources, in-cluding memory, the video system, communications devices, and input and outputcomponents Figure 17.1 shows how DOS and Windows programs access system re-sources

re-Figure 17.1 DOS and Windows Applications Access to System Resources

DOS application

Windows application

Windows API services

Trang 11

17.1.2 Graphics Services

Windows is a graphical operating system; therefore, a Windows application is agraphics program Since Windows applications use a graphical user interface, andconsidering that an application’s access to resources must be controlled, then Win-dows is forced to provide a host of graphics services to applications In a protectedmode environment, applications cannot access memory or devices directly If an ap-plication attempts to do so, the CPU notifies the operating system (Windows in thiscase) which proceeds first to halt and eventually to destroy the offending program.The general rule under Windows is behave or you will be destroyed The Windowsprogrammer has no direct control over the machine resources but the operating sys-tem provides services which allow supervised access

17.2 Programming Models

The nature of the operating system environment determines the programming els In DOS, a program is “the god of the machine.” The running code has unre-stricted access and control It executes on its own strengths, implements its ownfunctionality, and calls the operating system only to request a specific service Itshares the machine with no other program Therefore, the programming model for aDOS program is a set of sequential instructions and program constructs Controldoes not return to the operating system until the application terminates This form

mod-of interaction between the application and the operating system gives rise to the quential programming model

se-The conceptual model for a Windows program is quite different In this case,the code has no direct access to devices and resources and must share the ma-chine with other applications and with the operating system itself The currentversions of Windows implement preemptive multitasking This means that the op-erating system can switch the foreground (CPU access) from one application toanother If an application misbehaves, Windows can simply turn it off Therefore,

it is the operating system that is “the god of the machine,” not the running gram

pro-17.2.1 Event-Driven Programs

A new programming model is necessary to accommodate this mode of interactionbetween an application and the system code The model is sometimes calledevent-driven programming In event-driven programming, synchronization be-tween the operating system and the application is in the form of program events Forexample, when the user changes the size of an application’s window (a user event),the operating system takes the appropriate action and then notifies the applicationcode (a system event) The application, in turn, may decide to take its own action toupdate its display area, or it may decide not to take any action at all In either case, itreturns control to the operating system The event-driven model, although simpleand effective, can appear odd to a programmer used to working in DOS In the case

of a Windows program, the application’s code is no longer a sequential set of tions, but a series of blocks of code which execute when the corresponding message

instruc-is received

Trang 12

The event-driven model is implemented by means of messages passed among theparticipants In this example, we can say that in response to the user’s windowresizing event, the mouse device sent a message to the operating system, which inturn, sent a message to the application However, these messages are not like the in-terrupts so often used in DOS programming DOS interrupts can run concurrently;that is, a new interrupt can take place before the previous one has concluded Onthe other hand, Windows messages are queued and must wait in line until their turncomes for processing.

DOS programmers have to change their mindset when working in Windows ure 17.2 shows two models of programming: the sequential model in a DOS programand the event-driven model in a Windows programs In DOS, the application re-ceives control at load time and retains it during its entire life span In a Windowsprogram, a user input event sends a message to the operating system The operatingsystem takes the appropriate action and sends a message to the corresponding ap-plication The application looks at the message and decides if an action is required

Fig-or if the message should be ignFig-ored In either case, it returns control to Windows Attermination time, the application sends a message to Windows requesting to beended

Figure 17.2 Sequential and Event-Driven Programming Models

DOS

(message)

(message) DOS APPLICATION

WINDOWS APPLICATION [event handlers]

USER INPUT EVENT

WINDOWS OPERATING SYSTEM [event manager]

// program code

initialize

get_user_input:

if action required take action X

if program end return to DOS else

get_user_input action X:

action (X=1) get_user_input action (X=2) get_user_input

// end of program

// message processing switch (msg)

case 1:

application event 1 return

case 2:

application event 2 return

default:

return // send message msg=end execution return

Trang 13

The Event Manager

The principal difference between sequential and event-driven programs is that one

is active and the other one is passive Event-driven code need not provide loops tomonitor user input since this function is performed by Windows The applicationstays dormant until it is notified by the operating system that an event has takenplace It is the operating system code which must monitor the hardware devices inorder to detect actions which must be handled by the code This function is calledevent management, and Windows is the event manager

It is the event manager’s responsibility to detect events and to make sure thatapplications that must react to the events are promptly notified This is usuallycalled an event dispatch operation The event manager monitors hardware de-vices that can generate events, such as the keyboard and the mouse The softwareroutine that checks for action on the event generating devices is sometimes calledthe event loop

The Event Handler

In the event-driven model, the application is the event handler Its function is to waitfor an event to occur and then perform the corresponding action The event handlerdoes not monitor event-generating devices directly, and often does not provide thefirst level response to an event It simply performs the action or actions that arewithin its responsibilities and returns control to the event manager In Windows all

of the complications of the device interface are performed at the system level Inthis sense, event-driven programs are easier to code since the “dirty work” is done

by the operating system

17.2.2 Event Types

Events can be grouped into several types, although the classification is not very orous Often one event can be placed into one or another group according to ourown definitions However, three general groups can be delimited without muchoverlap:

exam-is thexam-is interconnection between related events that sometimes makes it difficult

to pinpoint a particular event type

System Events

In this group are those events that originate in the operating system software Forexample, if the user presses the left mouse button while the cursor is inside the cli-ent area, Windows sends a WM_LBOTTONDOWN message to the application This

Trang 14

message indicates to the application code that a certain action has taken place (or isabout to take place) to which, perhaps, the program should respond Many other sys-tem-generated events are possible, including a user typing on the keyboard, selecting

a menu item, moving the mouse cursor, dragging an object with the mouse, resizing awindow, or operating a scroll bar control

Control Events

Control events relate to graphics control objects that are so abundant in the Windowsenvironment Among them are buttons, list boxes, combo boxes, scroll bars, up-downcontrols, and many others A control event takes place when user interaction with acontrol requires a reaction from the operating system or the application In this case,the control sent a message to the operating system If necessary, the operating systemcan then generate an event to notify the application of the user’s action

Much of the programming required to implement a user interface consists of sponding to control events The reason is that Windows programs have availablemany standard controls Programmers usually find it more convenient to use one ofthese pre-canned components than to create a customized one Windows controlsare discussed in greater detail later in this chapter

re-Program Events

In Figure 17.1 we can see that the termination of a Windows application requires thatthe program code send the corresponding message to the operating system In thiscase, the application originates an event in the form of a request to terminate execu-tion This type of event is called a programmer-created or program event

17.2.3 Event Modeling

A program event is generated when the application code sends a message to the ating system requiring a service or action However, program events are rarely at theorigin of the event chain For example, the program event that requests program termi-nation often originates in a control event where the user indicated a desire to end theprogram Figure 17.3, on the following page, shows the event chain that takes placewhen a user clicks on the close button on a Window’s title bar

oper-In Figure 17.3 the message sent by the operating system to the application is beled WM_DESTROY This is one of many standard messages that are used by Win-dows The WM_DESTROY message indicates to an application that the operatingsystem has already destroyed the window Therefore, the WM_DESTROY message isreceived after the fact Another Windows message named WM_CLOSE is sent to anapplication to notify it that it is time to clean up and terminate WM_CLOSE is a sort

la-of warning This means that Figure 17.3 is actually a rough sketch la-of a processwhich actually entails several other steps

The Windows messaging system that results from event generation and handlingmechanisms can get quite complicated The programmer or program designer oftenneeds to create a model of an event chain Several modeling tools have been devel-oped for graphically depicting processes and data Data flow and entity-relationshipdiagrams are well-known tools used by program designers However, these conven-

Trang 15

tional tools are not well suited to modeling event-driven systems Ward and Mellorand also Hatley and Pribhai have introduced variations of the data flow diagramswhich are better suited for representing systems in which events take place inreal time In Figure 17.3 we have used symbols from conventional data flow dia-grams and from the Ward and Mellor extensions in order to model an event chain.More elaborate and detailed representations could include symbols for datastores, control stores, and for processes.

Figure 17.3 An Event Chain

17.3 File Structure of a Windows Program

In addition to adopting an event-driven programming model in replacement of theconventional sequential model, the Windows programmer also needs to become fa-miliar with the file structure of a Windows application Many DOS programs havesimple file structures In many cases, the only files external to the source are the var-ious include files listed in the program header Internally, the DOS compiler sets thenecessary linker options, references the corresponding libraries, and creates theexecutable almost transparently to the programmer Windows compilers are alsodesigned to automatically manage much of the complications of program genera-tion; however, Windows programs usually require more files than their DOS coun-terparts Several of these files have no equivalent in DOS systems

17.3.1 Source Files

The source files in Windows are of the same type as in DOS programming In eithercase, they contain the language statements and constructs of a C or C++ program.Specific filename extensions are associated with different source files type, these

system event

program

terminate program

cleanup

Trang 16

are: C, CPP, and H The C extension depicts a program in C The presence of this tension usually indicates that the program is coded in straight C; therefore, it does notinclude any keywords and constructs that are part of C++ The CPP extension indi-cates a source file that can contain C++-specific keywords and constructs The H ex-tension corresponds to a header file, usually referenced at the beginning of a program

ex-by means of the #include statement

17.3.2 Library Files

C and C++ are small languages: they do not provide functions for performing input andoutput operations For this reason, few useful programs in C or C++ contain no otherfunctions than those explicitly coded in the source Most DOS programs, and virtuallyall Windows programs, require the support of library functions

Library files differ from source files All the program files containing source codeare merged at compile time Library functions are incorporated at link time, al-though the internal mechanisms of C and C++ development systems sometimes pre-vent us from noticing the difference What often happens is that an #includestatement in a source file references a header file, which in turn, contains refer-ences to other sources or to object code in a library These references are usuallymade by means of the extern declarator which serves to indicate that a variable orfunction has external linkage Figure 17.4 shows the different source, object, and li-brary files that can be part of a C or C++ program

Figure 17.4 File Structure of a Windows Program

VENDOR.H

VENDOR.OBJ WINDOWS APPLICATION

DOS AND WINDOWS APPLICATIONS

WIN_LIB.DLL

USER2.CPP USER1.CPP

Trang 17

17.3.3 Resource Files

Windows programs have access to data items stored within the executable file, or in

a library file, called resources Although resources are data, and though they are ten associated with the program’s EXE file, they are unique In the first place, re-sources cannot be modified at run time They are actually read-only files and are notdirectly accessible to program code Furthermore, resources do not reside in theprogram’s data area At load time program resources are usually left on a disk fileuntil they are needed Typical resources are icons, cursors, dialog boxes, menus,bitmaps, and character strings.The current generation of software tools for devel-oping Windows applications, such as Microsoft Visual C++ and Borland C++, con-tain special tools for working with resources In the Microsoft system there areseveral specialized resource editors

of-Resources, which have no equivalent in DOS programming, provide several vantages to Windows applications:

ad-• User interface components are isolated from the rest of the code

• Applications can be modified without changing the resources

• Data can be shared among applications by reusing the same resources

• Graphical elements in the user interface can be created easily

• Graphical elements in the user interface can be modified without changing the cation code

appli-Several special file types are used by Windows to manage resources The source script file (extension RC) is an ASCII text file from which the binary re-sources are created Resource script files can be created manually by theprogrammer or they can be automatically generated by the resource facilities inthe development environment The Resource Compiler program, which is part ofthe development system, produces binary resource files (extension RES) fromthe ASCII script files (extension RC) In Microsoft Visual C++, the command lineversion of the Resource Compiler is named RC.EXE; in Borland C++ it is namedBRCC.EXE or BRCC32.EXE

re-Before Windows 95, the Resource Compiler also had the task of adding the nary resources to the executable file created by the linker The Microsoft linkerfor Windows 95 and later versions can directly manipulate files in both OBJ and.RES formats

bi-17.3.4 Make Files

During the evolution of software development systems, the component programsbecame increasingly more powerful Consequently, the number switches, options,and modes that could be selected in compilers, linkers and other tools also grewrapidly It became progressively more difficult for the programmer to rememberand enter all of these options every time that a project had to be compiled or up-dated Various forms of so-called make programs and utilities were developed toremedy this situation By means of a make program the programmer would record

Trang 18

all the switches and options in a text file and the make utility would automaticallyapply them in a particular project.

In DOS programming, the simplest implementation of a make utility is abatch file An additional refinement is a program that reads the switches andoptions selected in the development environment and applies them to the as-sembler, compiler, linker, or other software tools In most environments, theuse of the make program is optional; however, in the Windows platform the op-tions and controls are so intricate that most programmers would not considerentering them manually

All major Windows C and C++ development systems for the PC have a makeutility In Microsoft’s Visual C++, it is named NMAKE.EXE In the Borland sys-tem, it is MAKE.EXE The text file for either system has the extension MAK.Make files consist of instructions in ASCII text format They can be createdmanually or generated automatically by the development environment Themake programs can be entered from the command line or they can be activatedfrom inside the development environment, usually by selecting a specific menuoption

17.3.5 Object Files

The compiler program generates a file called an object file, which has the sion OBJ The Microsoft Visual C++ development system uses the Common Ob-ject File Format (COFF) specification which originated in the UNIX operatingsystem The Microsoft version of COFF adds additional header data in order tomake the format compatible with DOS and with 16-bit versions of Windows

exten-T h e c o m p i l e r s i n Wi n d o w s d e v e l o p m e n t s y s t e m s h a v e m a n y d i f f e r e n tswitches, options, and modes of operation selectable by the user In Visual C++,the compiler options are selected through the Settings command of the Buildmenu The Project Settings dialog box contains a C/C++ tab which activates thecompiler switches and controls, as shown in Figure 17.5, on the following page.Once the C/C++ tab is active in the Project Settings, a drop-down list box la-beled Category is displayed When the Category box is expanded (see Figure17.5), eight options appear Selecting any one of these options activates a dialogbox with a new set of selectable choices The Warning Level and Optimizationsdrop down list boxes are also shown in Figure 17.5 The compiler warning leveldetermines the severity of warnings for which the compiler generates a mes-sage Optimizations consist of four predefined modes: default, disable, maxi-mize speed, and minimize size In addition, an entry labeled Customize (notshown in Figure 17.5) is also in the list box Selecting this option activates an-other list box of customized optimizations when the Optimizations options inselected in the Category list box

Mastering all the compiler options and switches requires considerable rience with the development environment Programmers often use the defaultsettings and make modifications to these settings when necessary

Trang 19

Figure 17.5 Visual C++ the Compiler Options

oper-The linker is the tool that generates the executable file; however, the Windowsdevelopment environments can activate the linker functions indirectly In

Trang 20

Microsoft Visual C++, the CL program can be used to compile source files, or tocompile and then link object files into executables Make files can also reference thelinker operation As in the case of the compiler, there are considerable numbers ofswitches and options that can be selected at link time In Visual C++, the linker op-tions are activated through the Settings command of the Build menu The ProjectSettings dialog box contains a Link tab, as shown in Figure 17.6.

Figure 17.6 Visual C++ Linker Options

When the Link tab is active in the Project Settings, a drop-down list box labeledCategory is displayed Five options appear when the Category box is expanded (seeFigure 17.6) Selecting any one of these options activates a dialog box with a new set

of selectable choices

Learning all the linker switches and options requires a mastery of the ment system and as well as an intimate knowledge of the Windows operating sys-tem Here again, programmers often change the default linker options only whennecessary, but this attitude often results in sacrifices in functionality and perfor-mance

Trang 21

17.3.7 Dynamic Linking

One of the unique characteristics of Windows is dynamic linking In DOS the linkeroperates statically: it takes one or more object and library files and merges theminto an executable which physically includes all the code in both the sources and thelibrary modules Windows programs use conventional libraries and source files atlink time, but also a special type of file called a dynamic-link library or DLL In dy-namic linking, the library files are referenced at link time, but the code is not physi-cally incorporated into the executable When the program runs, the requiredrun-time libraries are loaded into memory and the references are resolved

Dynamic link libraries are binary files that have functions which can be shared

by several applications In addition to sharing code between applications, DLLscan be used to break up an application into separate components that are moremanageable and easier to upgrade Dynamic linking has several advantages:

• Several processes can share the same code thus saving memory space and reducingaccess time

• DLLs can be modified and upgraded independently of the applications that use them.Programs that use static libraries must be recompiled when the libraries are modi-fied This mechanism can be effectively used in providing after-sale support for a pro-gram

• DLLs can be accessed from different programming languages or environments aslong as the applications follows the calling conventions

There are also disadvantages associated with DLLs One of them is that thecode is not self-contained since it depends on the DLLs files being present on thetarget system If a process that uses load-time dynamic linking references a DLLthat is not available on the host machine, Windows immediately terminates theprogram In the case of applications that depend on run-time dynamic linking, theprogram is not terminated if the DLL is not loaded, but the functionality associ-ated with the missing DLL are not available to the code

Dynamic link libraries are stored in different formats and associated with ous filename extensions The standard extension is DLL but files with the exten-sion EXE, DRV, FON, and others can also perform as dynamic-link libraries Thesystem-level DLL files, such as KERNEL32.DLL, USER32.DLL, and GDI32.DLL,are found in the WINxx\SYSTEM directory Files with the extension DLL areloaded automatically by Windows Others must be explicitly loaded by the pro-gram module using the LoadLibary() or LoadLibaryEx() API functions

vari-In addition to DLLs, two other types of libraries and their associated files areused in Windows programming:

• Object libraries (extension LIB) contain object code that is added to the application

at link time Object libraries are used in static linking The standard C libraries namedLIBC.LIB and LIBCMT.LIB are in this group

• Import libraries (extension LIB) are a special form of an object library which tains no code Import libraries provide information to the linker regarding dy-

Trang 22

namic-link libraries Access to the dynamic link library GDI32.DLL is by means of theimport library named GDI32.LIB.

Trang 24

18.0 “Hello, World”

Experienced and talented DOS programmers are often intimidated by their first counter with Windows programs Windows programming has been described asweird, convoluted, and awkward In reality Windows programming is not more diffi-cult than DOS programming, although Windows programs, at first, appear more com-plicated

en-In the first place, Windows text-only programs can be coded using the ConsoleApplication facilities described in Chapter 16 Regarding programs that requiregraphics or a Graphical User Interface, then Windows programs are definitively eas-ier to design and code than their DOS counterparts Because Windows is a graphicsenvironment it contains a multitude of services, canned routines, and coding aidsthat are not available in DOS Anyone who has ever implemented a graphical user in-terface for a DOS application will greatly appreciate the graphics facilities in Win-dows

Kernighan and Ritchie, in their book The C Programming Language, (published

by Prentice-Hall in 1978) listed the code for a short program that displays the sage “hello, world!” on the screen This program has since been known as the HelloWorld program, and many other authors of programming books have followed suit.The C++ version of the Hello World program is as follows:

mes-447

Trang 25

pro-“glass teletype” that scrolls automatically when the text reaches the end of thescreen In this text-based paradigm there are no provisions for graphical user in-terface or for multitasking.

A Windows program that performs these same functions must deal with manyother levels of complexity In the first place, it must coexist and share resourceswith the operating system and with other applications In Chapter 17 we dis-cussed the model of an event-driven program that is necessary in this case In ad-dition, a Windows application is a graphics-based not a text-based program.Finally, the program executes as a window which can be overlapped, overlaid,minimized, maximized, to which keyboard and mouse input can be given or with-drawn, and many other functions As can be expected, the code is more lengthy,although it is relatively simple considering the functionality achieved The follow-ing is a listing for a Windows version of the Hello World program:

/********************************************************

WIN_HELLO.CPP Displays the message “Hello World from

Windows!" in the client area.

wndclass.lpfnWndProc = WndProc ;

wndclass.cbClsExtra = 0 ;

wndclass.cbWndExtra = 0 ;

wndclass.hInstance = hInstance ;

wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION) ;

wndclass.hCursor = LoadCursor (NULL, IDC_ARROW) ;

wndclass.hbrBackground = (HBRUSH) GetStockObject

(WHITE_BRUSH) ; wndclass.lpszMenuName = NULL ;

wndclass.lpszClassName = szAppName ;

wndclass.hIconSm = LoadIcon (NULL, IDI_APPLICATION) ;

// Registering the structure wmdclass

RegisterClassEx (&wndclass) ;

// CreateWindow()

Trang 26

“WIN_HELLO Program”, // window caption

WS_OVERLAPPEDWINDOW, // window style

1, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER) ;

EndPaint (hwnd, &ps) ; return 0 ;

case WM_DESTROY :

PostQuitMessage (0) ; return 0 ;

no-static char szAppName[] = “WinHello” ;

If you are a C or C++ programmer the statement itself is quite familiar: it is thedeclaration and initialization of a static array of type char What could strike you asunusual is the array name szAppName The identifier “szAppName” appears strange

Trang 27

because it follows the conventions recommended by Microsoft for variablenames Reputedly, this naming style originated with a Microsoft programmer ofHungarian descent named Charles Simonyi, and is, in his honor, called Hungariannotation.

Figure 18.1 The WIN_HELLO Program Screen

In Hungarian notation the variable name should provide a way for identifyingthe data type In szAppName the prefix sz stands for string terminated in zero Theword or words that follow the prefix describe the variable contents, in this casethe application name Table 18.1 lists the standard variable name prefixes recom-mended by Microsoft

The merits of Hungarian notation have been passionately debated Those whosupport it claim that it helps avoid data type mismatch errors The detractorsmention that linking the name and the data type forces the programmer to alterthe name whenever the data type is changed, which can lead to unnecessary pro-gram editing Also that Microsoft itself does not follow Hungarian notation con-sistently, there being many cases in which this style leads to confusion

Perhaps the most noted source of confusion caused by Hungarian notation isthe wParam passed to the Windows procedure (see WinProc in the WIN_HELLOprogram listing) In this case, wParam indicates a word according to the namingconvention, but when the Win32 API was developed, wParam was changed to a32-bit unsigned integer However, for consistency with older code, the Windowsdocumentation still refers to it as wParam

In principle, we agree that Hungarian notation creates more problems that itsolves However, deviating from it only makes things worse since Microsoft hasofficially adopted it in Windows and in the Visual C++ documentation In thisbook, we use Hungarian notation in the sample programs and the code listing,

Trang 28

specially when referring to Windows data types and structures In our own variables

we use it rather loosely, and only for the sake of simplicity and uniformity

Table 18.1

Standard Prefixes Recommended by Microsoft

(f stands for flag)

cx/cy INT count of x values and count of y values

pt POINT 32-bit coordinates, labeled x and

y, packed in a structure

in 32-bits as follows: 00BB GGRR

sz array of char string terminated in zero

Regarding function names, there is less reason for debate Microsoft suggeststhat programmers use a verb-noun model that describes what the function does andwhat it operates on: for example, the Windows API functions BeginPaint(),GetClientRect(), DrawText(), and EndPaint() referenced in the WIN_HELLO pro-gram listed earlier in this chapter The function name begins with a capital letter and

so does every other word in the function name The underscore is not used as a arator Since this style is familiar to most C and C++ programmers there is no reason

sep-to adopt a different one for our own functions

18.2 Constants and Handles

The Windows header files define many numeric constants which can be a source of wilderment to the uninitiated For example, in the WIN_HELLO program listed previ-

be-o u s l y, w e f i n d t h e u p p e r- c a s e i d e n t i f i e r s C S _ H R E D R AW, C S _ V R E D R AW,WS_OVERLAPPEDWINDOW, and CW_USEDEFAULT, among others These, andmany other identifiers, are used as placeholders for numeric constants The rationale

is that symbolic names are more significant than numeric values and that they can bechanged transparently to the code and the documentation Table 18.2 lists the mean-ing of some common prefixes used for numeric constants Many others are also used

by Windows functions

Trang 29

In this case, the value returned by the CreateWindow() call is a handle to a window

of the type HWND as defined in the windows.h header file After a handle has beenobtained it can be used to reference the object or data item that it represents For ex-ample, later in the listing of the WIN_HELLO program we see that the handle to theprogram’s window is used to obtain system information The call

GetClientRect (hwnd, &rect) ;

passes the handle to the Windows API function in order to retrieve the coordinates

of the windows client area, which are stored by the function in the structure able named rect In addition, Windows uses this same handle to identify a particularwindow to your program If your application has several windows open simulta-neously, it can tell to which of them the message refers, by examining the handle.DOS programmers first learn about handles in relation to disk files In DOS,there is little use for handles outside of disk files and standard devices Windowshandles, on the other hand, refer to many types of objects and resources in the en-vironment, including handles to windows, to strings, to icons, to menus, tocursors, to instances of a program, to graphical objects (including pens, brushes,fonts, and bitmaps), to dynamically allocated memory, to regions, and to colorpalettes Table 18.3 lists some of the more frequently used handles in Windowsprogramming

Trang 30

Table 18.3

Common Windows Handle Types

differ-18.3.1 The Main Window

Although it is possible for a Windows program to execute without output to the displaydevice, most Windows applications will have a main window The main window is aprogram’s principal means of input and output and its only access to the screen Figure18.2, on the following page, shows the basic components of a program’s main window.Some of the elements of the window in Figure 18.2 are present in all program win-dows, others must be present but can be configured in different ways, and a thirdgroup is optional The following are the fundamental building blocks of a programwindow:

• The main window display has a title bar, although the caption can be left blank

• The control buttons to the right of the title bar are used to minimize, maximize, andclose the program window The programmer can select which of these control buttonsare displayed

• The icon on the left side of the title bar activates the system menu Programs can use theWindows default icons or one of their own

• The menu bar is optional A typical menu bar contains one or more drop-down menus.Each drop-down menu consists of commands which are activated by a mouse click or

by using the Alt key and the underlined letter code Menu commands that expand intosubmenus are usually indicated by trailing ellipses

Trang 31

Figure 18.2 Elements of the Program Window

• The program main window, as well as many input/output controls, can have vertical

or horizontal scroll bars Windows notifies the application of user’s action on thescroll bars, but the application must provide the required processing

• Windows programs can have a status bar at the bottom of the screen which can tain a single text display area (as the one in Figure 18.2) or be divided into multiple ar-eas The status bar, as its name indicates, is used to display messages that inform theuser about the program’s status A status bar includes sizing grips on the right-handside which are used to change the window’s size

con-• The screen zone assigned to each program window is called the client area The mensions and graphics attributes of the client area can be obtained from the operat-ing system using the window’s handle

di-18.3.2 Controls

The window in Figure 18.2 contains several controls: the buttons on the title bar, themenu items and command, the sizing grip, the scroll bars, and the button that acti-vates the system menu Buttons, scroll bars, menu commands, and sizing grips arejust a few of the many control components that are available in Windows These

program icon and system menu menu bar vertical scroll bar

drop-down menu status bar sizing grip

horizontal scroll bar

title bar control buttons

Trang 32

graphical components that are used in implementing input/output operations are nerically called controls Some controls have been around since the original Windowsoperating system; others were added with the various versions and revisions; still oth-ers are furnished as add-on or after-market products.

ge-Controls are classified in two groups: predefined controls and common controls.The differences between them are mostly related to the message type used to com-municate with the application and to historical considerations Programmers cancreate their own customized controls and provide processing routines to operatethem In this section we refer to standard controls that are part of Windows; theseinclude: buttons, check boxes, edit boxes, list boxes, combo boxes, scroll bars, dia-log boxes, toolbars, ToolTips, status bars, tree views and tree lists, progress bars,up-down controls, trackbars, and many others Figure 18.3 shows some of the con-trols frequently used by Windows applications

Figure 18.3 Windows Program Controls

18.3.3 Other Visual Components

In addition to the input/output controls such as those shown in Figure 18.3, Windowsapplications have available a rich selection of additional program elements EveryWindows user is familiar with dialog boxes, list and tree views of files, tab controls,toolbars and ToolTips, and property sheets Wizards are used to assist the user in exe-cuting complex tasks Much of Windows programming is learning how to implementthese canned program components in your own code and adapt them to perform thetasks that your program requires

Trang 33

As we mentioned earlier in this chapter, Windows programming is not difficult

or profound, but many Windows programs end up being extremely complicated.Well-organized and commented sources let you quickly find the fundamental rou-tines and grasp the basics of the processing operations A good style promotes theorganization of the code into execution blocks and the use of comments to de-scribe the mechanism by which the program accomplishes its basic purposes Onthe other hand, program comments should not be used to explain the fundamen-tals of a programming language nor trivial or obvious manipulations Sometimes

we see a line of code that contains several flaws, for example:

int var1, var2 = 22; // Creating and initializing

// Variables

In this line, we can spot several style problems In the first place, modern gramming techniques advise that each variable be declared separately Multipledeclarations and initializations are possible in C and C++, but the code is clearer

pro-if you devote a single text line to each variable Another flaw in the sample line isthat the variable names are not indicative of their function in the program Finally,the comment is useless since any C programmer knows that the statement is avariable declaration

18.4.1 Commented Headers

One way to make sure that the necessary information is included in the source is touse a pre-designed comment block Software companies often furnish their pro-grammers with standard headers that are to be attached to all source files Theseheaders serve to remind the programmer of all the items of information that should

be included with each source file The following can be used as a checklist for mation that may be included in the program’s commented header block:

infor-• Developers copyright notice

• Program name

• Programmer or programmer’s name and other personal information

• Name of the source file

• List of related sources, program modules, and support files, including libraries,DLLs, and required add-ons

• Description of the development system and resources

• Program hardware and software requirements

Trang 34

• Program update chronology listing dates and modifications

• Program test history and bug fixes

The following is the commented header used by the author’s software company:

//************************************************************

//************************************************************

// Copyright (c) 20?? by Skipanon Software Associates

//************************************************************

//************************************************************

The jury is still out regarding the practical viability of formal methods of programspecification, but most programmers agree that it is a good idea to reduce the ambi-guity and inconsistency in the coding A semiformal method of specifications calledassertions notation has been progressively gaining favor It consists of a specific

Trang 35

style of comments that are inserted into the code so as to define the state of putation The following types of assertion are used as comment headers:

com-ASSERT

The ASSERT comment header describes the state of computation at a particularpoint in the code The idea is to state what is certainly known about variables andother program objects so that this information can be used in designing and testingthe code that follows

Special symbols and terms are associated with the ASSERT header The termAssigned is used to represent variables and constants initialized to a value Thesymbol && is used to represent logical AND, while the symbol || represents logical

OR regarding the terms of the assertion The symbol == is used to document aspecific value and the symbol ?? indicates that the value is unknown or undeter-minable at the time Finally, the symbol —>, or the word Implies, is used to repre-sent logical implication The programmer is also free to use other symbols andterms from mathematics, logic, or from the project’s specific context, as long asthey are clear and consistent

INV

The INV comment header represents a loop invariant It is used to describe a state ofcomputation at a certain point within a loop The intention of the loop invariant is todocument the fundamental tasks to be performed by the loop Since the invariant isinserted inside the loop body, its assertion must be true before the body executes,during every loop iteration, and immediately after the loop body has executed forthe last time Loop invariants are also used in code optimization techniques

PRE and POST

The PRE and POST comment headers are associated with functions They establishthe conditions that are expected at the function’s entry and exit points The PRE: as-sertion describes the elements (usually variables and constants) that must be sup-plied by the caller The POST: assertion describes the state of computation at themoment the function concludes its execution Taken together, they represent theterms of a contract between caller and function If the caller ensures that the PRE:assertion is true at call time, then the function guarantees that the POST: assertion issatisfied at return time

FCTVAL

The FCTVAL assertion represents the value returned by a function In C, this value isassociated with the function name Therefore, it should not be used to representvariables modified by the function

18.4.3 Programming Templates

One objection often made to API-level programming for Windows is coding cations In the program named WIN_HELLO, listed previously in this chapter, yousaw that the code for a simple hello, world program in Windows can be quite elabo-rate

Trang 36

One way in which to reduce the difficulties of Windows programming is by means

of code templates that provide a standard framework of operations A further plification is by means of “wrappers” that allow accessing API services indirectly,thus avoiding some of the coding difficulties Development environments such asthe MFC, Visual Basic, Power Builder, and Delphi are based on these two simplifica-tions, although implemented differently in each language

sim-Our approach precludes the use of “wrappers” for accessing API services; ever, it is possible to simplify direct API-level programming by means of sourcecode templates A template is a program, or a part of a program, from which all the

how-“specifics” have been removed The template method is reminiscent of how a tor uses a wood-and-wire frame to build a statue by adding and manipulating themodeling clay In the case of sculpturing, the frame has a body, a head, arms, andlegs; however it has no sex, or age, or clothing attire The same frame is used tobuild a statue of a naked cave man and that of a fully-dressed lady in the court ofLouis XIV

sculp-The programming version of the sculptor’s wood-and-wire frame is a coding plate If we take the idea of a standard header block and add to it the generic por-tions of the WIN_HELLO program, we come up with the following source codetemplate for a Windows program:

Trang 37

// Predeclaration of the Windows Procedure

LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM) ;

//

//****************************

//****************************

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,

PSTR szCmdLine, int iCmdShow) {

static char szAppName[] = “AppName” ; // Application name

// Defining a structure of type WNDCLASSEX

WNDCLASSEX wndclass ;

wndclass.lpfnWndProc = WndProc ;

wndclass.cbClsExtra = 0 ;

wndclass.cbWndExtra = 0 ;

wndclass.hInstance = hInstance ;

wndclass.hIcon = LoadIcon (NULL,IDI_APPLICATION);

wndclass.hCursor = LoadCursor (NULL, IDC_ARROW) ;

wndclass.hbrBackground = (HBRUSH) GetStockObject

(WHITE_BRUSH) ; wndclass.lpszMenuName = NULL ;

wndclass.lpszClassName = szAppName ;

wndclass.hIconSm = LoadIcon (NULL,IDI_APPLICATION);

// Registering the structure wmdclass

RegisterClassEx (&wndclass) ;

// CreateWindow()

hwnd = CreateWindow (szAppName,

WS_OVERLAPPEDWINDOW, // window style

Trang 38

EndPaint (hwnd, &ps) ; return 0 ;

// End of program execution

case WM_DESTROY :

PostQuitMessage (0) ; return 0 ;

}

return DefWindowProc (hwnd, iMsg, wParam, lParam) ;

}

You can use this template as a frame on which to build a Windows application It

is important to remember that a programming template is not a sample program, asmuch as a sculptor’s frame is not a statue Some templates may compile correctlywhile others may not Each template contains instructions regarding its use.Typically, the programmer removes these notes when they are no longer necessary

Trang 40

Win-a Windows progrWin-am from Win-a templWin-ate.

19.0 Preliminary Steps

Our approach to Windows programming is to avoid class libraries or other wrappers,such as The Microsoft Foundation Classes (MFC) At an initial level of Windows pro-gramming the use pre-canned interfaces may have some attraction, however, inhigh-performance graphics these packages are, at best, a nuisance and more often amajor hindrance On the other hand, we do take advantage of the editing and code gen-erating facilities provided by Developer Studio and use the program-generating wiz-ards, since there is no control or performance price to be paid in this case

Before we can create a major graphics application we must be able to constructthe Windows code framework that supports it Fabricating a program requires notonly knowledge of the programming language, but also skills in using the develop-ment environment For example, to create an icon for your program's title bar youneed to know about the API services that are used in defining and loading the icon,but you also need to have skills in using the icon editor that is part of Developer Stu-dio Even after the icon has been created and stored in a file, you need to follow aseries of steps that make this resource available to the program

463

Ngày đăng: 12/08/2014, 07:22

TỪ KHÓA LIÊN QUAN