Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# and the NET Platform, Second Edition - Andrew Troelsen.pdf
Скачиваний:
67
Добавлен:
24.05.2014
Размер:
22.43 Mб
Скачать
Part Two - The C# Programming Language
Chapter 1 - The Philosophy of .NET
Part One - Introducing C# and the .NET Platform

Summary C# and the .NET Platform, Second Edition

by Andrew Troelsen ISBN:1590590554

GDI+ is the name given to a number of related .NET namespaces, each of which is used to render graphic

Apress © 2003 (1200 pages)

images to a Control-derived type. The chapter began by examining the core types defined within the

This comprehensive text starts with a brief overview of the

System.Drawing C#namespacelanguage (includinga d then quicklya numbermovesof usefulto key utilitytechnicaltypes),and and examined various manners to intercept paint eventsarchitectural. issues for .NET developers.

The bulk of this chapter was spent examining how to work with core GDI+ object types such as colors,

Tablefonts,ofgraphicsContentsimages, pens, and brushes in conjunction with the almighty Graphics type. Along the way, C#youandexaminedthe .NETsomePlatform,GDI+Se-centricond Editiondetails such as hit-testing, and how to drag and drop images.

Introduction

This chapter wrapped up by examining the new .NET resource format. As you have seen, an application does not need to bundle its external resources into the containing assembly, however, if your application

does so, your binary image is far more portable. The *.resx file is used to describe a set of name/value

Chapter 2 - Building C# Applications

pairs (a la XML). This file is fed into the resgen.exe utility, resulting in a binary format (*.resources) that can

then be embedded into the owning assembly. The System.Resouces.ResourceManager type is your key

Chapter 3 - C# Language Fundamentals

to programmatically obtaining this information at runtime.

Chapter 4 - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Part Two - The C# Programming Language
Chapter 2 - Building C# Applications

Chapter C#15:andProgrammingthe .NET Platfor , SecondwithEd ion Windows Forms

by Andrew Troelsen

ISBN:1590590554

ControlsApress © 2003 (1200 pages)

 

This comprehensive text starts with a brief overview of the

C# language and then quickly moves to key technical and

Overview architectural issues for .NET developers.

This chapter is concerned with providing a roadmap of the suite of GUI widgets defined in the

TableSystemof Contents.Windows.Forms namespace. You have already had a chance to work with some Form-level C#controland thetypes.NETsuchPlatform,as MainMenu,Second EditionMenuItem, StatusBar, and ToolBar (see Chapter 13); however, in this

chapter, you will be examining various types that tend to exist within the boundaries of a Form's client area

Introduction

(e.g., Buttons, TextBoxes, Panels, and the like).

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

In addition to giving you a formal grounding in the Windows Forms Control set, this chapter also details a number of related topics, such as establishing the tab order for your widgets, as well as configuring the

docking and anchoring behaviors for your family of GUI types. The chapter then investigates the process

Chapter 3 - C# Language Fundamentals

of building custom dialog boxes, including techniques for responding to (and validating) user input.

Chapter 4 - Object-Oriented Programming with C#

ChapterNext, you'll5 - examineE ceptionsa newand ObjectfacilityLiofetimefered by the .NET Windows Forms architecture: Form inheritance. As

Chapteryou will6see,- Interfacesit is now possibleand Collectionsto establish "is-a" relationships between related Forms (which should make Chapterthe MFC7 developers- Callback Interfaces,of the worldDelegates,insanelyandhappy)Events. Finally, we wrap things up with an examination of the

process of building custom Windows Forms controls (which should make the ATL developers of the world

Chapter 8 - Advanced C# Type Construction Techniques

insanely happy).

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

UnderstandingC# andthet .WindowsNET Platform,FormsSecond EditiControln Hierarchy

by Andrew Troelsen

ISBN:1590590554

The System.Windows.Forms namespace contains a number of types that represent common GUI widgets

Apress © 2003 (1200 pages)

that allow you to respond to user input in a Windows Forms application. Because .NET is a system of

This comprehensive text starts with a brief overview of the

types built on standardC# languageOO principles,and thenthesequicklycontrolsmoves toarekeyarrangedtechnicalinanda hierarchy of related types. Figure 15-1 illustrates thearchitecturalbig pictureissues(note forthat.NETSystemdevelopers.Windows. .Forms.Control is the common base class for all Windows Forms widgets.)

Table of Contents

C# and

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part

Figure 15-1: The Windows Forms control hierarchy

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

