• Aucun résultat trouvé

a Copyright© 2002 by The A−Team − Version 0.0.2

N/A
N/A
Protected

Academic year: 2022

Partager "a Copyright© 2002 by The A−Team − Version 0.0.2"

Copied!
1122
0
0

Texte intégral

(1)

Copyright© 2002 by The A−Team − Version 0.0.2

(2)

Author's Note

Visit my web site www.cpetzold.com for updated information regarding this book, including possible bug reports and new code listings. You can address mail regarding problems in this book to

charles@cpetzold.com. Although I'll also try to answer any easy questions you may have, I can't make any promises. I'm usually pretty busy, and my cat refuses to learn the Windows API.

I'd like to thank everyone at Microsoft Press for another great job in putting together this book. I think this "10th Anniversary Edition" of Programming Windows is the best edition yet. Many other people at Microsoft (including some of the early developers of Microsoft Windows) also helped out when I was writing the earlier editions, and these fine people are listed in those editions.

Thanks also to my family and friends, and in particular those more recent friends (you know who you are!) whose support has made this book possible. To you this book is dedicated.

Charles Petzold

October 5, 1998

(3)

About the Author

Charles Petzold has been writing about personal computer programming since 1984 and has been programming for Microsoft Windows since 1985. He wrote the first magazine article about Windows programming in the December 1986 issue of Microsoft Systems Journal. Between 1986 and 1995, he wrote the Environments column for PC Magazine, which introduced his readers to many facets of Windows and OS/2 programming.

Programming Windows was first published by Microsoft Press in 1988 and has since become regarded as the best introductory text on the subject. In May 1994, Petzold was one of only seven people (and the only writer) to be given a Windows Pioneer Award from Windows Magazine and Microsoft

Corporation for his contribution to the success of Microsoft Windows.

In the fall of 1999, Microsoft Press will publish Charles Petzold’s first book for a general audience.

Tentatively entitled Code: The Hidden Language of Computer Hardware and Software, this book is a unique introduction to the nature of digital information and how computers work with that information

(4)

About This Electronic Book

This electronic book was originally createdand still may be purchasedas a print book. For simplicity, the electronic version of this book has been modified as little as possible from its original form. For instance, there may be occasional references to sample files that come with the book. These files are available with the print version, but are not provided in this electronic edition.

(5)

Your Information Source

We're the independent publishing division of Microsoft Corporationyour source of inside information and unique perspectives about Microsoft products and related technologies. We've been around since 1984, and we offer a complete line of computer booksfrom self−paced tutorials for first−time computer users to advanced technical references for professional programmers.

mspress.microsoft.com

(6)

Table of Contents:

Chapter 1 −− Getting Started...1

The Windows Environment...2

A History of Windows...2

Aspects of Windows...3

Dynamic Linking...5

Windows Programming Options...6

APIs and Memory Models...6

Language Options...7

The Programming Environment...8

API Documentation...8

Your First Windows Program...9

A Character−Mode Model...9

The Windows Equivalent...9

The Header Files...10

Program Entry Point...11

The MessageBox Function...12

Compile, Link, and Run...13

Chapter 2 −− An Introduction to Unicode...15

A Brief History of Character Sets...16

American Standards...16

The World Beyond...17

Extending ASCII...17

Double−Byte Character Sets...19

Unicode to the Rescue...19

Wide Characters and C...21

The char Data Type...21

Wider Characters...22

Wide−Character Library Functions...23

Maintaining a Single Source...24

Wide Characters and Windows...26

Windows Header File Types...26

The Windows Function Calls...27

Windows' String Functions...28

Using printf in Windows...29

A Formatting Message Box...30

Internationalization and This Book...31

Chapter 3 −− Windows and Messages...33

A Window of One's Own...34

An Architectural Overview...34

The HELLOWIN Program...35

Thinking Globally...37

Registering the Window Class...42

Creating the Window...46

Displaying the Window...48

The Message Loop...48

(7)

Table of Contents:

A Window of One's Own

The Window Procedure...50

Processing the Messages...51

Playing a Sound File...51

The WM_PAINT Message...52

The WM_DESTROY Message...53

The Windows Programming Hurdles...54

Don't Call Me, I'll Call You...54

Queued and Nonqueued Messages...55

Get In and Out Fast...56

Chapter 4 −− An Exercise in Text Output...58

Painting and Repainting...59

The WM_PAINT Message...59

Valid and Invalid Rectangles...60

An Introduction to GDI...61

The Device Context...61

Getting a Device Context Handle: Method One...61

The Paint Information Structure...62

Getting a Device Context Handle: Method Two...64

TextOut: The Details...65

The System Font...66

The Size of a Character...66

Text Metrics: The Details...67

Formatting Text...68

Putting It All Together...69

The SYSMETS1.C Window Procedure...75

Not Enough Room...76

The Size of the Client Area...76

Scroll Bars...79

Scroll Bar Range and Position...80

Scroll Bar Messages...81

Scrolling SYSMETS...83

Structuring Your Program for Painting...86

Building a Better Scroll...88

The Scroll Bar Information Functions...88

How Low Can You Scroll?...89

The New SYSMETS...90

But I Don't Like to Use the Mouse...95

Chapter 5 −− Basic Drawing...96

The Structure of GDI...97

The GDI Philosophy...97

The GDI Function Calls...98

The GDI Primitives...99

Other Stuff...99

(8)

Table of Contents:

The Device Context...101

Getting a Device Context Handle...101

Getting Device Context Information...102

The DEVCAPS1 Program...103

The Size of the Device...106

Finding Out About Color...110

The Device Context Attributes...112

Saving Device Contexts...113

Drawing Dots and Lines...115

Setting Pixels...115

Straight Lines...115

The Bounding Box Functions...120

Bezier Splines...126

Using Stock Pens...130

Creating, Selecting, and Deleting Pens...131

Filling in the Gaps...133

Drawing Modes...134

Drawing Filled Areas...136

The Polygon Function and the Polygon−Filling Mode...137

Brushing the Interior...140

The GDI Mapping Mode...143

Device Coordinates and Logical Coordinates...144

The Device Coordinate Systems...145

The Viewport and the Window...145

Working with MM_TEXT...147

The Metric Mapping Modes...149

The "Roll Your Own" Mapping Modes...152

The WHATSIZE Program...157

Rectangles, Regions, and Clipping...161

Working with Rectangles...161

Random Rectangles...162

Creating and Painting Regions...165

Clipping with Rectangles and Regions...167

The CLOVER Program...168

Chapter 6 −− The Keyboard...172

Keyboard Basics...173

Ignoring the Keyboard...173

Who's Got the Focus?...173

Queues and Synchronization...174

Keystrokes and Characters...175

Keystroke Messages...176

System and Nonsystem Keystrokes...176

Virtual Key Codes...177

The lParam Information...180

Shift States...181

Using Keystroke Messages...182

Enhancing SYSMETS for the Keyboard...183

(9)

Table of Contents:

Character Messages...189

The Four Character Messages...189

