Tải bản đầy đủ (.pdf) (841 trang)

windows forms in action 2nd edition

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (13.09 MB, 841 trang )

Windows Forms in Action

Windows Forms

in Action
Second Edition of

Windows Forms Programming with C#
ERIK BROWN
MANNING
Greenwich
(74° w. long.)
For online information and ordering of this and other Manning books,
go to www.manning.com. The publisher offers discounts on this book
when ordered in quantity. For more information, please contact:
Special Sales Department
Manning Publications Co.
209 Bruce Park Avenue Fax: (203) 661-9018
Greenwich, CT 06830 email:
©2006 by Manning Publications Co. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
in any form or by means electronic, mechanical, photocopying, or otherwise, without prior
written permission of the publisher.
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial
caps or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy to have the
books we publish printed on acid-free paper, and we exert our best efforts to that end.
Manning Publications Co. Copyeditor: Liz Welch


209 Bruce Park Avenue Typesetter: Dottie Marsico
Greenwich, CT 06830 Cover designer: Leslie Haimes
ISBN 1932394-65-6
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – VHG – 10 09 08 07 06
In memory of Thelma Rose Wilson,
and for her beautiful daughter, whom I still love

vii
brief contents
Part 1 Hello Windows Forms 1
1 Getting started with Windows Forms 3
2 Getting started with Visual Studio 33
Part 2 Basic Windows Forms 63
3Menus 67
4 Context menu and status strips 92
5 Reusable libraries 116
6 Files and common dialog boxes 148
7 Dialog boxes 180
8 Text boxes 212
9 Buttons 240
10 Handling user input and encryption 268
11 List boxes 299
12 Combo boxes 327
13 Tab controls and pages 356
14 Dates, calendars, and progress bars 383
15 Bells and whistles 415
16 Tool strips 443
viii
Part 3 Advanced Windows Forms 475

17 Custom controls 477
18 Explorer interfaces and tree views 507
19 List views 541
20 Multiple document interfaces 575
21 Data binding 608
22 Two-way binding and binding sources 637
23 Odds and ends .NET 665
appendix A C# primer 701
appendix B .NET namespaces 735
appendix C Visual index 741
appendix D For more information 758
ix
contents
preface xix
preface to the first edition xxi
acknowledgments xxiii
about this book xxv
what’s new in 2.0 xxxiii
about the cover illustration xxxv
Part 1 Hello Windows Forms 1
1 Getting started with Windows Forms 3
1.1 Programming in C# 4
Namespaces and classes 6 ✦ Constructors and methods 8
C# types 8
✦ The Main method 11 ✦ The Application
class 12
✦ Program execution 13
1.2 Windows Forms controls 14
The using directive 15 ✦ The Control class 17
The Controls property 18

1.3 Loading files 19
Events 21 ✦ The OpenFileDialog class 23 ✦ Bitmap
images 26
1.4 Resizing forms 26
The Anchor property 29 ✦ The Dock property 30
1.5 Recap 32
2 Getting started with Visual Studio 33
2.1 Programming with Visual Studio 34
Creating a project 35 ✦ Executing a program 37
Viewing the source code 38
x
2.2 Windows Forms controls 43
The AssemblyInfo file 43 ✦ Renaming a form 46
The Toolbox window 46
2.3 Loading files 52
Handling events in Visual Studio 52 ✦ Handling exceptions 56
2.4 Resizing forms 58
Assigning the Anchor property 58 ✦ Assigning the Dock
property 60
2.5 Recap 61
Part 2 Basic Windows Forms 63
3Menus 67
3.1 Controls and containers 68
Control classes 68 ✦ Container classes 70
3.2 The nature of menus 72
Menu terminology 72 ✦ Menus in .NET 73
3.3 Menu bars 75
Adding a menu strip 75 ✦ Adding a menu item 78
Adding drop-down menu items 81
3.4 Menu handling 87

Adding handlers via the designer window 87
Adding handlers via the properties window 88
3.5 Recap 90
4 Context menu and status strips 92
4.1 Context menu strips 93
Creating a context menu 94 ✦ Adding items to a context
menu 95
✦ Sharing a context menu 97
4.2 Drop-down events and event arguments 99
Handling a submenu item click 100 ✦ Altering a submenu before
it appears 105
4.3 Status strips 108
Creating a status strip 108 ✦ Adding status strip labels 109
4.4 Recap 115
xi
5 Reusable libraries 116
5.1 Class libraries 117
Creating a class library 118 ✦ Using the command-line
tools 121
✦ Creating the Photograph class 122
Defining class properties 125
5.2 The object class 128
Comparing object and Object 128 ✦ Overriding object
methods 128
5.3 Interfaces 131
Interfaces and collections 132 ✦ Appreciating collection
classes 133
5.4 Generics 138
Generic classes 138 ✦ Appreciating generic collections 140
Disposing of resources 144