As you learned in Chapter 13, the System.Windows.Forms.Control type is the base class that provides a PartminimalFour -andLeveragingcompletetheset.NETof behaviorsLibraries for all descending widgets. This includes the ability to process Chaptermouse12and- keyboardObject Serializaevents,ionestablishand the .theNETphysicalRemotingdimensionsLayer of the widget using various properties

Chapter(Height,13Width,- BuildingLeft,aRighBett,erLocation,Wind w (Iantroduciso on),g manipulateWindows Forms)background and foreground colors, establish

Chapterthe active14 -font,A Betterand soPaintingforth. Also,Frameworkthe Control(GDI+)base type also defines members that control a widget's Chapteranchoring15 -andProgrammingdocking behaviorswith Windows(as seenFormslaterControlsin this chapter).

Chapter 16 - The System.IO Namespace

As you read through this chapter, remember that the widgets examined in this chapter gain a good deal of

Chapter 17 - Data Access with ADO.NET

their functionality from the System.Windows.Forms.Control base class. In this chapter we'll focus (more or

Part Five - Web Applications and XML Web Services

less) on a given type's unique members.

Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Chapter 19 - ASP.NET Web Applications
Chapter 18 - ASP.NET Web Pages and Web Controls
Part Five - Web Applications and XML Web Services

Adding ControlsC# and theto.NETFormsPlatform,(IDESecond-Free)Edition

by Andrew Troelsen

ISBN:1590590554

Regardless of which type of control you choose to place on a Form, you will follow a similar set of steps.

Apress © 2003 (1200 pages)

First of all, you must define member variables that represent the GUI widgets maintained by the Form.

This comprehensive text starts with a brief overview of the

Next, inside the Form'sC# languageconstructorand then(or quicklywithin amoveshelpertomethod,key technicalcalledandby the constructor), you'll configure the look and feelarchitecturalof each controlissuesusingfor the.NETexposeddevelopersproperties,. methods, and events. Finally (and most important), once the control has been set to its initial state, it must be added into the Form's internal controls collection using the inherited Controls property. If you forget this final step, your widgets will not be

Table of Contents

visible at runtime! To illustrate this process in the raw, consider the MyForm class:

C# and the .NET Platform, Second Edition

Introduction

// Don't forget to add a reference to System.Windows.Forms.dll!

Part One - Introducing C# and the .NET Platform

using System.Windows.Forms;

Chapter 1 - The Philosophy of .NET

class MyForm : Form

Chapter 2 - Building C# Applications

{

Part Two - The C# Programming Language

// Define a widget data member.

Chapter 3 - C# Language Fundamentals

private TextBox firstNameBox = new TextBox();

Chapter 4 - Object-Oriented Programming with C# public MyForm()

Chapter {5 - Exceptions and Object Lifetime

Chapter 6 - Inthiserfaces.Textand Collecti= "Controls in the raw";

Chapter 7 - Callback// ConfigureInterfaces, Delthegates,widgetand.Events

firstNameBox.Text = "Chucky";

Chapter 8 - Advanced C# Type Construction Techniques

firstNameBox.Size = new Size(150, 50);

Part Three - Programming with .NET Assemblies

firstNameBox.Location = new Point(10, 10);

Chapter 9 - Understanding .NET Assemblies

// Add new widget to the Form's Controls collection.

Chapter 10 - Processes, AppDomains, Contexts, and Threads

this.Controls.Add(firstNameBox);

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

}

Part Four - Leveraging the .NET Libraries

...

Chapter 12 - Object Serialization and the .NET Remoting Layer

}

Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

The Control$ControlCollection Type

Chapt r 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

While the process of adding a new widget to a Form is quite simple, I'd like to discuss the Controls property in a bit more detail. This property returns a reference to a nested class named ControlCollection defined by the Control class (recall that a nested type can be denoted using the "$" token, e.g.,

Control$ControlCollection). The Control$ControlCollection type maintains an entry for each widget placed

Chapter 20 - XML Web Services

on the Form. You can obtain a reference to this collection anytime you wish to "walk the list" of child

Index widgets:

List of Figures

List of Tables

// Get access to the Control$ControlCollection type for this Form.

Control.ControlCollection coll = this.Controls;

Once you have a reference to this collection, you can call any of the members described in Table 15-1. Be aware that by default controls are placed in the ControlCollection type using an (n + 1) insertion policy.

Table 15-1: Nested ControlCollection Members

 

 

 

 

 

 

 

Control$ControlCollectionC# and the .NET Platform,

 

SecondMeaningEditinon Life

 

 

Member

by Andrew Troelsen

 

ISBN:1590590554

 

 

 

 

 

 

 

 

Add()

Apress © 2003 (1200 pages)

 