Message Ordering...190

Control Character Processing...191

Dead−Character Messages...192

Keyboard Messages and Character Sets...193

The KEYVIEW1 Program...193

The Foreign−Language Keyboard Problem...197

Character Sets and Fonts...199

What About Unicode?...207

TrueType and Big Fonts...209

The Caret (Not the Cursor)...215

The Caret Functions...215

The TYPER Program...216

Chapter 7 −− The Mouse...222

Mouse Basics...223

Some Quick Definitions...223

The Plural of Mouse Is&...224

Client−Area Mouse Messages...225

Simple Mouse Processing: An Example...226

Processing Shift Keys...229

Mouse Double−Clicks...230

Nonclient−Area Mouse Messages...232

The Hit−Test Message...233

Messages Beget Messages...234

Hit−Testing in Your Programs...235

A Hypothetical Example...235

A Sample Program...235

Emulating the Mouse with the Keyboard...238

Add a Keyboard Interface to CHECKER...239

Using Child Windows for Hit−Testing...242

Child Windows in CHECKER...243

Child Windows and the Keyboard...247

Capturing the Mouse...252

Blocking Out a Rectangle...252

The Capture Solution...255

The BLOKOUT2 Program...256

Still to Come...259

The Mouse Wheel...265

Chapter 8 −− The Timer...266

Timer Basics...267

The System and the Timer...267

Timer Messages Are Not Asynchronous...267

(10)

Table of Contents:

Using the Timer: Three Methods...269

Method One...269

Method Two...272

Method Three...274

Using the Timer for a Clock...275

Building a Digital Clock...275

Getting the Current Time...278

Displaying Digits and Colons...279

Going International...280

Building an Analog Clock...280

Creating the Child Windows...286

The Child Talks to Its Parent...289

The Parent Talks to Its Child...291

Push Buttons...294

Check Boxes...295

Radio Buttons...296

Group Boxes...297

Changing the Button Text...297

Visible and Enabled Buttons...298

Buttons and Input Focus...299

Using the Timer for a Status Report...299

Chapter 9 −− Child Window Controls...299

The Button Class...300

Controls and Colors...301

System Colors...301

The Button Colors...302

The WM_CTLCOLORBTN Message...303

Owner−Draw Buttons...304

The Static Class...310

The Scroll Bar Class...311

The COLORS1 Program...312

The Automatic Keyboard Interface...317

Window Subclassing...318

Coloring the Background...318

Coloring the Scroll Bars and Static Text...319

The Edit Class Styles...321

Edit Control Notification...322

Using the Edit Controls...323

Messages to an Edit Control...324

The Edit Class...324

The Listbox Class...326

List Box Styles...326

Putting Strings in the List Box...327

Selecting and Extracting Entries...328

Receiving Messages from List Boxes...329

(11)

Table of Contents:

The Listbox Class

A Simple List Box Application...330

Listing Files...332

A head for Windows...334

HEAD.C...334

Chapter 10 −− Menus and Other Resources...339

Icons, Cursors, Strings, and Custom Resources...340

Adding an Icon to a Program...340

Getting a Handle on Icons...344

Using Icons in Your Program...346

Using Customized Cursors...347

Character String Resources...347

Custom Resources...349

Menus...357

Menu Concepts...357

Menu Structure...357

Defining the Menu...358

Referencing the Menu in Your Program...358

Menus and Messages...359

A Sample Program...361

Menu Etiquette...365

Defining a Menu the Hard Way...366

Floating Popup Menus...367

Using the System Menu...371

Changing the Menu...373

Other Menu Commands...374

An Unorthodox Approach to Menus...375

Keyboard Accelerators...380

Why You Should Use Keyboard Accelerators...380

Some Rules on Assigning Accelerators...380

The Accelerator Table...381

Loading the Accelerator Table...381

Translating the Keystrokes...381

Receiving the Accelerator Messages...382

POPPAD with a Menu and Accelerators...383

POPPAD2.ICO...387

Enabling Menu Items...388

Processing the Menu Options...388

The Dialog Box and Its Template...391

The Dialog Box Procedure...393

Invoking the Dialog Box...395

Variations on a Theme...396

A More Complex Dialog Box...397

Working with Dialog Box Controls...400

The OK and Cancel Buttons...405

Avoiding Global Variables...408

Tab Stops and Groups...409

Painting on the Dialog Box...410

Using Other Functions with Dialog Boxes...411

Defining Your Own Controls...412

(12)

Table of Contents:

Modal Dialog Boxes...412

Chapter 11 −− Dialog Boxes...418

Modeless Dialog Boxes...419

Differences Between Modal and Modeless Dialog Boxes...419

The New COLORS Program...421

HEXCALC: Window or Dialog Box?...425

The Common Dialog Boxes...432

POPPAD Revisited...432

Unicode File I/O...449

Changing the Font...449

Search and Replace...450

The One−Function−Call Windows Program...450

Chapter 12 −− The Clipboard...453

Simple Use of the Clipboard...454

The Standard Clipboard Data Formats...454

Memory Allocation...455

Transferring Text to the Clipboard...457

Getting Text from the Clipboard...458

Opening and Closing the Clipboard...459

The Clipboard and Unicode...459

Beyond Simple Clipboard Use...464

Using Multiple Data Items...464

Delayed Rendering...465

Private Data Formats...466

Becoming a Clipboard Viewer...469

The Clipboard Viewer Chain...469

Clipboard Viewer Functions and Messages...469

A Simple Clipboard Viewer...471

Chapter 13 −− Using the Printer...475

Printing Fundamentals...476

Printing and Spooling...476

The Printer Device Context...479

The Revised DEVCAPS Program...480

The PrinterProperties Call...488

Checking for BitBlt Capability...489

The Simplest Printing Program...489

Bare−Bones Printing...491

Implementing an Abort Procedure...493

Adding a Printing Dialog Box...496

Adding Printing to POPPAD...498

Printing Graphics and Text...501

(13)

Table of Contents:

Chapter 14 −− Bitmaps and Bitblts...507

Bitmap Basics...508

Bitmap Dimensions...510

Color and Bitmaps...510

Real−World Devices...511

Bitmap Support in GDI...513

The Bit−Block Transfer...515

A Simple BitBlt...515

Stretching the Bitmap...518

The StretchBlt Mode...520

The Raster Operations...521

The Pattern Blt...523

The GDI Bitmap Object...526

Creating a DDB...526

The Bitmap Bits...528

The Memory Device Context...529

Loading Bitmap Resources...530

The Monochrome Bitmap Format...533

Brushes from Bitmaps...536

Drawing on Bitmaps...538

The Shadow Bitmap...541

Using Bitmaps in Menus...545

Nonrectangular Bitmap Images...557

Some Simple Animation...561

Bitmaps Outside the Window...564

Chapter 15 −− The Device−Independent Bitmap...574

The DIB File Format...575

The OS/2−Style DIB...575

Bottoms Up!...578

The DIB Pixel Bits...578

The Expanded Windows DIB...579