5.5 Recap 146
6 Files and common dialog boxes 148
6.1 Standard menus 149
Changing the menu bar 149 ✦ Managing an album 152
6.2 Common file dialog boxes 159
Creating a new album 159 ✦ Opening an album 161
Saving an album 163
✦ Printing and exiting 166
6.3 Streams and writers 167
Stream classes 167 ✦ Writing an album to disk 169
Reading an album from disk 173
6.4 Album management 174
Adding and removing images 174 ✦ Navigating an album 176
Displaying album status 178
6.5 Recap 178
7 Dialog boxes 180
7.1 Message boxes 181
Creating an OK message box 183 ✦ Creating a YesNo message
box 184
✦ Creating a YesNoCancel message box 185
7.2 The Form.Close method 188
Comparing Close and Dispose 188
Intercepting the Form.Close method 190
xii
7.3 Forms and panels 192
The Form class 193 ✦ Creating a dialog box 195
7.4 Modeless dialog boxes 196
Creating a modeless dialog box 197 ✦ Adding panels and labels to
a form 199
✦ Updating the PixelDialog controls 203

Displaying a modeless dialog box 206
✦ Updating the PixelDialog
form 208
✦ Tracking mouse movement 209
7.5 Recap 211
8 Text boxes 212
8.1 Form inheritance 213
Creating a base form 214 ✦ Creating a derived form 217
8.2 Standard text boxes 219
Adding text boxes 220 ✦ Adding a multiline text box 225
Hooking up a dialog box 229
8.3 Masked text boxes 231
Handling key presses 231 ✦ Masking text 233
8.4 Recap 239
9 Buttons 240
9.1 Push buttons 241
The Button class 241 ✦ Expanding the PhotoAlbum class 243
Storing album data 245
9.2 Radio buttons 246
The RadioButton class 247 ✦ Creating an album dialog
box 248
9.3 Check box buttons 250
The CheckBox class 250 ✦ Using check box buttons 251
Completing the AlbumEditDialog form 253
✦ Hooking up a
dialog box (again) 255
9.4 Tooltips and error providers 256
The ToolTip class 256 ✦ Displaying tooltips 258
Building extender providers 261
✦ The ErrorProvider class 263

9.5 Recap 266
10 Handling user input and encryption 268
10.1 Keyboard events 269
The three events 269 ✦ Handling the KeyPress event 269
Handling the KeyDown and KeyUp events 271
Preprocessing command keys 272
xiii
10.2 Mouse events 274
The MouseEventArgs class 274 ✦ Implementing
FlybyTextProvider using mouse events 277
✦ Using the
FlybyTextProvider class 280
10.3 Encryption 282
The Cryptography namespace 282 ✦ Encrypting data 284
Writing encrypted data 286
✦ Reading encrypted data 287
Storing encrypted albums 288
10.4 Link labels 291
The LinkLabel class 292 ✦ Saving encrypted albums 293
Opening encrypted albums 294
10.5 Recap 297
11 List boxes 299
11.1 List controls 300
The ListControl classes 300 ✦ Creating a new solution 302
Refactoring application code 303
11.2 Simple list boxes 308
The ListBox class 310 ✦ Displaying a data source 311
Selecting list items 315
11.3 Multiselection list boxes 317
Enabling multiple selection 318 ✦ Reordering list items 321

Removing list items 324
11.4 Recap 325
12 Combo boxes 327
12.1 Standard combo boxes 328
The ComboBox class 328 ✦ Creating a combo box 330
Selecting combo box items 332
✦ Modifying the data
source 333
12.2 Editable combo boxes 335
Creating a combo box (again) 336 ✦ Updating a combo box
dynamically 339
12.3 Automatic completion 341
Understanding automatic completion 341
Using auto-completion in a combo box 344
12.4 Item formatting 345
The formatting interfaces 345 ✦ Implementing an IFormattable
interface 346
✦ Using formatting in list controls 350
Implementing custom formatters 352
12.5 Recap 355
xiv
13 Tab controls and pages 356
13.1 Tab control fundamentals 357
The TabControl class 357 ✦ Creating tab controls 358
13.2 Tab page fundamentals 362
The TabPage class 362 ✦ Creating tab pages 363
Enclosing existing controls in a tab page 366
13.3 Owner-drawn tabs 369
The DrawItem event 370 ✦ Drawing page tabs 371
Using a custom tab control 375

