1. Trang chủ
  2. » Khoa Học Tự Nhiên

Apress net user interfaces with c sharp

925 142 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 925
Dung lượng 6,96 MB

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

Nội dung

Chapter 6 -Modern Controls byMatthew MacDonald Apress 2002 Companion Web Site... User Interfaces in C#: Windows Forms and Custom ControlsbyMatthew MacDonald ISBN:1590590457 Apress 2002 5

Trang 1

Chapter 6 -Modern Controls

byMatthew MacDonald Apress 2002

Companion Web Site

Trang 2

Chapter 6: Modern Controls

Many of the controls you've looked at so far (like buttons, menus, andtext boxes) have been around since the early days of Windows 3.1without much more than the occasional facelift As development

entered the 32-bit world, more sophisticated controls began to appearand gain popularity Controls like the TabControl, ListView, and

TreeView began to do wonders organizing complex information At thesame time, the ToolBar and StatusBar revamped the look of the

standard Windows application with a more modern feel

In this chapter, you learn about all these controls More important, youlearn the tricks and techniques you need to master them Customcontrol classes, one of my favorite themes, returns in this chapter with

a few remarkable examples You see how to create subclassed

controls that are fine-tuned for specific data, or can automatically

communicate and synchronize themselves with other controls

Trang 3

The ImageList is a special type of collection that holds images of apreset size and color depth Other controls access pictures in theImageList using the appropriate index numbers In this way, an

ImageList acts as a resource for other controls, providing icons forcontrols like the ToolBar and TreeView

Note In some respects, the ImageList isn't really a control It

doesn't have a graphical representation, and the end usernever interacts with it directly On the other hand, ImageListobjects are usually created and configured at design timewhen you are building the user interface They are alsoclosely linked to other modern controls like ListView,

TreeView, and ToolBar controls

To create an ImageList at design time, drag it onto your form (it willappear in the component tray) The basic properties for the ImageListare described in Table 6-1

Table 6-1: ImageList Members

ColorDepth

A value from the ColorDepth enumeration thatidentifies the color resolution of the images in thecontrol Some common choices are 8-bit (256color mode), 16-bit (high color), and 24-bit (truecolor)

Images The collection of Image objects that are provided

to other controls

A Size structure that defines the size of the

Trang 4

ImageSize contained images ImageList controls can onlycontain images that share the same size and

color-depth Images are converted to thespecified format when they are added

TransparentColor

Some image types, like icons and GIFs, define atransparent color that allows the background toshow through By setting the Transparent Colorproperty, you can define a new transparent colorthat will be used when this image is displayed

This is useful for graphic formats that don'tdirectly support transparency, like bitmaps

Draw()

This method provides a quick and easy way totake an image and output it to a GDI+ drawingsurface

Tip Transparent regions are a must when mixing custom imagesand standard controls If you simply use an icon with a greybackground, your interface becomes garish and ugly on acomputer where the default color scheme is not used, as agrey box appears around the image.You also run into

problems if the icon can be selected, at which point it is

highlighted with a blue background

You can add, remove, and rearrange images using the ListView

designer Just click the ellipsis (…) next to the Images property in theProperties window Images can be drawn from almost any commonbitmap file, including bitmaps, GIFs, JPEGs, and icons When you add

a picture, some related read-only properties about its size and formatappear in the window (see Figure 6-1)

Trang 8

User Interfaces in C#: Windows Forms and Custom Controls

byMatthew MacDonald

ISBN:1590590457

Apress 2002 (586 pages)

Including a comprehensive examination of the user interface controls and classes in NET, this resource provides an overview of how to design elegant user interfaces the average user can understand.

Trang 10

Chapter 5 -Forms

byMatthew MacDonald Apress 2002

Companion Web Site

Trang 11

creating them, displaying them, and handling their interactions, toadvanced techniques using shaped forms and visual inheritance Inmany respects, these new developments hint at two of the themes Itake up in the rest of the book Shaped forms give just a taste of whatyou encounter in 13, which dive headfirst into GDI+ Visual inheritanceprovides a preview into some of the custom control designs you