Reality Check...582

DIB Compression...583

Color Masking...585

The Version 4 Header...588

The Version 5 Header...591

Displaying DIB Information...592

Displaying and Printing...599

Digging into the DIB...599

Pixel to Pixel...601

The Topsy−Turvy World of DIBs...609

Sequential Display...616

Stretching to Fit...622

Color Conversion, Palettes, and Performance...631

(14)

Table of Contents:

The Union of DIBs and DDBs...632

Creating a DDB from a DIB...632

From DDB to DIB...638

The DIB Section...638

More DIB Section Differences...645

The File−Mapping Option...646

In Summary...647

Chapter 16 −− The Palette Manager...648

Using Palettes...649

Video Hardware...649

Displaying Gray Shades...650

The Palette Messages...656

The Palette Index Approach...657

Querying the Palette Support...659

The System Palette...660

Other Palette Functions...661

The Raster−Op Problem...661

Looking at the System Palette...662

Palette Animation...670

The Bouncing Ball...670

One−Entry Palette Animation...676

Engineering Applications...680

Palettes and Real−World Images...685

Palettes and Packed DIBs...685

The All−Purpose Palette...693

The Halftone Palette...698

Indexing Palette Colors...702

Palettes and Bitmap Objects...707

Palettes and DIB Sections...711

A Library for DIBs...717

The DIBSTRUCT Structure...718

The Information Functions...719

Reading and Writing Pixels...725

Creating and Converting...728

The DIBHELP Header File and Macros...738

The DIBBLE Program...740

Simple Palettes; Optimized Palettes...759

Converting Formats...770

Chapter 17 −− Text and Fonts...774

Simple Text Output...775

The Text Drawing Functions...775

Device Context Attributes for Text...777

Using Stock Fonts...778

Background on Fonts...780

The Types of Fonts...780

TrueType Fonts...781

(15)

Table of Contents:

Background on Fonts

Attributes or Styles?...782

The Point Size...782

Leading and Spacing...782

The Logical Inch Problem...782

The Logical Font...784

Logical Font Creation and Selection...784

The PICKFONT Program...785

The Logical Font Structure...797

The Font−Mapping Algorithm...801

Finding Out About the Font...801

Character Sets and Unicode...803

The EZFONT System...804

Font Rotation...811

Font Enumeration...814

The Enumeration Functions...814

The ChooseFont Dialog...814

Paragraph Formatting...822

Simple Text Formatting...822

Working with Paragraphs...823

Previewing Printer Output...830

The Fun and Fancy Stuff...840

The GDI Path...840

Extended Pens...841

Four Sample Programs...844

Chapter 18 −− Metafiles...851

The Old Metafile Format...852

Simple Use of Memory Metafiles...852

Storing Metafiles on Disk...855

Old Metafiles and the Clipboard...855

Enhanced Metafiles...860

The Basic Procedure...860

Looking Inside...862

Metafiles and GDI Objects...867

Metafiles and Bitmaps...871

Enumerating the Metafile...874

Embedding Images...880

An Enhanced Metafile Viewer and Printer...883

Displaying Accurate Metafile Images...891

Scaling and Aspect Ratios...899

Mapping Modes in Metafiles...900

Mapping and Playing...903

Chapter 19 −− The Multiple−Document Interface...907

(16)

Table of Contents:

MDI Concepts...908

The Elements of MDI...908

MDI Support...909

Three Menus...911

Program Initialization...920

Creating the Children...920

More Frame Window Message Processing...921

The Child Document Windows...922

Cleaning Up...923

A Sample MDI Implementation...924

Chapter 20 −− Multitasking and Multithreading...925

Modes of Multitasking...926

Multitasking Under DOS?...926

Nonpreemptive Multitasking...926

PM and the Serialized Message Queue...927

The Multithreading Solution...927

Multithreaded Architecture...928

Thread Hassles...929

The Windows Advantage...929

New! Improved! Now with Threads!...930

Windows Multithreading...931

Random Rectangles Revisited...931

The Programming Contest Problem...934

The Multithreaded Solution...939

Any Problems?...946

The Benefits of Sleep...946

Thread Synchronization...948

The Critical Section...948

Event Signaling...950

The BIGJOB1 Program...950

The Event Object...954

Thread Local Storage...958

Chapter 21 −− Dynamic−Link Libraries...960

Library Basics...961

Miscellaneous DLL Topics...977

Chapter 22 −− Sound and Music...982

Windows and Multimedia...983

Multimedia Hardware...983

An API Overview...983

Exploring MCI with TESTMCI...984

MCITEXT and CD Audio...988

(17)

Table of Contents:

Waveform Audio...993

Sound and Waveforms...993

Pulse Code Modulation...994

The Sampling Rate...994

The Sample Size...995

Generating Sine Waves in Software...996

A Digital Sound Recorder...1004

The MCI Alternative...1013

The MCI Command String Approach...1019

The Waveform Audio File Format...1022

Experimenting with Additive Synthesis...1023

Waking Up to Waveform Audio...1030

MIDI and Music...1038

The Workings of MIDI...1038

The Program Change...1039

The MIDI Channel...1040

MIDI Messages...1041

An Introduction to MIDI Sequencing...1042

Playing a MIDI Synthesizer from the PC Keyboard...1047

A MIDI Drum Machine...1060

The Multimedia time Functions...1077

RIFF File I/O...1080

Chapter 23 −− A Taste of the Internet...1082

Windows Sockets...1083

Sockets and TCP/IP...1083

Network Time Services...1083

The NETTIME Program...1084

WinInet and FTP...1095

Overview of the FTP API...1095

The Update Demo...1096

(18)

Chapter 1 −− Getting Started

This book shows you how to write programs that run under Microsoft Windows 98, Microsoft Windows NT 4.0, and Windows NT 5.0. These programs are written in the C programming language and use the native Windows application programming interfaces (APIs). As I'll discuss later in this chapter, this is not the only way to write programs that run under Windows. However, it is important to understand the Windows APIs regardless of what you eventually use to write your code.

As you probably know, Windows 98 is the latest incarnation of the graphical operating system that has become the de facto standard for IBM−compatible personal computers built around 32−bit Intel

microprocessors such as the 486 and Pentium. Windows NT is the industrial−strength version of Windows that runs on PC compatibles as well as some RISC (reduced instruction set computing) workstations.

There are three prerequisites for using this book. First, you should be familiar with Windows 98 from a user's perspective. You cannot hope to write applications for Windows without understanding its user interface. For this reason, I suggest that you do your program development (as well as other work) on a Windows−based machine using Windows applications.

Second, you should know C. If you don't know C, Windows programming is probably not a good place to start. I recommend that you learn C in a character−mode environment such as that offered under the Windows 98 MS−DOS Command Prompt window. Windows programming sometimes involves aspects of C that don't show up much in character−mode programming; in those cases, I'll devote some

discussion to them. But for the most part, you should have a good working familiarity with the language, particularly with C structures and pointers. Some knowledge of the standard C run−time library is helpful but not required.