13.4 Owner-drawn list boxes 376
Custom list items 377 ✦ Assigning item size 378 ✦ Drawing
list items 380
13.5 Recap 381
14 Dates, calendars, and progress bars 383
14.1 Date and time display 384
The DateTimePicker class 384 ✦ Creating a DateTimePicker
control 387
14.2 Date and time formats 389
Formatting date and time values 390 ✦ Customizing a
DateTimePicker control 393
14.3 Calendars 394
The MonthCalendar class 395 ✦ The UserControl class 396
Creating a calendar control 397
✦ Initializing a calendar 399
Handling mouse clicks in a calendar control 401
14.4 Progress bars 405
Creating an images user control 405 ✦ The ProgressBar
class 408
✦ Performing a background task 410
14.5 Recap 413
15 Bells and whistles 415
15.1 Images and cursors 416
Bitmaps 416 ✦ Icons 420 ✦ Cursors 425
15.2 Embedded resources and sounds 426
Embedding a resource 427 ✦ Using the project resource file 428
Playing a sound 431
15.3 Track bars 433
The TrackBar class 434 ✦ Using track bars 435
xv

15.4 Timers 439
The Timer class 439 ✦ Using timers 439
15.5 Recap 442
16 Tool strips 443
16.1 Tool strip fundamentals 444
The ToolStrip classes 445 ✦ Creating a tool strip 447
16.2 Tool strip item fundamentals 448
The ToolStripItem classes 448 ✦ Adding standard tool strip
items 449
✦ Item alignment, overflow, and other features 452
16.3 Image lists 453
The ImageList class 454 ✦ Creating an image list 454
Adding custom tool strip buttons 457
16.4 Tool strip containers 458
The ToolStripContainer class 458 ✦ Embedding a tool strip in a
container 460
16.5 Specialized button items 463
Toggle buttons 463 ✦ Drop-down buttons 467 ✦ Split
buttons 469
16.6 Recap 473
Part 3 Advanced Windows Forms 475
17 Custom controls 477
17.1 Extending existing controls 478
Designing a scrollable picture box 479 ✦ Creating a scrollable
picture box 481
✦ Implementing a scrollable picture box 483
17.2 Control-based classes 485
Creating a Control-based class 485 ✦ Common features of
custom controls 489
17.3 The ScrollablePictureBox class 491

Painting the control 491 ✦ Resizing the control 493
Handling property changes 495
17.4 User controls 497
17.5 Custom controls in Visual Studio 497
Customizing class behavior 498 ✦ Customizing class member
behavior 500
✦ Customizing design time behavior 503
17.6 Recap 506
xvi
18 Explorer interfaces and tree views 507
18.1 Interface styles 508
Single document interfaces 508 ✦ Multiple document
interfaces 509
✦ Explorer interfaces 510
18.2 Explorer interfaces in .NET 511
The SplitContainer class 511 ✦ The TreeView class 514
Creating an explorer interface 516
18.3 Tree nodes 518
The TreeNode class 518 ✦ Creating tree nodes 519
18.4 Custom tree views 523
Creating a custom tree view 524 ✦ Creating custom tree
nodes 525
✦ Using interfaces with custom nodes 526
Expanding and collapsing tree nodes 531
✦ Selecting and editing
tree nodes 533
✦ Integrating a custom tree view control 537
18.5 Recap 540
19 List views 541
19.1 List view fundamentals 542

The ListView class 542 ✦ Creating a list view 545
Populating a list view 548
19.2 List view columns 551
Defining column headers 551 ✦ Populating list view
columns 554
✦ Sorting list view columns 557
19.3 List view features 562
Selecting items 563 ✦ Editing item labels 566
Activating items 569
19.4 Virtual Items 571
19.5 Recap 574
20 Multiple document interfaces 575
20.1 MDI forms 576
Creating an MDI container 577 ✦ Creating an MDI child 578
Updating the entry point 579
20.2 Merged menus 581
Assigning merge actions 583 ✦ Assigning merge indexes 584
Opening and closing child forms 587
20.3 MDI children 589
Merging tool strips 590 ✦ Displaying pixel data 594
Opening an album twice 599
✦ Updating the title bar 600
xvii
20.4 MDI child window management 602
Arranging MDI children 603 ✦ Displaying an MDI child
list menu 605
20.5 Recap 607
21 Data binding 608
21.1 Data grid views 609
The DataGridView class 612 ✦ Creating a data grid view 612