In this chapter you've traveled from the basics of Windows forms-explore with control inheritance throughout this book Both techniquesrepresent the step from ordinary user interface programming to themore advanced techniques of a UI guru

Trang 12

Chapter 6 -Modern Controls

byMatthew MacDonald Apress 2002

Companion Web Site

Trang 13

The ListView and TreeView are probably the most widespread anddistinctive controls in modern application design As far as controls

go, they have it all: an attractive appearance, a flexible set of features,and an elegant ability to combine different types of functionality andinformation Thanks to Windows Explorer, they are also widely

recognized and understood by intermediate users

These days, it's hard to find programs that don't use TreeView and

ListView The Windows operating system makes heavy use of them inconfiguration and administration windows Other Microsoft softwarethat uses the MMC snap-in model follows suit, like SQL Server andeven configuration utilities for the NET platform (see Figure 6-3)

Figure 6-3: Configuring

assembly settings in NET

Trang 14

Windows Forms and Custom Controls

byMatthew MacDonald

ISBN:1590590457

Apress 2002 (586 pages)

Including a comprehensive examination of the user interface controls and classes in NET, this resource provides an overview of how to design elegant user interfaces the average user can understand.

Companion Web Site

Table of Contents Back Cover

Back Cover

Describes the architecture of a well-planned user interface—everything from data binding strategies

to multiple document view architecture using MDI

Trang 15

irregularly shaped forms, owner-drawn menus, and animated controls

Shows how to integrate “intelligence” into your user interfaces with embedded help and user

applications using the NET Framework After reading

User Interfaces in C#: Windows Forms and Custom

Controls, you’ll know how to design state-of-the-art

application interfaces, as well as how to extend NET controls, create data-binding strategies, program

Trang 16

you’ll use on a regular basis But you won’t just learn how to use NET controls—you’ll learn how and why to extend them, with owner-drawn menus, irregularly shaped forms, and custom controls tailored for specific types of data As a developer, you need to know more than how to add a control to a window You also need

to know how to create an entire user interface

framework that’s scalable, flexible, and reusable.

About the Author

Matthew MacDonald is an author, education and MCSD developer He’s also a regular contributor to

Trang 17

User Interfaces in C#—Windows Forms and Custom Controls

(pbk):

1-59059-045-7

Trang 18

trademark symbol with every occurrence of a trademarked name, weuse the names only in an editorial fashion and to the benefit of thetrademark owner, with no intention of infringement of the trademark

Phone 510-549-5930, fax: 510-549-5939, email info@apress.com, orvisit http://www.apress.com

The information in this book is distributed on an "as is" basis, withoutwarranty Although every precaution has been taken in the

preparation of this work, neither the author nor Apress shall have any

Trang 19

(MCDBA), Microsoft Certified Trainer (MCT) and Certified TechnicalTrainer (CTT), Gordon has specialized in Microsoft technologies andsoftware, including Microsoft's established technologies and also thenew technologies such as NET Framework (CLR), VB NET, C#,

ASP.NET, ADO.NET, SOAP, Web Services, and XML

Trang 20

byMatthew MacDonald Apress 2002

Companion Web Site

Trang 21

In the past few months, a deluge of NET books has hit store shelves,each one eager to explain the new programming philosophy of the.NET world In the excitement, many of these books have left out thetricks and insights you need to really master NET programming Part

of the problem is that no single work can cover the entire NET

platform-a sprawling, ambitious framework that revolutionizes

everything from Internet applications to data access technology Many.NET books provide a good overview of essential concepts, but theycan't deal with the subtleties needed for all types of development.This book represents the start of the second wave of NET books:closely focused works that give you the insight of experienced

architecture, custom control layout engines, dockable windows, andhit testing with owner-drawn controls You also learn how to designirregularly shaped forms, unshackle data binding, and build an

integrated help system

In short, this is the sort of NET book that I would want to read as aprofessional developer It's a book that goes beyond the basics, andcombines user interface design principles with practical guidelines forcreating the next generation of software applications And seeing as

you are reading this introduction, you've probably already realized that

this next generation will be built using the NET Framework