Third, you should have installed on your machine a 32−bit C compiler and development environment suitable for doing Windows programming. In this book, I'll be assuming that you're using Microsoft Visual C++ 6.0, which can be purchased separately or as a part of the Visual Studio 6.0 package.

That's it. I'm not going to assume that you have any experience at all programming for a graphical user interface such as Windows.

(19)

The Windows Environment

Windows hardly needs an introduction. Yet it's easy to forget the sea change that Windows brought to office and home desktop computing. Windows had a bumpy ride in its early years and was hardly destined to conquer the desktop market.

A History of Windows

Soon after the introduction of the IBM PC in the fall of 1981, it became evident that the predominant operating system for the PC (and compatibles) would be MS−DOS, which originally stood for Microsoft Disk Operating System. MS−DOS was a minimal operating system. For the user, MS−DOS provided a command−line interface to commands such as DIR and TYPE and loaded application programs into memory for execution. For the application programmer, MS−DOS offered little more than a set of function calls for doing file input/output (I/O). For other tasksin particular, writing text and sometimes graphics to the video displayapplications accessed the hardware of the PC directly.

Due to memory and hardware constraints, sophisticated graphical environments were slow in coming to small computers. Apple Computer offered an alternative to character−mode environments when it released its ill−fated Lisa in January 1983, and then set a standard for graphical environments with the Macintosh in January 1984. Despite the Mac's declining market share, it is still considered the standard against which other graphical environments are measured. All graphical environments, including the Macintosh and Windows, are indebted to the pioneering work done at the Xerox Palo Alto Research Center (PARC) beginning in the mid−1970s.

Windows was announced by Microsoft Corporation in November 1983 (post−Lisa but pre−Macintosh) and was released two years later in November 1985. Over the next two years, Microsoft Windows 1.0 was followed by several updates to support the international market and to provide drivers for

additional video displays and printers.

Windows 2.0 was released in November 1987. This version incorporated several changes to the user interface. The most significant of these changes involved the use of overlapping windows rather than the "tiled" windows found in Windows 1.0. Windows 2.0 also included enhancements to the keyboard and mouse interface, particularly for menus and dialog boxes.

Up until this time, Windows required only an Intel 8086 or 8088 microprocessor running in "real mode"

to access 1 megabyte (MB) of memory. Windows/386 (released shortly after Windows 2.0) used the

"virtual 86" mode of the Intel 386 microprocessor to window and multitask many DOS programs that directly accessed hardware. For symmetry, Windows 2.1 was renamed Windows/286.

Windows 3.0 was introduced on May 22, 1990. The earlier Windows/286 and Windows/386 versions were merged into one product with this release. The big change in Windows 3.0 was the support of the 16−bit protected−mode operation of Intel's 286, 386, and 486 microprocessors. This gave Windows and Windows applications access to up to 16 megabytes of memory. The Windows "shell" programs for running programs and maintaining files were completely revamped. Windows 3.0 was the first version of Windows to gain a foothold in the home and the office.

Any history of Windows must also include a mention of OS/2, an alternative to DOS and Windows that was originally developed by Microsoft in collaboration with IBM. OS/2 1.0 (character−mode only) ran on the Intel 286 (or later) microprocessors and was released in late 1987. The graphical Presentation Manager (PM) came about with OS/2 1.1 in October 1988. PM was originally supposed to be a protected−mode version of Windows, but the graphical API was changed to such a degree that it proved difficult for software manufacturers to support both platforms.

By September 1990, conflicts between IBM and Microsoft reached a peak and required that the two companies go their separate ways. IBM took over OS/2 and Microsoft made it clear that Windows was

(20)

the center of their strategy for operating systems. While OS/2 still has some fervent admirers, it has not nearly approached the popularity of Windows.

Microsoft Windows version 3.1 was released in April 1992. Several significant features included the TrueType font technology (which brought scaleable outline fonts to Windows), multimedia (sound and music), Object Linking and Embedding (OLE), and standardized common dialog boxes. Windows 3.1 ran only in protected mode and required a 286 or 386 processor with at least 1 MB of memory.