Populating a data grid view 614
21.2 Columns and rows 618
Creating columns 619 ✦ Creating combo box columns 624
Understanding bands and rows 626
21.3 Cells 630
The DataGridViewCell class 630 ✦ Using the cell class 631
Saving a modified album 634
21.4 Recap 635
22 Two-way binding and binding sources 637
22.1 Binding lists 638
The IBindingList interface 638 ✦ Creating a binding list 640
22.2 Editable objects 643
The IEditableObject interface 644 ✦ Creating an editable
object 644
22.3 Simple data binding 647
The BindingSource class 648 ✦ Altering the MyAlbumData
application 650
✦ Performing simple binding 652
Updating data bound controls 656
✦ Binding navigators 660
22.4 Recap 663
23 Odds and ends .NET 665
23.1 Printing 666
Using the print classes 667 ✦ Drawing a print page 669
23.2 Drag-and-drop 673
Initiating drag-and-drop 674 ✦ Receiving drag-and-drop 676
23.3 Web browsing 679
Creating an about box 680 ✦ The WebBrowser class 682
Browse to a web site 683
23.4 Application settings 686

Storing the Location setting 686 ✦ Defining a custom
setting 690
xviii
23.5 Deployment 691
Creating a setup project 692 ✦ Publishing a ClickOnce
application 696
23.6 Recap 699
appendix A C# primer 701
appendix B .NET namespaces 735
appendix C Visual index 741
appendix D For more information 758
bibliography 760
index 763
xix
preface
In my younger days at school and later working with various startup companies, I
thought Unix ruled the world and never expected to find myself working with “the
dark side” of the computer industry: that is, Microsoft Corporation. So I find it
amusing that here I am publishing not a first but a second book in support of
Microsoft technologies. I guess you go where the road leads, and my paths have car-
ried me fully into the depths of Windows-based development. Fortunately, I am
happy with my conversion, which I suppose is the way of the dark side.
As to this publishing idea, it is a very curious thing. The excitement of writing
wears off after a while, and you realize that you not only want to write a book, you
want to write a good book. This changes your approach and mentality, in that you put
in the extra effort and time to make it “good.” Then one day you have another reve-
lation: you not only want to write a good book, you want to write a book people actu-
ally like and are willing to purchase.
Such was my journey for both the first and the second editions of this book. The
first edition was reasonably well received, and a second edition for .

NET 2.0 seemed
apparent. Unfortunately, those clever folks at Microsoft added and changed so much
of the Windows Forms namespace that I found myself rewriting pretty much the
entire book.
While you might think the journey involved for a second edition is easier than the
first, don’t kid yourself. It is true that I knew how to approach the text and the basic
format is the same, but as a “seasoned author” I wanted to create a better design for
both the book and the sample application built throughout. The chapters are more
concise and I attempted to apply my experience with .
NET enterprise application
development at Unisys Corporation to generate a better program design. I added more
diversions from the main MyPhotos application to cover additional material and to
present code samples for alternate or interesting topics.
Another curious fact was that while writing the first edition of this book I was a
consultant, and it was fairly easy to take weeks off here and there to devote to writing.
As a full-time program manager these days, finding such time for the second edition
was not easy. My family and friends were equally supportive for both editions, for
which I am very thankful.
xx PREFACE
In the end, I find myself quite happy with this second edition of the book. Some
key concepts and classes, such as encryption, custom controls, and progress bars,
found their way into the text. I like the chapter layout for the second edition, from
18 chapters in the first edition to 23 chapters in this book. I am also much happier
with the index, which I’m sure you’ll find easier to use than in the first edition.
Another big change between the first and second editions of this book is the title.
This edition has been renamed Windows Forms in Action to differentiate it from other
books and to work with Manning’s new “in Action” titling theme. The Action-Result
table format used throughout this book lends itself to our new name. New title, new
cover, new chapters, and we appear to have a book.
Enjoy.

xxi
preface to the first edition
In early 2001 I began using Microsoft’s .NET Framework for a project I was working
on with a small startup company. Unfortunately, the winds changed and I found
myself with more free time than I would normally hope for. So when Manning Pub-
lications asked me if I would contribute to a book on programming with the .
NET
Framework, I welcomed the idea.
As events unfolded, I found myself with some fairly strong opinions about how
such a book should be organized, and offered up a proposal to write a solo book on
programming Windows Forms applications. I have always enjoyed the book Program-
ming Windows 95 with
MFC by Jeff Prosise, so a book about developing Windows-
based applications with the .
NET Framework seemed like an obvious subject.
The core idea behind my proposal was to build a single application over the course
of the book. The application would evolve to introduce each topic, so that by the end
of the manuscript readers would have a robust application they had built from scratch.
Manning Publications seemed to like the idea as well, and thus I suddenly found
myself writing this book.
In approaching the task, I set out to achieve two objectives. The first was to provide
ample coverage of most of the classes in the namespace. I have been frustrated by many
books that do not provide robust examples for a topic. So I try to provide detailed
examples that demonstrate how Windows Forms classes can be used and manipulated
in real applications.
A second objective was to present advanced user interface topics such as tree views
and drag and drop. While the book spends a good deal of time on fundamental classes,
such as menus and buttons, more than a cursory glance is given to some of the more
complex controls available for Windows-based programming.
The result of my proposal, these objectives, and a number of late nights is the book