Trang 22

This book has been, comparatively speaking, a lot of fun to write As aresult, I have a long list of people to thank

Gary Cornell never ceases to amaze me with his ability to respond toemails mere seconds after they've departed from my outbox I'm

indebted to him for quickly and painlessly signing me on for this

project I also owe a sincere thanks to a number of other individuals atApress who helped everything move swiftly and smoothly They

include Sofia Marchant, Kari Brooks, Grace Wong, Stephanie

Rodriguez, and doubtless many others I never interacted with directly.Gordon Henshaw performed the technical review for the C# edition ofthis book, and Gordon Wilmot performed the technical review for the

Trang 23

byMatthew MacDonald Apress 2002

Companion Web Site

Trang 24

This book explains how to program user interfaces applying the toolsand techniques of the NET world You may already be familiar withsome of the concepts that carry over from traditional development(like multiple-document interfaces, and the standard Windows controlsand conventions) Other features are entirely new and will be unlikeanything you have ever worked with before But no matter what

aspect of user interface design you're exploring, it all works throughthe NET class library, which provides a new set of capabilities,

subtleties, and quirks that every NET programmer needs to master

Trang 25

User interface design deals with several aspects of programming Thetendency in a book about a topic like this is to pursue one of thesethemes exclusively With NET, however, the programming framework

is entirely new A reference that only explains controls and commands

is dangerous, and without a proper discussion of best practices anddesign tips, programmers are likely to wind up in a great deal of

trouble-with applications that are difficult to enhance, debug, or scale

up For that reason, I've made the decision in this book to focus onthree distinct themes

What This Book Teaches You

This book fills three roles It provides the following:

An overview of how to design elegant user interfaces the average user can understand This is addressed directly in

the first chapter, and indirectly in Tips and Notes throughoutthe book

A comprehensive examination of the user interface

controls and classes in NET Although this book is not a

reference, it contains an exhaustive tour of almost every userinterface element you'll want to use, including providers,

components, and custom controls

A tutorial with best practices and design tips for coding user interfaces and integrating help As a developer, you

need to know more than how to add a control to a window.You also need to know how to create an entire user interfaceframework that's scalable, flexible, and reusable

What This Book Doesn't Teach You

Of course, it's just as important to point out what this book doesn't

Trang 26

A description of core NET concepts like namespaces,

assemblies, exception handling and types These

fundamentals are an important basis for NET design, andthey are already explained well in several works, including anumber of excellent C# and VB NET books from Apress

A primer on object-oriented design No NET programmer canprogress very far without a solid understanding of classes,interfaces, and other NET types In this book, many examplesrely on these basics, using objects to encapsulate, organize,and transfer information

A reference for Visual Studio NET The new integrated designenvironment provides powerful customization, automation,and productivity features that deserve a book of their own.Though this book describes a few control designers, for themost part it assumes that you already know how to use IDE tocreate controls and set properties

A comparison between NET and its predecessors (includingVisual Basic, C++, and even Java) Examining the evolution ofthe NET language is largely a historical interest and whilefascinating, it won't help you master modern NET

development any faster The best approach is to leave yourpast language allegiances behind

If you haven't learned the NET fundamentals, you will probably still beable to work through this book You will probably need to do so at aslower pace, and you may also need to refer to the MSDN help files toclear up a few issues along the way On the other hand, if you havealready read another, more general NET book, you will benefit themost

Note This book is targeted at experienced developers If you

have never programmed with a language like Visual Basic,C++/C#, or Java before, this isn't the place to start Instead,start with an introductory book on object-oriented design or

Trang 27

Code Samples

It's a good idea to check the online site to download the most recent,up-to-date code samples You'll need to do this to test most of themore sophisticated code examples described in this book, becausethe full code listing is often left out Instead, I focus on the most

important conceptual sections so that you don't need to wade throughneedless extra pages to understand an important concept

To download the source code, surf to http://www.prosetech.com orhttp://www.apress.com

Variable Naming

It seems that variable naming is about to become another religiousissue where there is no clear standard, but developers take heated,uncompromising attitudes Hungarian notation, which was the

