programming windows

1431
Copyright© 1998 by Charles Petzold Converted from HTML to Word97 by anarchriz (http://surf.to/anarchriz ), last update: 31 july 1999

Upload: depaksudarsanam

Post on 18-Jun-2015

262 views

Category:

Software


11 download

DESCRIPTION

This is a good reference material for Windows programming.

TRANSCRIPT

  • 1. Copyright 1998 by Charles Petzold Converted from HTML to Word97 by anarchriz (http://surf.to/anarchriz), last update: 31 july 1999

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 [email protected]. 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 2 3. Contents Author's Note ........................................................................................................................................2 Contents..................................................................................................................................................3 Section I: The Basics....................................................................................................................13 Chapter 1 -- Getting Started................................................................................................................13 The Windows Environment..................................................................................................................................13 A History of Windows......................................................................................................................................13 Aspects of Windows.........................................................................................................................................14 Dynamic Linking..............................................................................................................................................16 Windows Programming Options...........................................................................................................................17 APIs and Memory Models................................................................................................................................17 Language Options.............................................................................................................................................18 The Programming Environment........................................................................................................................18 API Documentation...........................................................................................................................................19 Your First Windows Program...............................................................................................................................19 A Character-Mode Model.................................................................................................................................19 The Windows Equivalent..................................................................................................................................20 The Header Files...............................................................................................................................................21 Program Entry Point..........................................................................................................................................21 The MessageBox Function................................................................................................................................22 Compile, Link, and Run....................................................................................................................................23 Chapter 2 -- An Introduction to Unicode...........................................................................................24 A Brief History of Character Sets.........................................................................................................................24 American Standards..........................................................................................................................................24 The World Beyond............................................................................................................................................25 Extending ASCII...............................................................................................................................................25 Double-Byte Character Sets..............................................................................................................................27 Unicode to the Rescue.......................................................................................................................................27 Wide Characters and C.........................................................................................................................................28 The char Data Type...........................................................................................................................................28 Wider Characters...............................................................................................................................................29 Wide-Character Library Functions...................................................................................................................30 Maintaining a Single Source.............................................................................................................................31 Wide Characters and Windows.............................................................................................................................32 Windows Header File Types.............................................................................................................................32 The Windows Function Calls............................................................................................................................33 Windows String Functions..............................................................................................................................34 Using printf in Windows...................................................................................................................................34 A Formatting Message Box..............................................................................................................................36 Internationalization and This Book...................................................................................................................37 Chapter 3 -- Windows and Messages..................................................................................................38 A Window of Ones Own.....................................................................................................................................38 An Architectural Overview...............................................................................................................................38 The HELLOWIN Program................................................................................................................................39 Thinking Globally.............................................................................................................................................42 The Windows Function Calls............................................................................................................................42 New Data Types................................................................................................................................................44 Getting a Handle on Handles............................................................................................................................44 Hungarian Notation...........................................................................................................................................45 Registering the Window Class..........................................................................................................................46 Creating the Window........................................................................................................................................50 Displaying the Window....................................................................................................................................51 3 4. The Message Loop............................................................................................................................................52 The Window Procedure....................................................................................................................................53 Processing the Messages...................................................................................................................................54 Playing a Sound File.........................................................................................................................................54 The WM_PAINT Message...............................................................................................................................55 The WM_DESTROY Message.........................................................................................................................56 The Windows Programming Hurdles...................................................................................................................56 Dont Call Me, Ill Call You.............................................................................................................................56 Queued and Nonqueued Messages...................................................................................................................57 Get In and Out Fast...........................................................................................................................................59 Chapter 4 -- An Exercise in Text Output...........................................................................................60 Painting and Repainting........................................................................................................................................60 The WM_PAINT Message...............................................................................................................................61 Valid and Invalid Rectangles............................................................................................................................61 An Introduction to GDI.........................................................................................................................................62 The Device Context..........................................................................................................................................62 Getting a Device Context Handle: Method One...............................................................................................63 The Paint Information Structure.......................................................................................................................63 Getting a Device Context Handle: Method Two...............................................................................................65 TextOut: The Details.........................................................................................................................................66 The System Font...............................................................................................................................................67 The Size of a Character.....................................................................................................................................68 Text Metrics: The Details.................................................................................................................................68 Formatting Text.................................................................................................................................................70 Putting It All Together......................................................................................................................................70 The SYSMETS1.C Window Procedure............................................................................................................76 Not Enough Room............................................................................................................................................77 The Size of the Client Area...............................................................................................................................77 Scroll Bars.............................................................................................................................................................78 Scroll Bar Range and Position..........................................................................................................................79 Scroll Bar Messages..........................................................................................................................................81 Scrolling SYSMETS.........................................................................................................................................83 Structuring Your Program for Painting.............................................................................................................86 Building a Better Scroll.........................................................................................................................................87 The Scroll Bar Information Functions..............................................................................................................87 How Low Can You Scroll?...............................................................................................................................88 The New SYSMETS.........................................................................................................................................89 But I Dont Like to Use the Mouse...................................................................................................................94 Chapter 5 -- Basic Drawing.................................................................................................................95 The Structure of GDI............................................................................................................................................95 The GDI Philosophy.........................................................................................................................................95 The GDI Function Calls....................................................................................................................................96 The GDI Primitives...........................................................................................................................................97 Other Stuff.........................................................................................................................................................97 The Device Context..............................................................................................................................................98 Getting a Device Context Handle.....................................................................................................................98 Getting Device Context Information...............................................................................................................100 The DEVCAPS1 Program..............................................................................................................................100 The Size of the Device....................................................................................................................................103 Finding Out About Color................................................................................................................................107 The Device Context Attributes.......................................................................................................................109 Saving Device Contexts..................................................................................................................................110 Drawing Dots and Lines.....................................................................................................................................111 Setting Pixels...................................................................................................................................................111 Straight Lines..................................................................................................................................................112 4 5. The Bounding Box Functions.........................................................................................................................116 Bezier Splines.................................................................................................................................................122 Using Stock Pens............................................................................................................................................127 Creating, Selecting, and Deleting Pens...........................................................................................................128 Filling in the Gaps...........................................................................................................................................130 Drawing Modes...............................................................................................................................................130 Drawing Filled Areas..........................................................................................................................................132 The Polygon Function and the Polygon-Filling Mode....................................................................................133 Brushing the Interior.......................................................................................................................................137 The GDI Mapping Mode.....................................................................................................................................139 Device Coordinates and Logical Coordinates.................................................................................................140 The Device Coordinate Systems.....................................................................................................................140 The Viewport and the Window.......................................................................................................................141 Working with MM_TEXT..............................................................................................................................142 The Metric Mapping Modes...........................................................................................................................145 The Roll Your Own Mapping Modes..........................................................................................................147 The WHATSIZE Program..............................................................................................................................152 Rectangles, Regions, and Clipping.....................................................................................................................155 Working with Rectangles................................................................................................................................155 Random Rectangles.........................................................................................................................................156 Creating and Painting Regions........................................................................................................................160 Clipping with Rectangles and Regions...........................................................................................................161 The CLOVER Program...................................................................................................................................161 Chapter 6 -- The Keyboard...............................................................................................................166 Keyboard Basics.................................................................................................................................................166 Ignoring the Keyboard....................................................................................................................................166 Whos Got the Focus?.....................................................................................................................................167 Queues and Synchronization...........................................................................................................................167 Keystrokes and Characters..............................................................................................................................168 Keystroke Messages............................................................................................................................................168 System and Nonsystem Keystrokes................................................................................................................168 Virtual Key Codes...........................................................................................................................................169 The lParam Information..................................................................................................................................172 Shift States......................................................................................................................................................173 Using Keystroke Messages.............................................................................................................................174 Enhancing SYSMETS for the Keyboard........................................................................................................175 Character Messages.............................................................................................................................................180 The Four Character Messages.........................................................................................................................181 Message Ordering...........................................................................................................................................181 Control Character Processing..........................................................................................................................183 Dead-Character Messages...............................................................................................................................183 Keyboard Messages and Character Sets.............................................................................................................184 The KEYVIEW1 Program..............................................................................................................................184 The Foreign-Language Keyboard Problem.....................................................................................................188 Character Sets and Fonts.................................................................................................................................190 What About Unicode?.....................................................................................................................................200 TrueType and Big Fonts.................................................................................................................................201 The Caret (Not the Cursor).................................................................................................................................206 The Caret Functions........................................................................................................................................206 The TYPER Program......................................................................................................................................207 Chapter 7 -- The Mouse.....................................................................................................................213 Mouse Basics......................................................................................................................................................213 Some Quick Definitions..................................................................................................................................214 The Plural of Mouse Is................................................................................................................................214 Client-Area Mouse Messages.............................................................................................................................214 5 6. Simple Mouse Processing: An Example.........................................................................................................216 Processing Shift Keys.....................................................................................................................................219 Mouse Double-Clicks.....................................................................................................................................220 Nonclient-Area Mouse Messages.......................................................................................................................221 The Hit-Test Message.....................................................................................................................................222 Messages Beget Messages..............................................................................................................................223 Hit-Testing in Your Programs.............................................................................................................................223 A Hypothetical Example.................................................................................................................................223 A Sample Program..........................................................................................................................................224 Emulating the Mouse with the Keyboard.......................................................................................................227 Add a Keyboard Interface to CHECKER.......................................................................................................228 Using Child Windows for Hit-Testing............................................................................................................231 Child Windows in CHECKER........................................................................................................................232 Child Windows and the Keyboard..................................................................................................................236 Capturing the Mouse...........................................................................................................................................240 Blocking Out a Rectangle...............................................................................................................................240 The Capture Solution......................................................................................................................................242 The BLOKOUT2 Program..............................................................................................................................243 The Mouse Wheel...............................................................................................................................................246 Still to Come...................................................................................................................................................252 Chapter 8 -- The Timer......................................................................................................................253 Timer Basics.......................................................................................................................................................253 The System and the Timer..............................................................................................................................253 Timer Messages Are Not Asynchronous........................................................................................................254 Using the Timer: Three Methods........................................................................................................................254 Method One.....................................................................................................................................................254 Method Two....................................................................................................................................................257 Method Three..................................................................................................................................................259 Using the Timer for a Clock...............................................................................................................................260 Building a Digital Clock.................................................................................................................................260 Getting the Current Time................................................................................................................................264 Displaying Digits and Colons.........................................................................................................................264 Going International.........................................................................................................................................265 Building an Analog Clock...............................................................................................................................265 Using the Timer for a Status Report...................................................................................................................270 Chapter 9 -- Child Window Controls................................................................................................273 The Button Class.................................................................................................................................................274 Creating the Child Windows...........................................................................................................................277 The Child Talks to Its Parent..........................................................................................................................278 The Parent Talks to Its Child..........................................................................................................................279 Push Buttons...................................................................................................................................................280 Check Boxes...................................................................................................................................................281 Radio Buttons..................................................................................................................................................281 Group Boxes...................................................................................................................................................282 Changing the Button Text...............................................................................................................................282 Visible and Enabled Buttons...........................................................................................................................282 Buttons and Input Focus.................................................................................................................................283 Controls and Colors............................................................................................................................................283 System Colors.................................................................................................................................................284 The Button Colors...........................................................................................................................................285 The WM_CTLCOLORBTN Message............................................................................................................286 Owner-Draw Buttons......................................................................................................................................286 The Static Class...................................................................................................................................................290 The Scroll Bar Class...........................................................................................................................................291 The COLORS1 Program.................................................................................................................................292 6 7. The Automatic Keyboard Interface.................................................................................................................295 Window Subclassing.......................................................................................................................................295 Coloring the Background................................................................................................................................296 Coloring the Scroll Bars and Static Text.........................................................................................................297 The Edit Class.....................................................................................................................................................297 The Edit Class Styles......................................................................................................................................299 Edit Control Notification................................................................................................................................300 Using the Edit Controls...................................................................................................................................300 Messages to an Edit Control...........................................................................................................................301 The Listbox Class................................................................................................................................................302 List Box Styles................................................................................................................................................302 Putting Strings in the List Box........................................................................................................................303 Selecting and Extracting Entries.....................................................................................................................303 Receiving Messages from List Boxes.............................................................................................................304 A Simple List Box Application.......................................................................................................................305 Listing Files.....................................................................................................................................................308 Using file attribute codes................................................................................................................................308 Ordering file lists............................................................................................................................................309 A head for Windows.......................................................................................................................................309 HEAD.C..........................................................................................................................................................309 Chapter 10 -- Menus and Other Resources......................................................................................314 Icons, Cursors, Strings, and Custom Resources..................................................................................................314 Adding an Icon to a Program..........................................................................................................................314 Getting a Handle on Icons...............................................................................................................................318 Using Icons in Your Program.........................................................................................................................320 Using Customized Cursors..............................................................................................................................321 Character String Resources.............................................................................................................................322 Custom Resources...........................................................................................................................................323 Menus..................................................................................................................................................................328 Menu Concepts...............................................................................................................................................329 Menu Structure................................................................................................................................................329 Defining the Menu..........................................................................................................................................329 Referencing the Menu in Your Program.........................................................................................................330 Menus and Messages......................................................................................................................................330 A Sample Program..........................................................................................................................................332 Menu Etiquette................................................................................................................................................337 Defining a Menu the Hard Way......................................................................................................................337 Floating Popup Menus....................................................................................................................................339 Using the System Menu..................................................................................................................................343 Changing the Menu.........................................................................................................................................345 Other Menu Commands..................................................................................................................................346 An Unorthodox Approach to Menus...............................................................................................................347 Keyboard Accelerators........................................................................................................................................350 Why You Should Use Keyboard Accelerators...............................................................................................351 Some Rules on Assigning Accelerators..........................................................................................................351 The Accelerator Table.....................................................................................................................................351 Loading the Accelerator Table........................................................................................................................352 Translating the Keystrokes..............................................................................................................................352 Receiving the Accelerator Messages..............................................................................................................353 POPPAD with a Menu and Accelerators........................................................................................................353 POPPAD2.ICO...............................................................................................................................................358 Enabling Menu Items......................................................................................................................................359 Processing the Menu Options.........................................................................................................................359 Chapter 11 -- Dialog Boxes................................................................................................................362 Modal Dialog Boxes...........................................................................................................................................362 7 8. Creating an "About" Dialog Box....................................................................................................................362 The Dialog Box and Its Template...................................................................................................................366 The Dialog Box Procedure..............................................................................................................................368 Invoking the Dialog Box.................................................................................................................................369 Variations on a Theme....................................................................................................................................369 A More Complex Dialog Box.........................................................................................................................372 Working with Dialog Box Controls................................................................................................................378 The OK and Cancel Buttons...........................................................................................................................380 Avoiding Global Variables.............................................................................................................................381 Tab Stops and Groups.....................................................................................................................................382 Painting on the Dialog Box.............................................................................................................................383 Using Other Functions with Dialog Boxes.....................................................................................................384 Defining Your Own Controls..........................................................................................................................384 Modeless Dialog Boxes......................................................................................................................................390 Differences Between Modal and Modeless Dialog Boxes..............................................................................391 The New COLORS Program..........................................................................................................................392 HEXCALC: Window or Dialog Box?............................................................................................................397 The Common Dialog Boxes................................................................................................................................403 POPPAD Revisited.........................................................................................................................................404 Unicode File I/O..............................................................................................................................................422 Changing the Font...........................................................................................................................................422 Search and Replace.........................................................................................................................................422 The One-Function-Call Windows Program....................................................................................................423 Chapter 12 -- The Clipboard.............................................................................................................425 Simple Use of the Clipboard...............................................................................................................................425 The Standard Clipboard Data Formats............................................................................................................425 Memory Allocation.........................................................................................................................................426 Transferring Text to the Clipboard.................................................................................................................428 Getting Text from the Clipboard.....................................................................................................................429 Opening and Closing the Clipboard................................................................................................................429 The Clipboard and Unicode............................................................................................................................430 Beyond Simple Clipboard Use............................................................................................................................434 Using Multiple Data Items..............................................................................................................................435 Delayed Rendering..........................................................................................................................................436 Private Data Formats.......................................................................................................................................437 Becoming a Clipboard Viewer............................................................................................................................438 The Clipboard Viewer Chain..........................................................................................................................438 Clipboard Viewer Functions and Messages....................................................................................................439 A Simple Clipboard Viewer............................................................................................................................441 Section II: More Graphics.........................................................................................................444 Chapter 13 -- Using the Printer.........................................................................................................444 Printing Fundamentals........................................................................................................................................444 Printing and Spooling......................................................................................................................................444 The Printer Device Context.............................................................................................................................448 The Revised DEVCAPS Program...................................................................................................................450 The PrinterProperties Call...............................................................................................................................458 Checking for BitBlt Capability.......................................................................................................................458 The Simplest Printing Program.......................................................................................................................459 Printing Graphics and Text.................................................................................................................................460 Bare-Bones Printing........................................................................................................................................462 Implementing an Abort Procedure..................................................................................................................465 Adding a Printing Dialog Box........................................................................................................................467 Adding Printing to POPPAD..........................................................................................................................470 Chapter 14 -- Bitmaps and Bitblts....................................................................................................477 8 9. Bitmap Basics.....................................................................................................................................................477 Bitmap Dimensions.............................................................................................................................................478 Color and Bitmaps..........................................................................................................................................479 Real-World Devices .......................................................................................................................................479 Bitmap Support in GDI...................................................................................................................................481 The Bit-Block Transfer.......................................................................................................................................482 A Simple BitBlt...............................................................................................................................................482 Stretching the Bitmap......................................................................................................................................486 The StretchBlt Mode.......................................................................................................................................489 The Raster Operations.....................................................................................................................................489 The Pattern Blt................................................................................................................................................491 The GDI Bitmap Object......................................................................................................................................494 Creating a DDB...............................................................................................................................................494 The Bitmap Bits..............................................................................................................................................496 The Memory Device Context..........................................................................................................................497 Loading Bitmap Resources.............................................................................................................................497 The Monochrome Bitmap Format...................................................................................................................501 Brushes from Bitmaps.....................................................................................................................................504 Drawing on Bitmaps.......................................................................................................................................506 The Shadow Bitmap........................................................................................................................................510 Using Bitmaps in Menus.................................................................................................................................513 Nonrectangular Bitmap Images......................................................................................................................526 Some Simple Animation.................................................................................................................................531 Bitmaps Outside the Window.........................................................................................................................535 Chapter 15 -- The Device-Independent Bitmap...............................................................................545 The DIB File Format...........................................................................................................................................545 The OS/2-Style DIB........................................................................................................................................546 Bottoms Up!....................................................................................................................................................548 The DIB Pixel Bits..........................................................................................................................................548 The Expanded Windows DIB.........................................................................................................................549 Reality Check..................................................................................................................................................551 DIB Compression ...........................................................................................................................................553 Color Masking.................................................................................................................................................555 The Version 4 Header.....................................................................................................................................558 The Version 5 Header.....................................................................................................................................561 Displaying DIB Information...........................................................................................................................562 Displaying and Printing......................................................................................................................................570 Digging into the DIB.......................................................................................................................................570 Pixel to Pixel...................................................................................................................................................572 The Topsy-Turvy World of DIBs...................................................................................................................581 Sequential Display..........................................................................................................................................589 Stretching to Fit...............................................................................................................................................596 Color Conversion, Palettes, and Performance................................................................................................605 The Union of DIBs and DDBs............................................................................................................................606 Creating a DDB from a DIB...........................................................................................................................607 From DDB to DIB...........................................................................................................................................613 The DIB Section..............................................................................................................................................614 More DIB Section Differences.......................................................................................................................621 The File-Mapping Option...............................................................................................................................622 In Summary.....................................................................................................................................................623 Chapter 16 -- The Palette Manager..................................................................................................624 Using Palettes......................................................................................................................................................624 Video Hardware..............................................................................................................................................624 Displaying Gray Shades..................................................................................................................................625 The Palette Messages......................................................................................................................................632 9 10. The Palette Index Approach............................................................................................................................632 Querying the Palette Support..........................................................................................................................634 The System Palette..........................................................................................................................................635 Other Palette Functions...................................................................................................................................635 The Raster-Op Problem..................................................................................................................................636 Looking at the System Palette.........................................................................................................................636 Palette Animation................................................................................................................................................645 The Bouncing Ball..........................................................................................................................................645 One-Entry Palette Animation..........................................................................................................................650 Engineering Applications................................................................................................................................655 Palettes and Real-World Images.........................................................................................................................659 Palettes and Packed DIBs...............................................................................................................................659 The All-Purpose Palette..................................................................................................................................669 The Halftone Palette........................................................................................................................................675 Indexing Palette Colors...................................................................................................................................680 Palettes and Bitmap Objects...........................................................................................................................685 Palettes and DIB Sections...............................................................................................................................690 A Library for DIBs..............................................................................................................................................696 The DIBSTRUCT Structure............................................................................................................................697 The Information Functions..............................................................................................................................698 Reading and Writing Pixels............................................................................................................................704 Creating and Converting.................................................................................................................................708 The DIBHELP Header File and Macros.........................................................................................................710 The DIBBLE Program....................................................................................................................................712 Simple Palettes; Optimized Palettes................................................................................................................735 Converting Formats.........................................................................................................................................748 Chapter 17 -- Text and Fonts............................................................................................................753 Simple Text Output.............................................................................................................................................753 The Text Drawing Functions..........................................................................................................................753 Device Context Attributes for Text.................................................................................................................755 Using Stock Fonts...........................................................................................................................................756 Background on Fonts..........................................................................................................................................757 The Types of Fonts.........................................................................................................................................757 TrueType Fonts...............................................................................................................................................758 Attributes or Styles?........................................................................................................................................758 The Point Size.................................................................................................................................................759 Leading and Spacing.......................................................................................................................................759 The Logical Inch Problem...............................................................................................................................759 The Logical Font.................................................................................................................................................760 Logical Font Creation and Selection...............................................................................................................760 The PICKFONT Program...............................................................................................................................761 The Logical Font Structure.............................................................................................................................774 The Font-Mapping Algorithm.........................................................................................................................777 Finding Out About the Font............................................................................................................................778 Character Sets and Unicode............................................................................................................................780 The EZFONT System.....................................................................................................................................781 Font Rotation...................................................................................................................................................788 Font Enumeration................................................................................................................................................790 The Enumeration Functions............................................................................................................................790 The ChooseFont Dialog..................................................................................................................................791 Paragraph Formatting..........................................................................................................................................799 Simple Text Formatting..................................................................................................................................799 Working with Paragraphs................................................................................................................................800 Previewing Printer Output..............................................................................................................................808 The Fun and Fancy Stuff.....................................................................................................................................817 The GDI Path..................................................................................................................................................817 10 11. Extended Pens.................................................................................................................................................818 Four Sample Programs....................................................................................................................................821 Chapter 18 -- Metafiles......................................................................................................................830 The Old Metafile Format....................................................................................................................................830 Simple Use of Memory Metafiles...................................................................................................................830 Storing Metafiles on Disk...............................................................................................................................833 Old Metafiles and the Clipboard.....................................................................................................................834 Enhanced Metafiles.............................................................................................................................................837 The Basic Procedure.......................................................................................................................................837 Looking Inside................................................................................................................................................841 Metafiles and GDI Objects.............................................................................................................................846 Metafiles and Bitmaps....................................................................................................................................850 Enumerating the Metafile................................................................................................................................852 Embedding Images..........................................................................................................................................858 An Enhanced Metafile Viewer and Printer.....................................................................................................861 Displaying Accurate Metafile Images.............................................................................................................870 Scaling and Aspect Ratios...............................................................................................................................878 Mapping Modes in Metafiles..........................................................................................................................879 Mapping and Playing......................................................................................................................................882 Section III: Advanced Topics.....................................................................................................886 Chapter 19 -- The Multiple-Document Interface.............................................................................886 MDI Concepts.....................................................................................................................................................886 The Elements of MDI.....................................................................................................................................886 MDI Support...................................................................................................................................................887 A Sample MDI Implementation..........................................................................................................................888 Three Menus...................................................................................................................................................898 Program Initialization.....................................................................................................................................899 Creating the Children......................................................................................................................................900 More Frame Window Message Processing.....................................................................................................900 The Child Document Windows.......................................................................................................................901 Cleaning Up....................................................................................................................................................902 Chapter 20 -- Multitasking and Multithreading..............................................................................903 Modes of Multitasking........................................................................................................................................903 Multitasking Under DOS?..............................................................................................................................903 Nonpreemptive Multitasking..........................................................................................................................903 PM and the Serialized Message Queue...........................................................................................................904 The Multithreading Solution...........................................................................................................................905 Multithreaded Architecture.............................................................................................................................905 Thread Hassles................................................................................................................................................906 The Windows Advantage................................................................................................................................906 New! Improved! Now with Threads!..............................................................................................................907 Windows Multithreading....................................................................................................................................907 Random Rectangles Revisited........................................................................................................................908 The Programming Contest Problem................................................................................................................910 The Multithreaded Solution............................................................................................................................916 Any Problems?................................................................................................................................................923 The Benefits of Sleep......................................................................................................................................923 Thread Synchronization......................................................................................................................................924 The Critical Section........................................................................................................................................924 Event Signaling...................................................................................................................................................925 The BIGJOB1 Program...................................................................................................................................925 The Event Object............................................................................................................................................929 Thread Local Storage..........................................................................................................................................933 Chapter 21 -- Dynamic-Link Libraries.............................................................................................935 11 12. Library Basics.....................................................................................................................................................935 Miscellaneous DLL Topics.................................................................................................................................948 Chapter 22 -- Sound and Music........................................................................................................953 Windows and Multimedia...................................................................................................................................953 Multimedia Hardware.....................................................................................................................................953 An API Overview............................................................................................................................................953 Exploring MCI with TESTMCI......................................................................................................................954 MCITEXT and CD Audio...............................................................................................................................958 Waveform Audio.................................................................................................................................................962 Sound and Waveforms....................................................................................................................................962 Pulse Code Modulation...................................................................................................................................963 The Sampling Rate..........................................................................................................................................963 The Sample Size..............................................................................................................................................964 Generating Sine Waves in Software...............................................................................................................964 A Digital Sound Recorder...............................................................................................................................972 The MCI Alternative.......................................................................................................................................976 The MCI Command String Approach.............................................................................................................982 The Waveform Audio File Format..................................................................................................................986 Experimenting with Additive Synthesis.........................................................................................................987 Waking Up to Waveform Audio.....................................................................................................................994 MIDI and Music................................................................................................................................................1000 The Workings of MIDI.................................................................................................................................1001 The Program Change....................................................................................................................................1002 The MIDI Channel........................................................................................................................................1002 MIDI Messages.............................................................................................................................................1003 An Introduction to MIDI Sequencing...........................................................................................................1005 Playing a MIDI Synthesizer from the PC Keyboard.....................................................................................1010 A MIDI Drum Machine................................................................................................................................1023 The Multimedia time Functions....................................................................................................................1035 RIFF File I/O.................................................................................................................................................1037 Chapter 23 -- A Taste of the Internet..............................................................................................1040 Windows Sockets..............................................................................................................................................1040 Sockets and TCP/IP......................................................................................................................................1040 Network Time Services.................................................................................................................................1040 The NETTIME Program...............................................................................................................................1041 WinInet and FTP...............................................................................................................................................1046 Overview of the FTP API.............................................................................................................................1047 The Update Demo.........................................................................................................................................1048 About.................................................................................................................................................1052 About the Author..............................................................................................................................................1052 About This Electronic Book.............................................................................................................................1052 Expanding Graphics..................................................................................................................................1052 12 13. Section I: The Basics 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 Ill 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 users 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 dont 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 dont show up much in character-mode programming; in those cases, Ill 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, Ill be assuming that youre using Microsoft Visual C++ 6.0, which can be purchased separately or as a part of the Visual Studio 6.0 package. Thats it. Im not going to assume that you have any experience at all programming for a graphical user interface such as Windows. The Windows Environment Windows hardly needs an introduction. Yet its 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 Macs 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 13 14. 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 Intels 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 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 ve