Used to insert a new Control-derived type (or array of

 

 

This comprehensive text starts

 

 

 

 

 

with a brief overview of the

 

 

AddRange() C# language and then quickly

 

types) in the collection

 

 

 

moves to key technical and

 

 

 

 

 

 

 

 

Clear()

architectural issues for .NET

 

developers.

 

 

 

 

Removes all entries in the collection

 

 

 

 

 

 

 

Count

 

 

Returns the number of items in the collection

 

Table of Contents

 

 

 

 

 

 

C#GetChildIndex()and the .NET Platform, Second Edition

 

Returns the index value for a specified item in the

 

Introduct on

 

collection

 

 

SetChildIndex()

 

 

 

 

 

 

 

 

Part One - Introducing C# and the .NET Platform

 

Returns the IEnumerator interface for this collection

 

 

GetEnumerator()

 

 

 

Chapter 1 - The Philosophy of .NET

 

 

 

 

 

 

 

 

Chapter 2 - Building C# Applications

 

Used to remove a control from the collection

 

 

Remove()

 

 

Part Two - The C# Programming Language

 

 

 

 

RemoveAt()

 

 

 

 

Chapter 3

- C# Language Fundamentals

 

 

 

Chapter 4 - Object-Oriented Programming with C#

To illustrate programmatic manipulation of this very important collection, assume you have now configured

Chapter 5

- Exceptions nd Object Lifetime

Chapterand added6 -aIntnewrfacesButtoandwidgetColl ctitonsthe Form's collection (Figure 15-2).

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter

Techniques

Part

 

Chapter

 

Chapter

and Threads

Chapter

Attribute-Based Programming

Part

 

Chapter

Remoting Layer

Chapter

Windows Forms)

Chapter

(GDI+)

Chapter

Controls

Chapter

 

Chapter

Part Five - Web Applications and XML Web Services

Figure 15-2: The Form's UI

Chapter 18 - ASP.NET Web Pages and Web Controls

ChapterAlso assume19 - ASPyou.NEThaveWebwrittenApplicationsan event handler for the Button's Click event. In the implementation of this

Chaptermethod,20you- XMLloopWeboverSeachrvicesitem in the Controls collection and print out some relevant information

Indexregarding the contained members:

List of Figures

Listclassof TablesMyForm : Form

{

private TextBox firstNameBox = new TextBox(); private Button btnShowControls = new Button(); public MyForm()

{

// Configure new TextBox.

...

// Configure and add a new Button. btnShowControls.Text = "Examine Controls collection"; btnShowControls.Size = new Size(90, 90); btnShowControls.Location = new Point(10, 70); btnShowControls.Click +=

new EventHandler(btnShowControls_Clicked); this.Controls.Add(btnShowControls);

}

protected void btnShowControls_Clicked(object sender, EventArgs e)

C# and the .NET Platform, Second Edition

{

by Andrew Troelsen ISBN:1590590554

Control.ControlCollection coll = this.Controls;

Apress © 2003 (1200 pages)

string ctrs = "";

This comprehensive text starts with a brief overview of the foreach(Control c in coll)

{

Table of Contents

C# language and then quickly moves to key technical and

architectural issues for .NET developers. if(c != null)

ctrs += string.Format("Index: {0}, Text: {1}\n", coll.GetChildIndex(c, false), c.Text);

}

C# and the .NET Platform, Second Edition

MessageBox.Show(ctrs, "Index and Text values for each control");

Introduction

}

Part One - Introducing C# and the .NET Platform

...

Chapter 1 - The Philosophy of .NET

}

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

ChapterNotice 4how- theObjectcall-Orientedto GetChildIndex()ProgrammingallowswithyouC# to obtain the numerical index of a given widget in the

Chaptercollection5 (the- Exceptisecond Booleanand ObjectparameterLifetime is used to control if an exception is raised in the case that the Chapterrequested6 -controlInterfacesis notandfound)Collections. If you run the application and click the Form's Button, you are presented

with the information shown in Figure 15-3.

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part

 

Chapter

 

Chapter

Threads

Chapter

-Based Programming

Part

 

Chapter

Layer

Chapter

Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Figure 15-3: Interacting with a Form's Controls collection

Chapter 15 - Programming with Windows Forms Controls

ChapterGiven that16 -SystemThe System.Windows.IO Namespace.Forms.Control-derived types maintain a nested Control.ControlsCollection

type, it stands to reason that you can dynamically add, hide, disable, or remove items using this collection

Chapter 17 - Data Access with ADO.NET

at any point in a Form's lifetime (which can prove quite helpful if you need to dynamically generate new

Part Five - Web Applications and XML Web Services