preferred standard for C++ and Visual Basic (in a slightly modifiedform), is showing its age In the world of NET, where memory

management is handled automatically, it seems a little backward torefer to a variable by its data type, especially when the data type maychange without any serious consequences, and the majority of

variables are storing references to full-fledged objects

To complicate matters, Microsoft recommends that objects use simplenames for properties and methods, like COM components and

controls This system makes a good deal of sense, as data type

considerations are becoming more and more transparent Visual

Studio NET now takes care of some of the work of spotting the invaliduse of data types, and its built-in IntelliSense automatically displaysinformation about the data types used by a method

In this book, data type prefixes are not used for variables The onlysignificant exception is with control variables, where it is still a usefultrick to distinguish between types of controls (like txtUserName andlstUserCountry), and with some data objects Of course, when you

Trang 28

create your programs you are free to follow whatever variable namingconvention you prefer, provided you make the effort to adopt completeconsistency across all your projects (and ideally across all the projects

Trang 29

Chapter 1 -Creating Usable Interfaces

byMatthew MacDonald Apress 2002

Companion Web Site

Trang 30

Chapter 1: Creating Usable Interfaces

Trang 31

Sometimes it seems that no one can agree what user interface designreally is Is it the painstaking process an artist goes through to createshaded icons that light up when the mouse approaches? Is it the

hours spent in a usability lab subjecting users to a complicated newapplication? Is it the series of decisions that determine how to modelinformation using common controls and metaphors?

In fact, user interface design is really a collection of several differenttasks:

User interface modeling This is the process where you look

at the tasks a program needs to accomplish, and decide how

to break these tasks into windows and controls To emergewith an elegant design, you need to combine instinct,

convention, a dash of psychology, and painstaking usabilitytesting

User interface architecture This is the logical design you

use to divide the functionality in your application into separateobjects Creating a consistent, well-planned design makes iteasy to extend, alter, and reuse portions of the user interfaceframework

User interface coding This is the process where you write

the code for managing the user interface with the appropriateclasses and objects Ideally, you follow the first two steps tolay out a specific user interface model and architecture beforeyou begin this stage

This book concentrates on the third, and most time-consuming step,where user interfaces designs are translated into code using the toolsand techniques of NET However, it's impossible to separate goodcoding from good code design, and discussion about user interfacearchitecture, the second item on the list, recurs throughout this book(and is the focus of the next chapter)

Trang 32

handling complexity, and entering into the mind of that often-fearedfinal judge: the end user

You could skip ahead at this point and dive right into NET code

However, the greatest programming framework in the world won'tsolve some common, critical user interface mistakes Learning how todesign an interface is no less important than learning how to work with

it in code

Trang 33

Chapter 2 -Designing with Classes and Tiers

byMatthew MacDonald Apress 2002

Companion Web Site

Trang 34

Chapter 2: Designing with Classes and Tiers

Trang 35

Some developers resent user interface programming because theybelieve it's all about painting icons, rewording text, and endlessly

tweaking dialog boxes until an entire company agrees that an

application looks attractive Certainly, making a program usable,

elegant, and even impressive (or cool) is no trivial task It can evenmake the difference between indifferent customers and an

enthusiastic audience that's willing to promote your product tirelessly.This kind of excitement about a program's look and feel has drivenobscure products like Kai's Power Tools and even Microsoft Windows

to great success, and it can't be overlooked However, developerswho are involved in creating and maintaining sophisticated enterprise-level applications realize that there is another set of design

considerations for user interface programming These are

considerations about application architecture

Application architecture determines how a user interface "plugs in" tothe rest of an application Today's development software (like MFC,Visual Basic, and NET) makes this interaction relatively

straightforward and, as a result, developers usually spend little or notime thinking about it User interface code is usually inserted wherever

is most immediately convenient at the time the program is written.This almost always leads to interface code that's tightly bound to aparticular problem, scenario, or data source, and heavily interwovenwith the rest of the application logic The interface code might lookgood on the outside, but it's almost impossible to enhance, reuse, oralter with anything more than trivial changes To make the jump fromthis type of scattered user interface coding to a more modern styleyou have to stop thinking in terms of windows and controls, and startlooking at user interface as an entire interrelated framework

This chapter explains how the principles of object-oriented

programming and three-tier architecture apply to user interface

design It identifies the overall concepts that you'll return to again andagain throughout the book, including:

Trang 36

Why inheritance is more important for user interface designthan for business logic

How the NET framework approaches user interface design,and how it affects your coding practices

What makes an interface data-driven and well encapsulated.What the dream of three-tier design promises, why it's so hard

to achieve, and whether other solutions are possible

The emphasis in this chapter is on general concepts You'll see somecode, but you won't learn about the intricate details like the propertiesand methods that controls provide All these details are explored as

we delve deeper into controls and user interface coding in the

chapters that follow

Trang 37

Chapter 3 -Control Class

Basics

byMatthew MacDonald Apress 2002

Companion Web Site

Trang 38

Chapter 3: Control Class Basics

This chapter explores the Control class, which provides basic

functionality for the family of Windows controls You will learn aboutfundamental topics like mouse and keyboard handling, focus, andcontrol relations Along the way, I'll also introduce some importantpieces of the System.Drawing namespace that allow you to createstructures that represent colors, fonts, rectangles, and points

Trang 39

.NET provides two toolkits for user interface design: one for web

applications, and one for Windows development This chapter

introduces the Windows Forms package, which allows you to createthe traditional rich graphical interfaces found in everything from officeproductivity software to arcade games The one detail that all theseapplications have in common is the fact that they are built out of

windows-tiny pieces of screen real estate that can present informationand receive user input

It's easy to imagine that "Windows Forms" refers to a special part ofthe NET class library, where fundamental classes like Form and

Control are stored This is true, but it isn't the whole story More

accurately, Windows Forms is the technology that allows the CommonLanguage Runtime to interact with control objects and translate theminto the low-level reality of the Windows operating system In otherwords, you create objects that represent controls and windows, andthe Common Language Runtime handles the details like routing

messages, keeping track of window handles, and calling functionsfrom the Windows API

This idea isn't new In the past, developers have used the MFC

framework in C++, WFC in J++, and Visual Basic's own "Ruby" formsengine to insulate themselves from some of the low-level details ofWindows programming These frameworks all provide an object-

oriented wrapper around the Windows API (which, on its own, is adisorganized collection holding hundreds of miscellaneous C

routines) These frameworks were well intentioned, but they have allsuffered from a few problems

Lack of consistency If you learn how to use MFC, you still

won't know anything about creating Visual Basic user

interfaces Even though every framework ultimately interactswith the Windows API, they have dramatically different objectmodels and philosophies

Trang 40

either easy to use, or powerful, but not both MFC is reallyonly a couple of steps away from Windows messages andlow-level grunt work On the other hand, Visual Basic

developers have the benefit of a simple framework, but facethe lingering dread that they will need to delve into the rawWindows API for complex or unusual tasks that are beyondVisual Basic's bounds

Subjugation to Windows API rules The Windows API

dictates certain harsh realities For example, once you create

a fixed-border window, you can't make its border resizable.These limitations make sense based on how the Windows API

is organized, but they often lead to confusing inconsistencies

in a framework's object model

The result of these limitations is that there are essentially two types offrameworks: those that are complicated to use for simple tasks (likeMFC), and those that are easy to use for simple tasks, but difficult orimpossible to use for complex tasks (like VB) These object modelsprovide a modern way to code user interfaces, but many

programmers wonder why they should abstract the Windows API

when its restrictions remain

The NET Solution

.NET addresses these problems by becoming more ambitious Theresult is a user interface framework that uses some innovative sleight-of-hand to perform tasks that are difficult or impossible with the

Windows API Here are some examples- tasks that NET can performbut the Windows API cannot:

Change fixed style properties like the selection type of a listbox or the border type of a window

Change a form's owner

Move an MDI child window from one MDI parent window to

Ngày đăng: 25/03/2019, 16:42

TỪ KHÓA LIÊN QUAN