you see before you. I take a tutorial approach to application development by creating
a common application throughout the book, and provide summaries of relevant
classes and other topics that might be of further interest. Hopefully, this approach pro-
vides enough detail to demonstrate how Windows-based applications are put together
with the .
NET Framework, and yet offers additional information that should prove
helpful as you develop and expand your own .
NET projects.
xxii PREFACE TO THE FIRST EDITION
While the book is not specifically about C# and Visual Studio, the text does
attempt to introduce and explain the syntax and usage of C# as well as the features and
functionality of Visual Studio. These topics are presented “along-the-way” by intro-
ducing relevant concepts and features as they are used in the examples. An overview
of C# is also provided in appendix A at the back of the book.
xxiii
acknowledgments
It never ceases to amaze me how the tangled threads of our lives come together to
produce a tangible result, in this case the book you are reading. While the front of
this book bears my name, a number of people knowingly or unknowingly contrib-
uted to its conception and development. I would especially like to acknowledge Man-
ning typesetter Sydney Brown, whose care and insight contributed greatly to the
visual quality of the first edition. Sydney is no longer with us, but she is missed, and
her echoes in this and other Manning books remain.
Thanks go to my family: to my wife Bridgett for her patience and love; to Katie
and Sydney for the smiles and laughter they bring to my world; to Bianca, who really
wishes she was the only animal in the house; and to Laura, who has become my faithful
companion, stretching out in my office on a regular basis (much to Bianca’s dismay).
I am also grateful for my parents, David and Janet, and teachers and others who
have supported me throughout my life. Special recognition goes to Steve Cox and
David Cobb, who first interested me in computer programming so long ago.

Thanks also to my many friends who provided support and encouragement in ways
that only friends can do, most notably Jean Siegel, Tommy McCracken, Tony Mason,
and Reggie Blue.
Many reviewers from all corners of the globe dedicated their time and energy to
reading early versions of various chapters, and for them I am especially grateful. This
book would not be the same without their assistance and efforts. This is especially true
of Dave Corun for his exhaustive technical review of the entire text during final pro-
duction. Also many thanks to Erick Ellis and other members of the Microsoft Win-
dows Forms team, both for the early looks at the .
NET 2.0 Framework and for the
many constructive comments offered on the text. Other reviewers that offered insight-
ful comments or thoughts on the text include Andrew Deren, Berndt Hamboeck, Jack
Herrington, Shane Jervis, Joe Litton, Robert Marshall, Robert McGovern, Mark
Monster, Alan Newson, Vipul Patel, Heath Stewart, Gary Udstrand, and Andrew
Varner.
I would also like to recognize the reviewers of my original first edition outline way
back in 2001, namely Steve Binney, Mark Boulter, Drew Marsh, Josh Mitts, and
xxiv ACKNOWLEDGMENTS
Kunle Odutola. Their suggestions were critical to my thinking for the first edition that
resulted in the focus and layout that carries forward into this edition.
Finally, I would like to acknowledge the many people I worked with from and
through Manning Publications whom I have never met and yet who provided critical
support throughout the writing process. This especially includes Susan Capparelle for
seeing some merit in my original proposal; Marjan Bace for his ideas and guidance in
the first edition and for his thoughts and support for a second edition; Karen Tegt-
meyer for coordinating all the reviewers and their feedback; Leslie Haimes for design-
ing the very cool cover; Mary Piergies for overseeing the project and answering my
many questions; Ann Navarro, Susannah Pfalzer, and Lianna Wlasiuk for working
with me on the structural elements of the book; Liz Welch for her very thorough copy
edit of my final documents; Barbara Mirecki and especially Katie Tennant for their

detailed wordsmithing of the final manuscript; Dottie Marsico for creating appendix
C with page numbers and for the final typesetting of the book itself; Helen Trimes
for coordinating the sales and marketing aspects; and finally Lee Fitzpatrick for con-
tinuing to sign my royalty checks.

×