Programming Microsoft Windows with C# Programming Microsoft Windows with C# by Charles Petzold Microsoft Press © 2002 For the great people from [OR] Forum Enjoy Programming Microsoft Windows with C# Charles Petzold PUBLISHED BY Microsoft Press A Division of Microsoft Corporation One Microsoft Way Redmond, Washington 98052-6399 Copyright © 2002 by Charles Petzold All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any means without the written permission of the publisher. Library of Congress Cataloging-in-Publication Data Petzold, Charles, 1953- Programming Microsoft Windows with C# / Charles Petzold. p. cm. Includes index. ISBN 0-7356-1370-2 1. C# (Computer program language) 2. Microsoft Windows (Computer file) I. Title. QA76.73.C154 P48 2001 005.26'8--dc21 2001052178 1 2 3 4 5 6 7 8 9 QWT 7 6 5 4 3 2 Distributed in Canada by Penguin Books Canada Limited. A CIP catalogue record for this book is available from the British Library. Microsoft Press books are available through booksellers and distributors worldwide. For further information about international editions, contact your local Microsoft Corporation office or contact Microsoft Press International directly at fax (425) 936-7329. Visit our Web site at www.microsoft.com/mspress. Send comments to mspinput@microsoft.com. ClearType, Georgia, IntelliMouse, Microsoft, Microsoft Press, MS-DOS, MSDN, Natural, the .NET logo, OpenType, Verdana, Visual Basic, Visual C#, Visual Studio, Webdings, Win32, Windows, Windows NT, and Wingdings are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. Other product and company names mentioned herein may be the trademarks of their respective owners. The example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious. No association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred. Acquisitions Editor: Danielle Bird Project Editor: Sally Stickney Technical Editor: Jean Ross Body Part No. X08-22413 About The Author Charles Petzold Charles Petzold (www.charlespetzold.com) is a full-time freelance writer who has been programming for Microsoft Windows since 1985 and writing about Windows programming for nearly as long. He wrote the very first magazine article about Windows programming for the December 1986 issue of Microsoft Systems Journal. His book Programming Windows (first published by Microsoft Press in 1988 and currently in its fifth edition) taught a generation of programmers how to write applications for Windows. 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. He is also the author of a unique introduction to the inner workings of computers entitled Code: The Hidden Language of Computer Hardware and Software. Petzold is currently researching a book on the historical origins of software. The manuscript for this book was prepared and galleyed using Microsoft Word version 2000. Pages were composed by Microsoft Press using Adobe PageMaker 6.52 for Windows, with text in Garamond and display type in Helvetica Condensed. Composed pages were delivered to the printer as electronic prepress files. Cover Designer: Methodologie, Inc. Interior Graphic Designer: James D. Kramer Principal Compositor: Paula Gorelick Interior Artist: Joel Panchot Principal Copy Editor: Holly M. Viola Indexer: Shane-Armstrong Information Systems PROGRAMMING MICROSOFT WINDOWS WITH C# 2 WINDOWS PROGRAMMING: AN OVERVIEW 14 USER REQUIREMENTS .15 S YSTEM R EQUIREMENTS 16 THE ORGANIZATION OF THIS BOOK .16 THE CD-ROM .17 SUPPORT 17 SPECIAL THANKS 17 CHAPTER 1: CONSOLE THYSELF 19 OVERVIEW 19 THE C# VERSION 19 ANATOMY OF A PROGRAM 21 C# NAMESPACES .22 CONSOLE I/O .23 C# DATA TYPES 25 EXPRESSIONS AND OPERATORS 29 CONDITIONS AND ITERATIONS .31 T HE L EAP TO O BJECTS .34 PROGRAMMING IN THE KEY OF C# .38 STATIC METHODS .40 EXCEPTION HANDLING 41 THROWING EXCEPTIONS 43 GETTING AND SETTING PROPERTIES 44 CONSTRUCTORS .47 INSTANCES AND INHERITANCE 51 A BIGGER PICTURE 54 NAMING CONVENTIONS .55 BEYOND THE CONSOLE .56 CHAPTER 2: HELLO, WINDOWS FORMS .57 OVERVIEW 57 THE MESSAGE BOX 58 THE FORM 63 SHOWING THE FORM .64 I T ' S AN A PPLICATION AND W E W ANT TO R UN I T .66 VARIATIONS ON A THEME .68 FORM PROPERTIES 68 EVENT-DRIVEN INPUT 70 HANDLING THE PAINT EVENT 71 DISPLAYING TEXT .74 The Font .74 The Brush 75 The Coordinate Points .75 THE PAINT EVENT IS SPECIAL! .78 MULTIPLE FORMS, MULTIPLE HANDLERS 78 INHERITING FORMS 80 THE ONPAINT METHOD .82 DOES MAIN BELONG HERE? .83 EVENTS AND "ON" METHODS 85 CHAPTER 3: ESSENTIAL STRUCTURES 89 OVERVIEW 89 CLASSES AND STRUCTURES 89 TWO-DIMENSIONAL COORDINATE POINTS .90 A RRAYS OF P OINTS 92 THE SIZE STRUCTURE .92 T HE F LOAT V ERSIONS .93 A RECTANGLE IS A POINT AND A SIZE 95 RECTANGLE PROPERTIES AND METHODS .96 A NICE-SIZED FORM 98 THE FORM AND THE CLIENT .99 POINT CONVERSIONS 102 THE COLOR STRUCTURE 103 THE 141 COLOR NAMES .104 PENS AND BRUSHES 104 S YSTEM C OLORS 106 THE KNOWN COLORS 108 W HAT TO U SE ? .109 GETTING A FEEL FOR REPAINTS .109 CENTERING HELLO WORLD .112 MEASURING THE STRING 115 TEXT IN A RECTANGLE 117 CHAPTER 4: AN EXERCISE IN TEXT OUTPUT .120 OVERVIEW 120 SYSTEM INFORMATION 120 SPACING LINES OF TEXT 120 PROPERTY VALUES 121 FORMATTING INTO COLUMNS 123 EVERYTHING IS AN OBJECT .125 L ISTING THE S YSTEM I NFORMATION 130 WINDOWS FORMS AND SCROLL BARS 132 SCROLLING A PANEL CONTROL 132 THE HERITAGE OF SCROLLABLECONTROL 136 SCROLLING WITHOUT CONTROLS 136 ACTUAL NUMBERS 138 DON'T BE A PIG .141 REFLECTING ON THE FUTURE .142 CHAPTER 5: LINES, CURVES, AND AREA FILLS .149 OVERVIEW 149 HOW TO GET A GRAPHICS OBJECT .149 PENS, BRIEFLY 150 STRAIGHT LINES .151 AN INTRODUCTION TO PRINTING 152 PROPERTIES AND STATE 157 ANTI-ALIASING .158 M ULTIPLE C ONNECTED L INES .160 CURVES AND PARAMETRIC EQUATIONS .164 T HE U BIQUITOUS R ECTANGLE 167 GENERALIZED POLYGONS 169 EASIER ELLIPSES 170 ARCS AND PIES .171 FILLING RECTANGLES, ELLIPSES, AND PIES .177 OFF BY 1 .178 POLYGONS AND THE FILLING MODE 180 CHAPTER 6: TAPPING INTO THE KEYBOARD 184 OVERVIEW 184 IGNORING THE KEYBOARD .184 WHO'S GOT THE FOCUS? .184 KEYS AND CHARACTERS .185 K EYS D OWN AND K EYS U P 186 THE KEYS ENUMERATION .187 T ESTING THE M ODIFIER K EYS .194 REALITY CHECK 195 A KEYBOARD INTERFACE FOR SYSINFO .196 KEYPRESS FOR CHARACTERS 197 CONTROL CHARACTERS .198 LOOKING AT THE KEYS 199 INVOKING THE WIN32 API 203 HANDLING INPUT FROM FOREIGN KEYBOARDS 205 INPUT FOCUS .207 T HE M ISSING C ARET .208 ECHOING KEY CHARACTERS .212 R IGHT - TO -L EFT P ROBLEMS .216 CHAPTER 7: PAGES AND TRANSFORMS .218 OVERVIEW 218 DEVICE INDEPENDENCE THROUGH TEXT .218 HOW MUCH IS THAT IN REAL MONEY? .218 DOTS PER INCH 220 WHAT'S WITH THE PRINTER? .221 MANUAL CONVERSIONS 222 PAGE UNITS AND PAGE SCALE .225 PEN WIDTHS 228 PAGE TRANSFORMS .231 SAVING THE GRAPHICS STATE 232 METRICAL DIMENSIONS 233 ARBITRARY COORDINATES 237 WHAT YOU CAN'T DO 239 HELLO, WORLD TRANSFORM 240 THE BIG PICTURE .244 LINEAR TRANSFORMS 244 I NTRODUCING M ATRIXES 246 THE MATRIX CLASS .248 S HEAR AND S HEAR A LIKE 250 COMBINING TRANSFORMS 252 CHAPTER 8: TAMING THE MOUSE 254 O VERVIEW 254 THE DARK SIDE OF THE MOUSE .254 IGNORING THE MOUSE 255 SOME QUICK DEFINITIONS .255 INFORMATION ABOUT THE MOUSE .255 THE MOUSE WHEEL .256 THE FOUR BASIC MOUSE EVENTS .257 DOING THE WHEEL .259 MOUSE MOVEMENT .262 T RACKING AND C APTURING THE M OUSE 264 ADVENTURES IN TRACKING 267 G ENERALIZING C ODE WITH I NTERFACES .274 CLICKS AND DOUBLE-CLICKS 277 MOUSE-RELATED PROPERTIES 278 ENTERING, LEAVING, HOVERING .279 THE MOUSE CURSOR 280 AN EXERCISE IN HIT-TESTING .287 ADDING A KEYBOARD INTERFACE 289 PUTTING THE CHILDREN TO WORK 291 HIT-TESTING TEXT .296 S CRIBBLING WITH THE M OUSE 297 CHAPTER 9: TEXT AND FONTS .303 OVERVIEW 303 F ONTS U NDER W INDOWS .303 TALKING TYPE .303 FONT HEIGHTS AND LINE SPACING 305 DEFAULT FONTS .306 VARIATION ON A FONT .306 CREATING FONTS BY NAME .309 A POINT SIZE BY ANY OTHER NAME… .313 CLASH OF THE UNITS .317 FONT PROPERTIES AND METHODS 319 NEW FONTS FROM FONTFAMILY 324 UNDERSTANDING THE DESIGN METRICS 326 ARRAYS OF FONT FAMILIES .329 FONT COLLECTIONS .335 VARIATIONS ON DRAWSTRING 336 ANTI-ALIASED TEXT .337 MEASURING THE STRING 339 THE STRINGFORMAT OPTIONS .340 G RID F ITTING AND T EXT F ITTING .341 HORIZONTAL AND VERTICAL ALIGNMENT .343 T HE H OTKEY D ISPLAY .348 A CLIP AND A TRIM .349 START A TAB 356 CHAPTER 10: THE TIMER AND TIME 363 OVERVIEW 363 THE TIMER CLASS 363 THE DATETIME STRUCTURE 366 LOCAL TIME AND UNIVERSAL TIME 368 THE TICK COUNT 370 CALENDARS AROUND THE WORLD 372 A READABLE RENDITION 374 A SIMPLE CULTURE-SPECIFIC CLOCK 378 T HE R ETRO L OOK .383 AN ANALOG CLOCK 388 A L ITTLE P UZZLE C ALLED J EU DE T AQUIN .394 CHAPTER 11: IMAGES AND BITMAPS 401 OVERVIEW 401 BITMAP SUPPORT OVERVIEW 402 BITMAP FILE FORMATS 402 LOADING AND DRAWING .405 IMAGE INFORMATION 409 RENDERING THE IMAGE .413 FITTING TO A RECTANGLE 415 ROTATE AND SHEAR 420 DISPLAYING PART OF THE IMAGE .421 DRAWING ON THE IMAGE 426 M ORE ON THE I MAGE C LASS .430 THE BITMAP CLASS 433 HELLO WORLD WITH A BITMAP .435 THE SHADOW BITMAP .437 BINARY RESOURCES .439 ANIMATION 443 THE IMAGE LIST 449 THE PICTURE BOX 452 CHAPTER 12: BUTTONS AND LABELS AND SCROLLS (OH MY!) .456 OVERVIEW 456 BUTTONS AND CLICKS .456 KEYBOARD AND MOUSE 459 CONTROL ISSUES .460 DEEPER INTO BUTTONS 460 APPEARANCE AND ALIGNMENT .464 BUTTONS WITH BITMAPS 466 M ULTIPLE H ANDLERS OR O NE ? 469 DRAWING YOUR OWN BUTTONS 469 DROPPING ANCHOR .474 DOCK AROUND THE CLOCK .477 CHILDREN OF THE FORM 480 Z-ORDER 482 THE CHECK BOX .482 THE THREE-STATE ALTERNATIVE 486 THE LABEL CONTROL 486 TAB STOPS AND TAB ORDER .489 IDENTIFYING THE CONTROLS .489 T HE A UTO -S CALE O PTION .492 How the Windows Forms Designer Uses Auto-Scale 493 Creative AutoScaleBaseSize Settings 493 Inside Auto-Scale .494 A HEXADECIMAL CALCULATOR .496 RADIO BUTTONS AND GROUP BOXES .501 SCROLL BARS 504 THE TRACK BAR ALTERNATIVE .511 CHAPTER 13: BÉZIERS AND OTHER SPLINES .516 OVERVIEW 516 THE BÉZIER SPLINE IN PRACTICE 516 A MORE STYLISH CLOCK .520 COLLINEAR BÉZIERS 523 C IRCLES AND A RCS WITH B ÉZIERS 525 BÉZIER ART 528 THE MATHEMATICAL DERIVATION 529 THE CANONICAL SPLINE .533 CANONICAL CURVE DERIVATION 539 CHAPTER 14: MENUS 543 OVERVIEW 543 MENUS AND MENU ITEMS .543 MENU SHORTCUT KEYS 545 YOUR FIRST MENU .547 UNCONVENTIONAL MENUS .550 MENUITEM PROPERTIES AND EVENTS 552 CHECKING THE ITEMS 554 WORKING WITH CONTEXT MENUS .557 THE MENU ITEM COLLECTION .561 THE STANDARD MENU (A PROPOSAL) .565 THE OWNER-DRAW OPTION 570 CHAPTER 15: PATHS, REGIONS, AND CLIPPING 580 OVERVIEW 580 A PROBLEM AND ITS SOLUTION 580 THE PATH, MORE FORMALLY 584 C REATING THE P ATH .586 RENDERING THE PATH 589 P ATH T RANSFORMS .593 OTHER PATH MODIFICATIONS .595 CLIPPING WITH PATHS .602 CLIPPING BITMAPS .607 REGIONS AND CLIPPING .610 CHAPTER 16: DIALOG BOXES .613 OVERVIEW 613 YOUR FIRST MODAL DIALOG BOX 613 MODAL DIALOG BOX TERMINATION .617 ACCEPT AND CANCEL 619 SCREEN LOCATION 621 THE ABOUT BOX .623 D EFINING P ROPERTIES IN D IALOG B OXES .626 IMPLEMENTING AN APPLY BUTTON 632 THE MODELESS DIALOG BOX 635 THE COMMON DIALOG BOXES 639 CHOOSING FONTS AND COLORS 639 USING THE WINDOWS REGISTRY .646 THE OPEN FILE DIALOG BOX .650 THE SAVE FILE DIALOG BOX .657 CHAPTER 17: BRUSHES AND PENS .660 OVERVIEW 660 FILLING IN SOLID COLORS 660 HATCH BRUSHES 661 THE RENDERING ORIGIN 669 TEXTURE BRUSHES 672 LINEAR GRADIENT BRUSHES .677 PATH GRADIENT BRUSHES 685 T ILING THE B RUSH .690 PENS CAN BE BRUSHES TOO .699 A DASH OF STYLE 702 [...]... currently one of the most popular approaches to Windows programming A good place to learn about MFC is the book Programming Windows with MFC (2nd edition, Microsoft Press, 1999) by Jeff Prosise For the more advanced Windows programmer, I also want to recommend Programming Applications for Microsoft Windows (Microsoft Press, 1999) by Jeffrey Richter From my view, Windows Forms is much better designed than... most dramatically in Windows NT (1993) and Windows 95 (1995), when Windows moved from a 16-bit to a 32-bit architecture When Windows was first released, there was really only one way to write Windows applications, and that was by using the C programming language to access the Windows application programming interface (API) Although it was also possible to access the Windows API using Microsoft Pascal,... you may have, go to: http://www .microsoft. com/mspress/support/search.asp If you have comments, questions, or ideas regarding this book or the companion CD-ROM, please send them to Microsoft Press using either of the following methods: Postal Mail: Microsoft Press Attn: Programming Microsoft Windows with C# Editor One Microsoft Way Redmond, WA 98052-6399 E-mail: MSPINPUT @MICROSOFT. COM Please note that... independent I chose to use C# for this book because C# and NET were—in a very real sense—made for each other Because of the language-neutral aspect of the NET Framework, you may be able to use this book to learn how to write Windows Forms applications with other NET languages Windows Programming: An Overview Microsoft released the first version of Windows in the fall of 1985 Since then, Windows has been progressively... C-based language: How to Write a Windows Application Using a C-Based Language (Microsoft- Centric View) Year Introduced Language Interface 1985 C Windows application programming interface (API) 1992 C++ Microsoft Foundation Class (MFC) Library 2001 C# or C++ Windows Forms (part of the NET Framework) It's not my job to tell you what language or interface you should use to write Windows applications That's... that run under Microsoft Windows There are a number of ways to write such programs In this book, I use the new object-oriented programming language C# (pronounced "C sharp") and a modern class library called Windows Forms The Windows Forms class library is part of the Microsoft NET ("dot net") Framework unveiled in the summer of 2000 and introduced about a year and a half later The Microsoft NET Framework... want more background and skill in working with the language, other books on C# are available, and many others will undoubtedly become available as the language becomes more popular The book Inside C# (Microsoft Press, 2001) by Tom Archer provides information on writing C# code and also on what's going on beneath the surface Microsoft Visual C# Step by Step (Microsoft Press, 2001) by John Sharp and Jon... make reference to the Windows API in this book Like I said previously, you can consult my book Programming Windows to learn more about the API System Requirements As I mentioned in the preceding section, to use this book effectively, you need to be able to compile and run C# programs System requirements are as follows: § Microsoft NET Framework SDK (minimum); Microsoft Visual C# or Microsoft Visual Studio... NET (preferred) § Microsoft Windows NT 4.0, Windows 2000, or Windows XP To run your C# programs on other computers requires that the NET runtime (also referred to as the NET Framework redistributable package) be installed on those machines That package comes with the NET Framework SDK, Visual C#, and Visual Studio NET The redistributable package can be installed on the versions of Windows already mentioned... doing Windows programming, including Visual Basic and C++ Both C++ and C# are object-oriented languages that support most of the types, operators, expressions, and statements of the C programming language For this reason, C++ and C# (as well as Java) are sometimes called C-based languages, or languages of the C family With the introduction of NET, Microsoft currently offers three approaches to writing Windows . Programming Microsoft Windows with C# Programming Microsoft Windows with C# by Charles Petzold Microsoft Press © 2002 For the. [OR] Forum Enjoy Programming Microsoft Windows with C# Charles Petzold PUBLISHED BY Microsoft Press A Division of Microsoft Corporation One Microsoft Way