controls on the fly or restrict which controls should be displayed based on user preferences/ permissions).

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Furthermore, also understand that it is completely possible to dynamically insert (or remove) Windows

Chapter 20 - XML Web Services

widgets into any descendent of System.Windows.Forms.Control (for example, adding RadioButton types

Index

to a GroupBox, TextBox types to a Panel, and so forth). We will see examples of this technique over the

List of Figures

course of this chapter.

List of Tables

SOURCE The ControlsByHand project is included under the Chapter 15 subdirectory.

CODE

Adding ControlsC# and theto.NETFormsPlatform,(viaSecondVS .EditionNET)

by Andrew Troelsen

ISBN:1590590554

Although you are always free to write Windows Forms code "in the raw," you will probably choose to use

Apress © 2003 (1200 pages)

the Visual Studio .NET IDE instead. When you drop a widget from the Toolbox onto the form designer, the

This comprehensive text starts with a brief overview of the

IDE responds byC#automaticallylanguage andaddingthen thequicklycorrectmovesmemberto k yvariabletechnicaltoandthe Form-derived class on your behalf. Of course,architecturalyou will typicallyissueswantfor .NETto changedevelopersthe.name of this new variable (via the Properties window) to represent its overall functionality (e.g., "btnSubmitQuery" rather than the default "button1"). As you design the look and feel of the widget using the IDE's Properties window (Figure 15-4), the underlying

Table of Contents

code changes are added to the InitializeComponent() member function.

C# and the .NET Platform, Second Edition

Introduction

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part

Chapter

Figure 15-4: Design time property configuration

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Be aware that this window allows you to configure not only the property set of a given GUI item, but the set

Chapter 12 - Object Serialization and the .NET Remoting Layer

of events as well (available by clicking the "lightning bolt" icon). Simply select the widget from the drop- Chapterdown list13and- Buildingtype inatheB tternameWindowof the(Introducingmethod to beWindowscalled forF rms)the events you are interested in responding

Chapterto (Figure14 -15A-5Better). Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Index

List of

List of

Figure 15-5: Design time event handling

If you examine the code generated in the InitializeComponent() method, you will find that the type has been configured based on your selections and inserted into the Control$ControlCollection automatically. For example, assume you have configured a TextBox type as follows:

private void InitializeComponent()

{

this.firstNameBox = new System.Windows.Forms.TextBox();

this.firstNameBox.Location = new System.Drawing.Point(32, 40);

this.firstNameBox.TabIndex = 0;

this.firstNameBox.Text = "Chucky";

C# and the .NET Platform, Second Edition

 

this.firstNameBox.TextChanged += new

ISBN:1590590554

by Andrew Troelsen

System.EventHandler(this.firstNameBox_TextChanged);

Apress © 2003 (1200 pages)

this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

This comprehensive textSystems arts with a brief overview of the this.ClientSize = new .Drawing.Size(292, 273);

C# language and then quickly moves to key technical and this.Controls.AddRange(new System.Windows.Forms.Control[]

architectural issues for .NET developers.

{ this.firstNameBox});

...

}

Table of Contents

C# and the .NET Platform, Second Edition

Introduction

Part One - Introducing C# and the .NET Platform

Note that here you use VS .NET to handle the TextChanged event for the TextBox, and are thus provided

Chapter 1 - The Philosophy of .NET

with an empty event handler as well as the correct event registration syntax (an obvious benefit of this

Chapter 2 - Building C# Applications

approach is that you are not the one in charge of determining the correct delegate used to handle a

PartparticularTwo - Theevent):C# Programming Language

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

protected void firstNameBox_TextChanged (object sender, System.EventArgs e)

Chapter 5 - Exceptions and Object Lifetime

{

Chapter 6 - Interfaces and Collections

// Do whatever you need to do...

Chapter 7 - Callback Interfaces, Delegates, and Events

}

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

As you can see, the VS .NET IDE simply saves you some typing. The remainder of this chapter focuses on

Chapter 9 - Understanding .NET Assemblies

a number of behaviors offered by numerous GUI widgets by examining the "raw" code behind the scenes.

Chapter 10 - Processes, AppDomains, Contexts, and Threads

If you decide to use the VS .NET IDE, be sure to examine the code generated inside the

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

InitializeComponent() method to gain a true understanding of Windows Forms programming. Now that you

Part Four - Leveraging the .NET Libraries

understand the process of configuring and inserting types into a Form's Control collection, we can turn our

Chapter 12 - Object Serialization and the .NET Remoting Layer

attention to the specifics of various Windows Forms widgets.

Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Соседние файлы в предмете Программирование