Windows NT, introduced in July 1993, was the first version of Windows to support the 32−bit mode of the Intel 386, 486, and Pentium microprocessors. Programs that run under Windows NT have access to a 32−bit flat address space and use a 32−bit instruction set. (I'll have more to say about address spaces a little later in this chapter.) Windows NT was also designed to be portable to non−Intel processors, and it runs on several RISC−based workstations.

Windows 95 was introduced in August 1995. Like Windows NT, Windows 95 also supported the 32−bit programming mode of the Intel 386 and later microprocessors. Although it lacked some of the features of Windows NT, such as high security and portability to RISC machines, Windows 95 had the

advantage of requiring fewer hardware resources.

Windows 98 was released in June 1998 and has a number of enhancements, including performance improvements, better hardware support, and a closer integration with the Internet and the World Wide Web.

Aspects of Windows

Both Windows 98 and Windows NT are 32−bit preemptive multitasking and multithreading graphical operating systems. Windows possesses a graphical user interface (GUI), sometimes also called a

"visual interface" or "graphical windowing environment." The concepts behind the GUI date from the mid−1970s with the work done at the Xerox PARC for machines such as the Alto and the Star and for environments such as SmallTalk. This work was later brought into the mainstream and popularized by Apple Computer and Microsoft. Although somewhat controversial for a while, it is now quite obvious that the GUI is (in the words of Microsoft's Charles Simonyi) the single most important "grand consensus" of the personal−computer industry.

All GUIs make use of graphics on a bitmapped video display. Graphics provides better utilization of screen real estate, a visually rich environment for conveying information, and the possibility of a WYSIWYG (what you see is what you get) video display of graphics and formatted text prepared for a printed document.

In earlier days, the video display was used solely to echo text that the user typed using the keyboard.

In a graphical user interface, the video display itself becomes a source of user input. The video display shows various graphical objects in the form of icons and input devices such as buttons and scroll bars.

Using the keyboard (or, more directly, a pointing device such as a mouse), the user can directly

manipulate these objects on the screen. Graphics objects can be dragged, buttons can be pushed, and scroll bars can be scrolled.

The interaction between the user and a program thus becomes more intimate. Rather than the one−way cycle of information from the keyboard to the program to the video display, the user directly interacts with the objects on the display.

Users no longer expect to spend long periods of time learning how to use the computer or mastering a new program. Windows helps because all applications have the same fundamental look and feel. The program occupies a windowusually a rectangular area on the screen. Each window is identified by a caption bar. Most program functions are initiated through the program's menus. A user can view the display of information too large to fit on a single screen by using scroll bars. Some menu items invoke dialog boxes, into which the user enters additional information. One dialog box in particular, that used

(21)

to open a file, can be found in almost every large Windows program. This dialog box looks the same (or nearly the same) in all of these Windows programs, and it is almost always invoked from the same menu option.

Once you know how to use one Windows program, you're in a good position to easily learn another.

The menus and dialog boxes allow a user to experiment with a new program and explore its features.

Most Windows programs have both a keyboard interface and a mouse interface. Although most functions of Windows programs can be controlled through the keyboard, using the mouse is often easier for many chores.

From the programmer's perspective, the consistent user interface results from using the routines built into Windows for constructing menus and dialog boxes. All menus have the same keyboard and mouse interface because Windowsrather than the application programhandles this job.

To facilitate the use of multiple programs, and the exchange of information among them, Windows supports multitasking. Several Windows programs can be displayed and running at the same time.

Each program occupies a window on the screen. The user can move the windows around on the screen, change their sizes, switch between different programs, and transfer data from one program to another. Because these windows look something like papers on a desktop (in the days before the desk became dominated by the computer itself, of course), Windows is sometimes said to use a "desktop metaphor" for the display of multiple programs.

Earlier versions of Windows used a system of multitasking called "nonpreemptive." This meant that Windows did not use the system timer to slice processing time between the various programs running under the system. The programs themselves had to voluntarily give up control so that other programs could run. Under Windows NT and Windows 98, multitasking is preemptive and programs themselves can split into multiple threads of execution that seem to run concurrently.

An operating system cannot implement multitasking without doing something about memory management. As new programs are started up and old ones terminate, memory can become

fragmented. The system must be able to consolidate free memory space. This requires the system to move blocks of code and data in memory.

Even Windows 1.0, running on an 8088 microprocessor, was able to perform this type of memory management. Under real−mode restrictions, this ability can only be regarded as an astonishing feat of software engineering. In Windows 1.0, the 640−kilobyte (KB) memory limit of the PC's architecture was effectively stretched without requiring any additional memory. But Microsoft didn't stop there: Windows 2.0 gave the Windows applications access to expanded memory (EMS), and Windows 3.0 ran in protected mode to give Windows applications access to up to 16 MB of extended memory. Windows NT and Windows 98 blow away these old limits by being full−fledged 32−bit operating systems with flat memory space.

Programs running in Windows can share routines that are located in other files called "dynamic−link libraries." Windows includes a mechanism to link the program with the routines in the dynamic−link libraries at run time. Windows itself is basically a set of dynamic−link libraries.

Windows is a graphical interface, and Windows programs can make full use of graphics and formatted text on both the video display and the printer. A graphical interface not only is more attractive in appearance but also can impart a high level of information to the user.

Programs written for Windows do not directly access the hardware of graphics display devices such as the screen and printer. Instead, Windows includes a graphics programming language (called the Graphics Device Interface, or GDI) that allows the easy display of graphics and formatted text.

Windows virtualizes display hardware. A program written for Windows will run with any video board or any printer for which a Windows device driver is available. The program does not need to determine what type of device is attached to the system.

(22)

Putting a device−independent graphics interface on the IBM PC was not an easy job for the developers of Windows. The PC design was based on the principle of open architecture. Third−party hardware manufacturers were encouraged to develop peripherals for the PC and have done so in great number.

Although several standards have emerged, conventional MS−DOS programs for the PC had to individually support many different hardware configurations. It was fairly common for an MS−DOS word−processing program to be sold with one or two disks of small files, each one supporting a particular printer. Windows programs do not require these drivers because the support is part of Windows.

Dynamic Linking

Central to the workings of Windows is a concept known as "dynamic linking." Windows provides a wealth of function calls that an application can take advantage of, mostly to implement its user interface and display text and graphics on the video display. These functions are implemented in dynamic−link libraries, or DLLs. These are files with the extension .DLL or sometimes .EXE, and they are mostly located in the \WINDOWS\SYSTEM subdirectory under Windows 98 and the \WINNT\SYSTEM and

\WINNT\SYSTEM32 subdirectories under Windows NT.

In the early days, the great bulk of Windows was implemented in just three dynamic−link libraries.

These represented the three main subsystems of Windows, which were referred to as Kernel, User, and GDI. While the number of subsystems has proliferated in recent versions of Windows, most function calls that a typical Windows program makes will still fall in one of these three modules. Kernel (which is currently implemented by the 16−bit KRNL386.EXE and the 32−bit KERNEL32.DLL) handles all the stuff that an operating system kernel traditionally handlesmemory management, file I/O, and tasking. User (implemented in the 16−bit USER.EXE and the 32−bit USER32.DLL) refers to the user interface, and implements all the windowing logic. GDI (implemented in the 16−bit GDI.EXE and the 32−bit GDI32.DLL) is the Graphics Device Interface, which allows a program to display text and graphics on the screen and printer.

Windows 98 supports several thousand function calls that applications can use. Each function has a descriptive name, such as CreateWindow. This function (as you might guess) creates a window for your program. All the Windows functions that an application may use are declared in header files.

In your Windows program, you use the Windows function calls in generally the same way you use C library functions such as strlen. The primary difference is that the machine code for C library functions is linked into your program code, whereas the code for Windows functions is located outside of your program in the DLLs.

When you run a Windows program, it interfaces to Windows through a process called "dynamic linking." A Windows .EXE file contains references to the various dynamic−link libraries it uses and the functions therein. When a Windows program is loaded into memory, the calls in the program are resolved to point to the entries of the DLL functions, which are also loaded into memory if not already there.

When you link a Windows program to produce an executable file, you must link with special "import libraries" provided with your programming environment. These import libraries contain the dynamic−link library names and reference information for all the Windows function calls. The linker uses this

information to construct the table in the .EXE file that Windows uses to resolve calls to Windows functions when loading the program.

(23)

Windows Programming Options

To illustrate the various techniques of Windows programming, this book has lots of sample programs.

These programs are written in C and use the native Windows APIs. I think of this approach as

"classical" Windows programming. It is how we wrote programs for Windows 1.0 in 1985, and it remains a valid way of programming for Windows today.

APIs and Memory Models

To a programmer, an operating system is defined by its API. An API encompasses all the function calls that an application program can make of an operating system, as well as definitions of associated data types and structures. In Windows, the API also implies a particular program architecture that we'll explore in the chapters ahead.

Generally, the Windows API has remained quite consistent since Windows 1.0. A Windows

programmer with experience in Windows 98 would find the source code for a Windows 1.0 program very familiar. One way the API has changed has been in enhancements. Windows 1.0 supported fewer than 450 function calls; today there are thousands.

The biggest change in the Windows API and its syntax came about during the switch from a 16−bit architecture to a 32−bit architecture. Versions 1.0 through 3.1 of Windows used the so−called

segmented memory mode of the 16−bit Intel 8086, 8088, and 286 microprocessors, a mode that was also supported for compatibility purposes in the 32−bit Intel microprocessors beginning with the 386.

The microprocessor register size in this mode was 16 bits, and hence the C int data type was also 16 bits wide. In the segmented memory model, memory addresses were formed from two componentsa 16−bit segment pointer and a 16−bit offset pointer. From the programmer's perspective, this was quite messy and involved differentiating between long, or far, pointers (which involved both a segment address and an offset address) and short, or near, pointers (which involved an offset address with an assumed segment address).

Beginning in Windows NT and Windows 95, Windows supported a 32−bit flat memory model using the 32−bit modes of the Intel 386, 486, and Pentium processors. The C int data type was promoted to a 32−bit value. Programs written for 32−bit versions of Windows use simple 32−bit pointer values that address a flat linear address space.

The API for the 16−bit versions of Windows (Windows 1.0 through Windows 3.1) is now known as Win16. The API for the 32−bit versions of Windows (Windows 95, Windows 98, and all versions of Windows NT) is now known as Win32. Many function calls remained the same in the transition from Win16 to Win32, but some needed to be enhanced. For example, graphics coordinate points changed from 16−bit values in Win16 to 32−bit values in Win32. Also, some Win16 function calls returned a two−dimensional coordinate point packed in a 32−bit integer. This was not possible in Win32, so new function calls were added that worked in a different way.

All 32−bit versions of Windows support both the Win16 API to ensure compatibility with old applications and the Win32 API to run new applications. Interestingly enough, this works differently in Windows NT than in Windows 95 and Windows 98. In Windows NT, Win16 function calls go through a translation layer and are converted to Win32 function calls that are then processed by the operating system. In Windows 95 and Windows 98, the process is opposite that: Win32 function calls go through a translation layer and are converted to Win16 function calls to be processed by the operating system.

At one time, there were two other Windows API sets (at least in name). Win32s ("s" for "subset") was an API that allowed programmers to write 32−bit applications that ran under Windows 3.1. This API supported only 32−bit versions of functions already supported by Win16. Also, the Windows 95 API was once called Win32c ("c" for "compatibility"), but this term has been abandoned.

(24)

At this time, Windows NT and Windows 98 are both considered to support the Win32 API. However, each operating system supports some features not supported by the other. Still, because the overlap is considerable, it's possible to write programs that run under both systems. Also, it's widely assumed that the two products will be merged at some time in the future.

Language Options

Using C and the native APIs is not the only way to write programs for Windows 98. However, this approach offers you the best performance, the most power, and the greatest versatility in exploiting the features of Windows. Executables are relatively small and don't require external libraries to run (except for the Windows DLLs themselves, of course). Most importantly, becoming familiar with the API

provides you with a deeper understanding of Windows internals, regardless of how you eventually write applications for Windows.

Although I think that learning classical Windows programming is important for any Windows

programmer, I don't necessarily recommend using C and the API for every Windows application. Many programmersparticularly those doing in−house corporate programming or those who do recreational programming at homeenjoy the ease of development environments such as Microsoft Visual Basic or Borland Delphi (which incorporates an object−oriented dialect of Pascal). These environments allow a programmer to focus on the user interface of an application and associate code with user interface objects. To learn Visual Basic, you might want to consult some other Microsoft Press books, such as Learn Visual Basic Now (1996), by Michael Halvorson.

Among professional programmersparticularly those who write commercial applicationsMicrosoft

Visual C++ with the Microsoft Foundation Class Library (MFC) has been a popular alternative in recent years. MFC encapsulates many of the messier aspects of Windows programming in a collection of C++

classes. Jeff Prosise's Programming Windows with MFC, Second Edition (Microsoft Press, 1999) provides tutorials on MFC.

Most recently, the popularity of the Internet and the World Wide Web has given a big boost to Sun Microsystems' Java, the processor−independent language inspired by C++ and incorporating a toolkit for writing graphical applications that will run on several operating system platforms. A good Microsoft Press book on Microsoft J++, Microsoft's Java development tool, is Programming Visual J++ 6.0 (1998), by Stephen R. Davis.

Obviously, there's hardly any one right way to write applications for Windows. More than anything else, the nature of the application itself should probably dictate the tools. But learning the Windows API gives you vital insights into the workings of Windows that are essential regardless of what you end up using to actually do the coding. Windows is a complex system; putting a programming layer on top of the API doesn't eliminate the complexityit merely hides it. Sooner or later that complexity is going to jump out and bite you in the leg. Knowing the API gives you a better chance at recovery.

Any software layer on top of the native Windows API necessarily restricts you to a subset of full functionality. You might find, for example, that Visual Basic is ideal for your application except that it doesn't allow you to do one or two essential chores. In that case, you'll have to use native API calls.

The API defines the universe in which we as Windows programmers exist. No approach can be more powerful or versatile than using this API directly.

MFC is particularly problematic. While it simplifies some jobs immensely (such as OLE), I often find myself wrestling with other features (such as the Document/View architecture) to get them to work as I want. MFC has not been the Windows programming panacea that many hoped for, and few people would characterize it as a model of good object−oriented design. MFC programmers benefit greatly from understanding what's going on in class definitions they use, and find themselves frequently consulting MFC source code. Understanding that source code is one of the benefits of learning the Windows API.

(25)

The Programming Environment

In this book, I'll be assuming that you're running Microsoft Visual C++ 6.0, which comes in Standard, Professional, and Enterprise editions. The less−expensive Standard edition is fine for doing the programs in this book. Visual C++ is also part of Visual Studio 6.0.

The Microsoft Visual C++ package includes more than the C compiler and other files and tools

necessary to compile and link Windows programs. It also includes the Visual C++ Developer Studio, an environment in which you can edit your source code; interactively create resources such as icons and dialog boxes; and edit, compile, run, and debug your programs.

If you're running Visual C++ 5.0, you might need to get updated header files and import libraries for Windows 98 and Windows NT 5.0. These are available at Microsoft's web site. Go to

http://www.microsoft.com/msdn/, and choose Downloads and then Platform SDK ("software

development kit"). You'll be able to download and install the updated files in directories of your choice.

To direct the Microsoft Developer Studio to look in these directories, choose Options from the Tools menu and then pick the Directories tab.

The msdn portion of the Microsoft URL above stands for Microsoft Developer Network. This is a program that provides developers with frequently updated CD−ROMs containing much of what they need to be on the cutting edge of Windows development. You'll probably want to investigate

subscribing to MSDN and avoid frequent downloading from Microsoft's web site.

API Documentation

This book is not a substitute for the official formal documentation of the Windows API. That

documentation is no longer published in printed form; it is available only via CD−ROM or the Internet.

When you install Visual C++ 6.0, you'll get an online help system that includes API documentation. You can get updates to that documentation by subscribing to MSDN or by using Microsoft's Web−based online help system. Start by linking to http://www.microsoft.com/msdn/, and select MSDN Library Online.

In Visual C++ 6.0, select the Contents item from the Help menu to invoke the MSDN window. The API documentation is organized in a tree−structured hierarchy. Find the section labeled Platform SDK. All the documentation I'll be citing in this book is from this section. I'll show the location of documentation using the nested levels starting with Platform SDK separated by slashes. (I know the Platform SDK looks like a small obscure part of the total wealth of MSDN knowledge, but I assure you that it's the essential core of Windows programming.) For example, for documentation on how to use the mouse in your Windows programs, you can consult /Platform SDK/User Interface Services/User Input/Mouse Input.

I mentioned before that much of Windows is divided into the Kernel, User, and GDI subsystems. The kernel interfaces are in /Platform SDK/Windows Base Services, the user interface functions are in /Platform SDK/User Interface Services, and GDI is documented in /Platform SDK/Graphics and Multimedia Services/GDI.

(26)

Your First Windows Program

Now it's time to do some coding. Let's begin by looking at a very short Windows program and, for comparison, a short character−mode program. These will help us get oriented in using the

development environment and going through the mechanics of creating and compiling a program.

A Character−Mode Model

A favorite book among programmers is The C Programming Language (Prentice Hall, 1978 and 1988) by Brian W. Kernighan and Dennis M. Ritchie, affectionately referred to as K&R. Chapter 1 of this book begins with a C program that displays the words "hello, world."

Here's the program as it appeared on page 6 of the first edition of The C Programming Language:

main () {

printf ("hello, world\n") ; }

Yes, once upon a time C programmers used C run−time library functions such as printf without declaring them first. But this is the '90s, and we like to give our compilers a fighting chance to flag errors in our code. Here's the revised code from the second edition of K&R:

#include <stdio.h>

main () {

printf ("hello, world\n") ; }

This program still isn't really as small as it seems. It will certainly compile and run just fine, but many programmers these days would prefer to explicitly indicate the return value of the main function, in which case ANSI C dictates that the function actually returns a value:

#include <stdio.h>

int main () {

printf ("hello, world\n") ; return 0 ;

}

We could make this even longer by including the arguments to main, but let's leave it at thatwith an include statement, the program entry point, a call to a run−time library function, and a return statement.

The Windows Equivalent

The Windows equivalent to the "hello, world" program has exactly the same components as the character−mode version. It has an include statement, a program entry point, a function call, and a return statement. Here's the program:

/*−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−

HelloMsg.c −− Displays "Hello, Windows 98!" in a message box (c) Charles Petzold, 1998

−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−*/

#include <windows.h>

(27)

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)

{

MessageBox (NULL, TEXT ("Hello, Windows 98!"), TEXT ("HelloMsg"), 0) ; return 0 ;

}

Before I begin dissecting this program, let's go through the mechanics of creating a program in the Visual C++ Developer Studio.

To begin, select New from the File menu. In the New dialog box, pick the Projects tab. Select Win32 Application. In the Location field, select a subdirectory. In the Project Name field, type the name of the project, which in this case is HelloMsg. This will be a subdirectory of the directory indicated in the Location field. The Create New Workspace button should be checked. The Platforms section should indicate Win32. Choose OK.

A dialog box labeled Win32 Application − Step 1 Of 1 will appear. Indicate that you want to create an Empty Project, and press the Finish button.

Select New from the File menu again. In the New dialog box, pick the Files tab. Select C++ Source File. The Add To Project box should be checked, and HelloMsg should be indicated. Type HelloMsg.c in the File Name field. Choose OK.

Now you can type in the HELLOMSG.C file shown above. Or you can select the Insert menu and the File As Text option to copy the contents of HELLOMSG.C from the file on this book's companion CD−ROM.

Structurally, HELLOMSG.C is identical to the K&R "hello, world" program. The header file STDIO.H has been replaced with WINDOWS.H, the entry point main has been replaced with WinMain, and the C run−time library function printf has been replaced with the Windows API function MessageBox.

However, there is much in the program that is new, including several strange−looking uppercase identifiers.

Let's start at the top.

The Header Files

HELLOMSG.C begins with a preprocessor directive that you'll find at the top of virtually every Windows program written in C:

#include <windows.h>

WINDOWS.H is a master include file that includes other Windows header files, some of which also include other header files. The most important and most basic of these header files are:

WINDEF.H Basic type definitions.

WINNT.H Type definitions for Unicode support.

WINBASE.H Kernel functions.

WINUSER.H User interface functions.

WINGDI.H Graphics device interface functions.

(28)

These header files define all the Windows data types, function calls, data structures, and constant identifiers. They are an important part of Windows documentation. You might find it convenient to use the Find In Files option from the Edit menu in the Visual C++ Developer Studio to search through these header files. You can also open the header files in the Developer Studio and examine them directly.

Program Entry Point

Just as the entry point to a C program is the function main, the entry point to a Windows program is WinMain, which always appears like this:

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)

This entry point is documented in /Platform SDK/User Interface Services/Windowing/Windows/Window Reference/Window Functions. It is declared in WINBASE.H like so (line breaks and all):

int WINAPI WinMain(

HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine,

int nShowCmd );

You'll notice I've made a couple of minor changes in HELLOMSG.C. The third parameter is defined as an LPSTR in WINBASE.H, and I've made it a PSTR. These two data types are both defined in

WINNT.H as pointers to character strings. The LP prefix stands for "long pointer" and is an artifact of 16−bit Windows.

I've also changed two of the parameter names from the WinMain declaration; many Windows programs use a system called "Hungarian notation" for naming variables. This system involves prefacing the variable name with a short prefix that indicates the variable's data type. I'll discuss this concept more in Chapter 3. For now, just keep in mind that the prefix i stands for int and sz stands for "string terminated with a zero."

The WinMain function is declared as returning an int. The WINAPI identifier is defined in WINDEF.H with the statement:

#define WINAPI __stdcall

This statement specifies a calling convention that involves how machine code is generated to place function call arguments on the stack. Most Windows function calls are declared as WINAPI.

The first parameter to WinMain is something called an "instance handle." In Windows programming, a handle is simply a number that an application uses to identify something. In this case, the handle uniquely identifies the program. It is required as an argument to some other Windows function calls. In early versions of Windows, when you ran the same program concurrently more than once, you created multiple instances of that program. All instances of the same application shared code and read−only memory (usually resources such as menu and dialog box templates). A program could determine if other instances of itself were running by checking the hPrevInstance parameter. It could then skip certain chores and move some data from the previous instance into its own data area.

In the 32−bit versions of Windows, this concept has been abandoned. The second parameter to WinMain is always NULL (defined as 0).

(29)

The third parameter to WinMain is the command line used to run the program. Some Windows applications use this to load a file into memory when the program is started. The fourth parameter to WinMain indicates how the program should be initially displayedeither normally or maximized to fill the window, or minimized to be displayed in the task list bar. We'll see how this parameter is used in Chapter 3.

The MessageBox Function

The MessageBox function is designed to display short messages. The little window that MessageBox displays is actually considered to be a dialog box, although not one with a lot of versatility.

The first argument to MessageBox is normally a window handle. We'll see what this means in Chapter 3. The second argument is the text string that appears in the body of the message box, and the third argument is the text string that appears in the caption bar of the message box. In HELLMSG.C, each of these text strings is enclosed in a TEXT macro. You don't normally have to enclose all character

strings in the TEXT macro, but it's a good idea if you want to be ready to convert your programs to the Unicode character set. I'll discuss this in much more detail in Chapter 2.

The fourth argument to MessageBox can be a combination of constants beginning with the prefix MB_

that are defined in WINUSER.H. You can pick one constant from the first set to indicate what buttons you wish to appear in the dialog box:

#define MB_OK 0x00000000L

#define MB_OKCANCEL 0x00000001L

#define MB_ABORTRETRYIGNORE 0x00000002L

#define MB_YESNOCANCEL 0x00000003L

#define MB_YESNO 0x00000004L

#define MB_RETRYCANCEL 0x00000005L

When you set the fourth argument to 0 in HELLOMSG, only the OK button appears. You can use the C OR (|) operator to combine one of the constants shown above with a constant that indicates which of the buttons is the default:

#define MB_DEFBUTTON1 0x00000000L

#define MB_DEFBUTTON2 0x00000100L

#define MB_DEFBUTTON3 0x00000200L

#define MB_DEFBUTTON4 0x00000300L

You can also use a constant that indicates the appearance of an icon in the message box:

#define MB_ICONHAND 0x00000010L

#define MB_ICONQUESTION 0x00000020L

#define MB_ICONEXCLAMATION 0x00000030L

#define MB_ICONASTERISK 0x00000040L

Some of these icons have alternate names:

#define MB_ICONWARNING MB_ICONEXCLAMATION

#define MB_ICONERROR MB_ICONHAND

#define MB_ICONINFORMATION MB_ICONASTERISK

#define MB_ICONSTOP MB_ICONHAND

There are a few other MB_ constants, but you can consult the header file yourself or the documentation in /Platform SDK/User Interface Services/Windowing/Dialog Boxes/Dialog Box Reference/Dialog Box Functions.

In this program, the MessageBox function returns the value 1, but it's more proper to say that it returns IDOK, which is defined in WINUSER.H as equaling 1. Depending on the other buttons present in the

(30)

message box, the MessageBox function can also return IDYES, IDNO, IDCANCEL, IDABORT, IDRETRY, or IDIGNORE.

Is this little Windows program really the equivalent of the K&R "hello, world" program? Well, you might think not because the MessageBox function doesn't really have all the potential formatting power of the printf function in "hello, world." But we'll see in the next chapter how to write a version of MessageBox that does printf−like formatting.

Compile, Link, and Run

When you're ready to compile HELLOMSG, you can select Build Hellomsg.exe from the Build menu, or press F7, or select the Build icon from the Build toolbar. (The appearance of this icon is shown in the Build menu. If the Build toolbar is not currently displayed, you can choose Customize from the Tools menu and select the Toolbars tab. Pick Build or Build MiniBar.)

Alternatively, you can select Execute Hellomsg.exe from the Build menu, or press Ctrl+F5, or click the Execute Program icon (which looks like a red exclamation point) from the Build toolbar. You'll get a message box asking you if you want to build the program.

As normal, during the compile stage, the compiler generates an .OBJ (object) file from the C source code file. During the link stage, the linker combines the .OBJ file with .LIB (library) files to create the .EXE (executable) file. You can see a list of these library files by selecting Settings from the Project tab and clicking the Link tab. In particular, you'll notice KERNEL32.LIB, USER32.LIB, and GDI32.LIB.

These are "import libraries" for the three major Windows subsystems. They contain the dynamic−link library names and reference information that is bound into the .EXE file. Windows uses this information to resolve calls from the program to functions in the KERNEL32.DLL, USER32.DLL, and GDI32.DLL dynamic−link libraries.

In the Visual C++ Developer Studio, you can compile and link the program in different configurations.

By default, these are called Debug and Release. The executable files are stored in subdirectories of these names. In the Debug configuration, information is added to the .EXE file that assists in

debugging the program and in tracing through the program source code.

If you prefer working on the command line, the companion CD−ROM contains .MAK (make) files for all the sample programs. (You can tell the Developer Studio to generate make files by choosing Options from the Tools menu and selecting the Build tab. There's a check box to check.) You'll need to run VCVARS32.BAT located in the BIN subdirectory of the Developer Studio to set environment variables.

To execute the make file from the command line, change to the HELLOMSG directory and execute:

NMAKE /f HelloMsg.mak CFG="HelloMsg _ Win32 Debug"

or

NMAKE /f HelloMsg.mak CFG="HelloMsg _ Win32 Release"

You can then run the .EXE file from the command line by typing:

DEBUG\HELLOMSG

or

RELEASE\HELLOMSG

I have made one change to the default Debug configuration in the project files on the companion CD−ROM for this book. In the Project Settings dialog box, after selecting the C/C++ tab, in the

Preprocessor Definitions field I have defined the identifier UNICODE. I'll have much more to say about

(31)

this in the next chapter.

(32)

Chapter 2 −− An Introduction to Unicode

In the first chapter, I promised to elaborate on any aspects of C that you might not have encountered in conventional character−mode programming but that play a part in Microsoft Windows. The subject of wide−character sets and Unicode almost certainly qualifies in that respect.

Very simply, Unicode is an extension of ASCII character encoding. Rather than the 7 bits used to represent each character in strict ASCII, or the 8 bits per character that have become common on computers, Unicode uses a full 16 bits for character encoding. This allows Unicode to represent all the letters, ideographs, and other symbols used in all the written languages of the world that are likely to be used in computer communication. Unicode is intended initially to supplement ASCII and, with any luck, eventually replace it. Considering that ASCII is one of the most dominant standards in computing, this is certainly a tall order.

Unicode impacts every part of the computer industry, but perhaps most profoundly operating systems and programming languages. In this respect, we are almost halfway there. Windows NT supports Unicode from the ground up. (Unfortunately, Windows 98 includes only a small amount of Unicode support.) The C programming language as formalized by ANSI inherently supports Unicode through its support of wide characters, which I'll discuss in detail below.

Of course, as usual, we as programmers are confronted with much of the dirty work. I've tried to ease the load by making all of the programs in this book "Unicode−ready." What this means exactly will become more apparent as I discuss Unicode in this chapter.

Références

Documents relatifs

Combien de points devrait enlever une mauvaise réponse pour qu’une personne répondant au hasard ait un total de point

68 Add a Calendar event 70 Go online with Internet Explorer 72 Open Internet Explorer in Desktop view 74 Add and manage favourites 76 Pin a website to the Start menu 77 Surf in

[r]

Recalling the impossibility of doubting his existence and looking back to his “sum”-intuition, the Cartesian

d’attribution précisé par le Fournisseur d’Information et/ou le Contributeur externe d’Information conformément à ce qui est indiqué lorsque vous accédez au serveur de

Dr Parr is a rural family physician practising in Mount Brydges, Ont, and is an Assistant Professor in the Department of Family Medicine at the University of Western Ontario

PHASE 2 - DEVELOP A VISION – WHAT DO WE WANT OUR CLUB TO BE LIKE DÉVELOPPER UNE VISION - QUE VOULONS-NOUS QUE NOTRE CLUB SOIT. • Purpose Statement – How you will be different

(But they are very close to being proportional, so drawing this on a grid paper might lead to a wrong answer)..