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

Summary C# and the .NET Platform, Second Edition

by Andrew Troelsen ISBN:1590590554

In this chapter, you examined how to configure distinct .NET assemblies to share types between

Apress © 2003 (1200 pages)

application boundaries. As you have seen, a remote object may be configured as an MBV or MBR type.

This comprehensive text starts with a brief overview of the

This choice ultimatelyC# languagecontrolsandhowthena remotequicklytypemovesis realizedto key technicalin the client'sand application domain (a copy or transparent proxy)architectural. Given thisissuesdistinction,for .NETthedeveloperschapter opened. by examining the MBV-centric topic of object serialization.

TableIf youofhaveContentsconfigured a type to function as an MBR entity, you are suddenly faced with a number of C#relatedand thechoices.NET Platform,(WKO vsSecond. CAO, Editionsingle call vs. singleton, and so forth), each of which was addressed

during this chapter. As well, you also examined the process of tracking the lifetime of a remote object via

Introduction

the use of leases and lease sponsorship. Finally, you revisited the role of the .NET delegate type in order

Part One - Introducing C# and the .NET Platform

to understand how to asynchronously invoke a remote method (which, as luck would have it, is identical to

Chapter 1 - The Philosophy of .NET

the process of asynchronously invoking a local type).

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

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

Chapter C#13:andBuildingthe .NET Platform,a SecondBetterEditionWindow (Introducing

by Andrew Troelsen

ISBN:1590590554

Windows Forms)

 

Apress © 2003 (1200 pages)

 

This comprehensive text starts with a brief overview of the

C# language and then quickly moves to key technical and

If you have read through the previous chapters, you should have a solid handle on the C# programming

architectural issues for .NET developers.

language as well as the foundation of the .NET architecture. While you could take your newfound knowledge and begin building the next generation of console applications (boring!) you are more likely to

be interested in building an attractive graphical user interface (GUI) to allow the outside world to interact

Table of Contents with your system.

C# and the .NET Platform, Second Edition

Introduction

This chapter introduces you to the System.Windows.Forms namespace. Here, you learn how to build a ParthighlyOnestylized- IntroducimaingwindowC# and(ethe.g..,NETa FormPlatform-derived class). In the process, you learn about a number of Chapterwindow1-related- The types,Philosophyincludingof .NETMenuItem, ToolBar, StatusBar, and Application. This chapter also

Chapterintroduces2 -howBuildingto captureC# Applicationsand respond to user input (i.e., handling mouse and keyboard events) within the

PartcontextTwo of- Thea GUIC# environmentProgrammi g. AlongLanguagethe way, you will construct a final example that illustrates the

Chapterconstruction3 - C#of MDILanguageapplicationsFundamentalsla Windows Forms.

Chapter 4 - Object-Oriented Programming with C#

ChapterA Tale5 -ofExceptionsThreeandGUIObjectNamespacesLifetime

Chapter 6 - Interfaces and Collections

ChapterThe .NET7 -platformCallback(asInterfaceof version, Delegates,1.1) providesand Eventsthree GUI toolkits, known as "Windows Forms," "Web

Forms," and "Mobile Forms." The System.Windows.Forms namespaces contain a number of types that

Chapter 8 - Advanced C# Type Construction Techniques

allow you to build traditional desktop applications, as well as Windows-based applications that target

Part Three - Programming with .NET Assemblies

handled computing devices (such as the Pocket PC). As you would expect, Windows Forms hides the raw

Chapter 9 - Understanding .NET Assemblies

windowing primitives from view, allowing you to focus on the functionality of your application using the

Chapter 10 - Processes, AppDomains, Contexts, and Threads

familiar .NET type system.

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

Part Four - Leveraging the .NET Libraries

Web Forms, on the other hand, is a GUI toolkit used during ASP.NET development. The bulk of the Web

Chapter 12 - Object Serialization and the .NET Remoting Layer

Form types are contained in the System.Web.UI.WebControls namespace. Using these types, you are

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

able to build browser-independent front ends based on various industry standards (HTML, HTTP, and so

Chapter 14 - A Better Painting Framework (GDI+)

forth). You will get to know the ASP.NET Web controls in Chapter 18.

Chapter 15 - Programming with Windows Forms Controls

Finally, .NET version 1.1 ships with a new GUI-centric namespace, System.Web.UI.MobileControls, which

Chapter 16 - The System.IO Namespace

allow you to build UIs that target mobile devices (such as cellular phones). Not surprisingly, the

Chapter 17 - Data Access with ADO.NET

programming model of Mobile control applications mimics the functionality found within ASP.NET.

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Note Coverage of mobile .NET technologies (including Pocket PC programming) is outside the scope

Chapter 19 - ASP.NET Web Applications

of this text. If you are interested, check out Mobile .NET (Ferguson, Apress 2001).

Chapter 20 - XML Web Services

IndexIt is worth pointing out that while Windows Forms, Web Forms, and Mobile Forms technologies define a

Listnumberof Figuresof similarly named types (e.g., Button, CheckBox, etc.) with similar members (Text, BackColor, Listetcof.),Tablesthey do not share a common implementation and cannot be treated identically. Nevertheless, as you become comfortable with the Windows Forms namespace, you should find the process of learning the details of other .NET GUI toolkits far more palatable.

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
FolderBrowserDialog
Part Four - Leveraging the .NET Libraries
ChapterMenu,12MainMenu,- Obj ct SerializationMenuItem, and the .NET RemotingThese typesLayerare used to build top most and context-
ContextMenu sensitive (pop-up) menu systems.
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
Clipboard, Help, Timer, Screen, Various utility types used to facilitate interactive GUIs.
Chapter 15 - Programming with Windows Forms Controls
ToolTip, Cursors
Chapter 16 - The System.IO Namespace
StatusBar, Splitter, ToolBar, ScrollBar Various types used to adorn a Form with common child
Chapter 17 - Data Access with ADO.NET
controls.
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

Overview ofC#theandSystemthe .NET Platform,.WindowsSecond.FormsEdition Namespace

by Andrew Troelsen

ISBN:1590590554

Like any namespace, System.Windows.Forms is composed of a number of classes, structures, delegates,

Apress © 2003 (1200 pages)

interfaces, and enumerations. Over the next couple of chapters, you drill into the specifics of a good

This comprehensive text starts with a brief overview of the

number of these C#typeslanguage. Whileandit is redundantthen quicklytomoveslist everyto keymembertechnicalof theandWindows Forms family (as they are all documentedarchitecturalin online Help)issuesTablefor .NET13-developers1 lists some. (but by no means all) of the core classes found within System.Windows.Forms.

Table of Contents

Table 13-1: A Subset of Types Within the System.Windows.Forms Namespace

 

 

 

 

 

 

C# and the .NET Platform, Second Edition

 

 

 

IntroductionWindows Forms Class

 

Meaning in Life

 

 

 

 

 

 

Part One - Introducing C# and the .NET Platform

 

 

Application

 

This class represents the guts of a Windows Forms

 

Chapter 1

- The Philosophy of .NET

 

application. Using the members of Application, you are

 

Chapter 2

- Building C# Applications

 

 

 

able to process windows messages, start and

 

Part Two - The C# Programming Language

 

 

 

terminate a Windows Forms application, and so forth.

 

 

 

 

 

 

 

Chapter 3

- C# Language Fundamentals

 

 

 

 

 

These classes (in addition to many others) represent

 

 

ButtonBase, Button, CheckBox,

 

 

 

Chapter 4

- Object-Oriented Programming with C#

 

 

ComboBox, DataGrid, GroupBox,

 

types that correspond to various GUI widgets. You

 

 

Chapter 5

- Exceptions and Object Lifetime

 

examine many of these items in detail in Chapter 15.

 

 

ListBox, LinkLabel, PictureBox

 

 

 

Chapter 6

- Interfaces and Collections

 

 

 

 

 

 

 

 

Chapter 7

- Callback Interfaces, Delegates,

and Events

 

 

Form

 

 

This type represents a main window, dialog box, or MDI

 

 

Chapter 8

- Advanced C# Type Construction

Techniques

 

 

 

 

 

child window of a Windows Forms application.

 

 

 

 

 

 

Part Three - Programming with .NET Assemblies

As you might expect, Windows Forms defines a

 

 

ColorDialog, OpenFileDialog,

 

 

Chapter 9

- Understanding .NET Assemblies

 

number of canned dialog boxes. If these don't fit the

 

 

SaveFileDialog, FontDialog,

 

 

Chapter 10

- Processes, AppDomains, Contexts,

and Threads

 

 

PrintPreviewDialog,

 

bill, you are free to build your own custom dialogs.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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

InteractingC#withand thee .NETWindowsPlatf rm, SecFormsnd EditionTypes

by Andrew Troelsen

ISBN:1590590554

When you build a Windows Forms application, you may choose to write all the relevant code by hand

Apress © 2003 (1200 pages)

(using Notepad perhaps) and send the resulting *.cs files into the C# compiler using the /target:winexe

This comprehensive text starts with a brief overview of the

flag. Taking timeC#to buildlanguagesomeandWindowsthen quicklyFormsmovesapplicationsto key technicalby handandis not only a great learning experience, but alsoarchithelpscturalyouissuesunderstandfor .NETthedeveloperscode generated. by various GUI wizards.

Another option is to build Windows Forms projects using the Visual Studio .NET IDE. To be sure, the IDE

TabledoesofsupplyContentsa number of great wizards, starter templates, and configuration tools that make working with C#Windowsand theForms.NET Platforextremely, SecondsimpleEdition. The problem with wizards, of course, is that if you do not understand

what the generated code is doing on your behalf, you cannot gain a true mastery of the underlying

Introduction

technology.

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Given this fact, you begin by creating your initial Windows Forms examples in the raw (complete with menus, status bars, and toolbars). Over the course of the chapter however, I'll illustrate the use of various

wizards supplied by the Visual Studio .NET. Hopefully, this will also drive the point home that when you do

Chapter 3 - C# Language Fundamentals

leverage VS .NET to build your Windows Forms applications, you are not creating source code that will tie

Chapter 4 - Object-Oriented Programming with C# you to a particular IDE.

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Prepping the Project Workspace

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

To begin understanding Windows Forms programming, let's build a simple main window by hand. The first

Part Three - Programming with .NET Assemblies

order of business is to create a new empty C# project workspace named "MyRawWindow" using the VS

Chapter 9 - Understanding .NET Assemblies

.NET IDE. Next, insert a new C# class definition (resist the temptation to insert a new Windows Form

Chapter 10 - Processes, AppDomains, Contexts, and Threads

class!) from the "Project | Add New Item..." menu option. Name this class MainWindow.

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

PartWhenFouryou- Leveragingbuild a mainthewindow.NET Libyrarieshand, you need to use the Form and Application types (at minimum),

both of which are contained in the System.Windows.Forms.dll assembly. A Windows Forms application

Chapter 12 - Object Serialization and the .NET Remoting Layer

also needs to reference System.dll, given that some types in the Windows Forms assembly make use of

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

types in the System.dll assembly. Add references to these assemblies now (Figure 13-1).

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Index

List of

List of

Figure 13-1: The minimal set of assembly references

Building a Main Window (By Hand)

In the world of Windows Forms, the Form class is used to represent any window in your application. This includes a topmost main window in an SDI (Single Document Interface) application, modeless and modal dialogs, as well as the parent and child windows of an MDI (Multiple Document Interface) application.

When you are interested in creating a new main window, you have two mandatory steps:

Derive a new custom class from System.Windows.Forms.Form.

Configure the application's Main() method to call Application.Run(), passing an instance of your new

Form-derived type as an argument.

C# and the .NET Platform, Second Edition

With these stepsbyin mind,AndrewyouTroelsenare able to update your initial classISBN:1590590554definition as follows:

Apress © 2003 (1200 pages)

This comprehensive text starts with a brief overview of the using System;

C# language and then quickly moves to key technical and using System.Windows.Forms;

architectural issues for .NET developers. namespace MyRawWindow

{

public class MainWindow : Form

Table of Contents

{

C# and the .NET Platform, Second Edition

public MainWindow(){ }

Introduction

// Run this application and identify the main window.

Part One - Introducing C# and the .NET Platform

public static int Main(string[] args)

Chapter 1 - The Philosophy of .NET

{

Chapter 2 - Building C# Applications

Application.Run(new MainWindow());

Part Two - The C# Programming Language

return 0;

Chapter 3 - C# Language Fundamentals

}

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

Here, I have defined with Main() method the scope of the class that represents the main window. If you

Chapter 8 - Advanced C# Type Construction Techniques

prefer, you may wish to create a second class (I named mine, TheApp) which is responsible for the task of

Part Three - Programming with .NET Assemblies

launching the main window:

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chnamespacept r 11 - TypeMyRawWindowReflection, Late Binding, and Attribute-Based Programming

Part{ Four - Leveraging the .NET Libraries

public class MainWindow : Form

Chapter 12 - Object Serialization the .NET Remoting Layer

Chapter{13

- Building a Better Window (Introducing Windows Forms)

Chapter 14

-publicA Better PaintingMainWindow(){}Framework (GDI+)

Chapter}15

- Programming with Windows Forms Controls

public class TheApp

Chapter 16 - The System.IO Namespace

{

Chapter 17 - Data Access with ADO.NET

public static int Main(string[] args)

Part Five - Web Applications and XML Web Services

{

Chapter 18 - ASP.NET Web Pages and Web Controls

Application.Run(new MainWindow());

Chapter 19 - ASP.NET Web Applications return 0;

Chapter 20 -}XML Web Services Index }

List of Figures

}

List of Tables

In either case, Figure 13-2 shows a test run.

Figure 13-2: A simple main window a la Windows Forms

If you notice how your MyRawWindow application has been launched, you should notice an annoying

command window looming in the background. This is because you have not yet configured the build

C# and the .NET Platform, Second Edition

 

settings to generate a Windows *.exe application. To supply the /t:winexe flag from within the IDE, open

by Andrew Troelsen

ISBN:1590590554

the Project Properties window (just right-click the project icon from the Solution Explorer) and expand the

Apress © 2003 (1200 pages)

"Common Properties | General" node. Finally, configure the "Output Type" property as "Windows

This comprehensive text starts withthea brief overview of the

Application" (Figure 13-3). When you recompile, annoying command window will be gone and your

C# language and then quickly moves to key technical and application will run as a true-blue Windows app.

architectural issues for .NET developers.

Table

C# and

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part Three - Programming with .NET Assemblies

Figure 13-3: Specifying /t—winexe within VS .NET

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

So, at this point we have a minimizable, maximizable, resizable, and closable main window (with a default

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

system-supplied icon to boot!). To be sure, it is a great boon to the Win32 programmers of the world to PartforegoFourthe- Leveragingneed to manuallythe .NETconfigureLibraries a WndProc function, establish a WinMain() entry point, and twiddle Chapterthe bits12of -aObjectWNDCLASSEXSerializationstructureand the. .Granted,NET Remotingyour MainWindowLayer does not do too much at this point,

Chowever,apt r 13you'll- Buildienhanceg B tterits functionalityWind w (IntroducingthroughoutWindowsthe chapterForms).

Chapter 14 - A Better Painting Framework (GDI+)

SOURCE The MyRawWindow application can be found under the Chapter 13 subdirectory.

Chapter 15 - Programming with Windows Forms Controls

CODE

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

Building a VSC# and.NETthe .NETWindowsPlatform, SecondFormsEditionProject Workspace

by Andrew Troelsen

ISBN:1590590554

The benefit of building Windows Forms applications using Visual Studio .NET is that the integrated tools

Apress © 2003 (1200 pages)

can take care of a number of mundane coding details by delegating them to a number of wizards,

This comprehensive text starts with a brief overview of the

configuration windows,C# languageand soandforththen. Toquicklyillustratemoveshowtotokeymaketechnicaluse ofandsuch assistance, close your current workspace. Now,architecturalselect a newissuesC# Windowsfor .NET developersApplication. project type (see Figure 13-4).

Table

C# and

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Figure 13-4: The Windows Forms project workspace

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

When you click OK, you will find that you are automatically given a new class derived from

Chapter 10 - Processes, AppDomains, Contexts, and Threads

System.Windows.Forms.Form [with a properly configured Main() method] and have references set to each

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

required assembly (as well as some additional assemblies that you may or may not make use of).

Part Four - Leveraging the .NET Libraries

ChapterYou will12also- Objectsee thatSerializationyou are givenand thea design.NET Re-timeotingtemplateLayer that can be used to assemble the user

interface of your Form (Figure 13-5). Understand that as you update this design-time template, you are

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

indirectly adding code to the associated Form-derived class (named Form1 by default).

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter

Chapter

Part

Services

Chapter

Controls

Chapter

 

Chapter

 

Index

 

List of

 

List of

 

Figure 13-5: The Form Designer

Using the Solution Explorer window, you are able to alternate between this design-time template and the underlying C# code. To view the code that represents your current design, simply right-click the *.cs file and select "View Code". You can also open the code window by double-clicking anywhere on the design time Form; however, this has the (possibly undesirable) effect of writing an event handler for the Form's Load event (more on event processing later in this chapter).

Once you open the code window, you will see a class that looks very much like the following (XML-based code comments removed for clarity):

namespace VSWinApp

C# and the .NET Platform, Second Edition

{

by Andrew Troelsen ISBN:1590590554 public class Form1 : System.Windows.Forms.Form

{Apress © 2003 (1200 pages)

This comprehensive text starts with a brief overview of the

private System.ComponentModel.Container components = null;

C# language and then quickly moves to key technical and public Form1()

architectural issues for .NET developers.

{ InitializeComponent(); }

protected override void Dispose( bool disposing )

{

Table of Contents

if( disposing )

C# and the .NET Platform, Second Edition

{

Introduction

if (components != null)

Part One - Introducing C# and the .NET Platform

{

Chapter 1 - The Philosophy of .NET components.Dispose();

Chapter 2 - Building C# Applications

}

Part Two - The C# Programming Language

}

Chapter 3 - C# Language Fundamentals

base.Dispose(disposing);

Chapter 4 - Object-Oriented Programming with C#

}

Chapter 5 - Exceptions and Object Lifetime

#region Windows Form Designer generated code

Chapter 6 - Inteprivatefaces and Collections

void InitializeComponent()

Chapter 7 - Callback{ Interfaces, Delegates, and Events

Chapter 8 - AdvancedthisC# Type.componentsConstruc ion=Techniquesnew System.ComponentModel.Container();

Part Three - Programmingthiswith.Size.NET =Assembliesnew System.Drawing.Size(300,300);

Chapter 9 - Understandingthis.NETTextAssemblies= "Form1";

}

Chapter 10 - Processes, AppDomains, Contexts, and Threads

#endregion

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

[STAThread]

Part Four - Leveraging the .NET Libraries

static void Main()

Chapter 12 - Object Serialization and the .NET Remoting Layer

{

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

Application.Run(new Form1());

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

As you can see, this class listing is essentially the same code as the previous raw Windows Forms Chapterexample19. Your- ASPtype.NETstillWebderivesApplicatifromnsSystem.Windows.Forms.Form, and the Main() method still calls

ChaApplicationter 20 -.Run()XML Web. TheServicesmajor change is a new method named InitializeComponent(), which is wrapped by

Indthex#region and #endregion preprocessor directives (as described in Chapter 2).

List of Figures

ListTheof TablesRole of InitializeComponent() and Dispose()

The InitializeComponent() method is updated automatically by the Form Designer to reflect the modifications you make to the Form and its controls using the Visual Studio .NET IDE. For example, if you were to use the Properties window to modify the Form's Text and BackColor properties (Figure 13-6), you would find that InitializeComponent() has been modified accordingly:

Edition

ISBN:1590590554

brief overview of the

to key technical and

.

Table

C# and

Part

Chapter

Chapter

Part

Chapter

Figure 13-6: The Properties window provides design time editing support.

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

Chapter 6 - Interfaces and Collections

#region Windows Form Designer generated code

Chapter 7 - Callback Interfaces, Delegates, and Events private void InitializeComponent()

Chapter 8 - Advanced C# Type Construction Techniques

{

Part Three - Programming with .NET Assemblies

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

Chapter 9 - Understanding .NET Assemblies

this.BackColor = System.Drawing.Color.Lime;

Chapter 10 - Processes, AppDomains, Contexts, and Threads this.ClientSize = new System.Drawing.Size(292, 273);

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming this.Text = "My Rad Form";

Part Four - Leveraging the .NET Libraries

}

Chapter 12 - Object Serialization and the .NET Remoting Layer

#endregion

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

Chapter 14 - A Better Painting Framework (GDI+)

The Form-derived class calls InitializeComponent() within the scope of the default constructor:

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapterpublic17Form1()- Data Access with ADO.NET

Part{ Five - Web Applications and XML Web Services

// Required for Windows Form Designer support

Chapter 18 - ASP.NET Web Pages and Web Controls

InitializeComponent();

Chapter 19 - ASP.NET Web Applications

}

Chapter 20 - XML Web Services

Index

List of Figures

Do be very aware that this helper method is simply a well-known member that VS .NET understands. If

List of Tables

you moved all the code within this method into the Form's constructor, your application would run identically. Unlike other windowing toolkits, the wizard-generated code does not tie you to a particular IDE (VS .NET or otherwise).

The final point of interest is the overridden Dispose() method. This method is called automatically when your Form is about to be destroyed, and is a safe place to free any allocated resources.

The SystemC#.Windowsand the .NET.FormsPlatform,.ApplicationSecond Edi ion Class

by Andrew Troelsen

ISBN:1590590554

The Application class defines members that allow you to control various low-level behaviors of a Windows

Apress © 2003 (1200 pages)

Forms application. For example, the Application class defines a set of events that allow you to respond to

This comprehensive text starts with a brief overview of the

events such as applicationC# languageshutdownand thenandquicklyidle processingm ves to key. Fortechnicalthe mostandpart, you do not need to directly interact with this typearchitectural(beyondissuescallingforRun().NETtodevelopersshow your. main window); however, let's check out some of its behavior. To begin, ponder the following core methods (all of which are static) listed in Table 13-2.

Table of Contents

 

 

 

 

 

 

 

Table 13-2: Methods of the Application Type

C# and the .NET Platform, Second

 

 

 

Edition

 

 

 

 

 

IntroductionMethod of the

 

 

 

Meaning in Life

 

 

PartApplicationOne - IntroducingClassC# and the

 

 

 

.NET Platform

 

 

 

 

 

 

 

 

 

Chapter 1 - The Philosophy of .NET

 

These methods allow your application to intercept messages for

 

 

 

 

AddMessageFilter()

 

 

 

 

 

 

Chapter 2 - Building C# Applications

 

any necessary preprocessing. When you add a message filter,

 

 

 

 

RemoveMessageFilter()

 

 

 

 

 

Part Two - The C# Programming

 

Language

 

 

 

 

 

 

 

 

you must specify a class that implements the IMessageFilter

 

 

Chapter 3 - C# Language Fundamentals

 

 

 

 

 

 

 

 

interface (as you do shortly).

 

 

 

 

 

 

Chapter 4 - Object-Oriented Programming with C#

 

 

 

 

DoEvents()

 

 

 

Provides the ability for an application to process messages

 

 

 

Chapter 5 - Exceptions and Object Lifetime

 

 

 

 

 

 

 

 

currently in the message queue, during a lengthy operation (such

 

 

 

Chapter 6 - Interfaces and Collections

 

 

 

 

 

 

 

 

as a looping construct). Think of DoEvents() as a quick and dirty

 

 

 

Chapter 7 - Callback Interfaces, Delegates, and Events

 

 

 

 

 

 

 

 

way to simulate multithreaded behaviors.

 

 

 

 

Chapter 8 - Advanced C# Type

 

 

Construction Techniques

 

 

PartExit()Three - Programming with .NETTerminatesAssembliesthe application.

 

Chapter 9

- Understanding .NET

 

Assemblies

 

 

ExitThread()

 

Exits the message loop on the current thread and closes all

 

 

Chapter 10

- Processes, AppDomains,

 

Contexts, and Threads

 

 

 

 

 

windows owned by the current thread.

 

 

Chapter 11

- Type Reflection, Late

 

Binding, and Attribute-Based Programming

 

 

 

 

PartOLERequired()Four - Leveraging the .NET LibrariesInitializes the OLE libraries. Consider this the .NET equivalent of

 

Chapter 12

- Object Serialization andmanuallythe .NET callingRemotingOleInitialize()Layer .

 

 

 

 

 

 

 

 

Chapter 13

- Building a Better Window (Introducing Windows Forms)

 

 

Run()

 

 

Begins running a standard application message loop on the

 

 

Chapter 14

- A Better Painting Framework (GDI+)

 

 

 

 

 

current thread.

 

 

Chapter 15

- Programming with Windows Forms Controls

Chapter 16

- The System.IO Namespace

ChapterThe Application17 - DataclassAccessalsowithdefinesADO.NETa number of static properties, many of which are read-only. As you

PartexamineFive -theW bfollowingAppl cationstable,andrealizeXML Webthat eachServicesproperty represents some "application-level" trait such as Chaptercompany18 name,- ASP.NETversionWebnumber,Pages andandWebsoCforthntrols. In fact, given what you already know about .NET attributes

(seeChapter 11), many of these properties should look vaguely familiar (Table 13-3).

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Table 13-3: Core Properties of the Application Type

Index

List of Figures

List of Tables

 

 

 

 

 

 

 

 

 

 

 

 

 

Property ofC#Applicationand the .NET Platform,MeaningSecondinEditionLife

 

 

 

 

 

Class

by Andrew Troelsen

 

ISBN:1590590554

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Apress © 2003 (1200 pages)

 

 

Retrieves the registry key for the application data that is

 

 

 

 

 

CommonAppDataRegistry

 

 

 

 

 

 

 

 

This comprehensive text

 

 

starts with a brief overview of the

 

 

 

 

 

 

 

 

 

shared among all users

 

 

 

 

 

 

C# language and then

 

 

quickly moves to key technical and

 

 

 

 

 

 

 

 

 

 

 

 

architectural issues for

 

 

.NET developers.

 

 

 

 

 

CompanyName

 

 

Retrieves the company name associated with the current

 

 

 

 

 

 

 

 

 

application

 

 

 

 

 

 

 

 

 

 

 

 

 

CurrentCulture

 

 

Gets or sets the locale information for the current thread

 

 

Table of Contents

 

 

 

 

 

 

 

 

 

 

 

 

C# and the .NET Platform, Second Edition

 

 

Gets or sets the current input language for the current

 

 

 

 

 

CurrentInputLanguage

 

 

 

 

Introduction

 

 

thread

 

 

 

 

 

 

 

 

 

 

 

Part One - Introducing C# and the .NET Platform

 

 

 

 

ChapterProductName1 - The Philosophy of .NET

Retrieves the product name associated with this

 

 

Chapter 2

- Building C# Applications

application

 

 

 

 

 

 

 

 

 

Part Two - The C# Programming Language

 

 

Retrieves the product version associated with this

 

 

 

 

 

ProductVersion

 

 

 

 

Chapter 3

- C# Language Fundamentals

 

 

application

 

 

 

Chapter 4 - Object-Oriented Programming

 

 

with C#

 

 

 

 

 

 

 

 

 

 

ChapterStartupPath5 - Exceptions and Object Lifetime

 

 

Retrieves the path for the executable file that started the

 

 

 

Chapter 6

- Interfaces and Collections

 

 

application

 

 

 

 

 

 

 

 

 

 

 

 

Chapter 7

- Callback Interfaces, Delegates, and Events

Notice that some properties, such as CompanyName and ProductName, provide a handy way to retrieve

Chapter 8 - Advanced C# Type Construction Techniques

assembly-level metadata. As you recall from Chapter 11, an assembly may be described using a number

Part Three - Programming with .NET Assemblies

of attributes. Thus, if you specify a value for the AssemblyCompany attribute, you may obtain this

Chapter 9 - Understanding .NET Assemblies

information using Application.CompanyName without the making direct use of the types defined within

Chapter 10 - Processes, AppDomains, Contexts, and Threads

System.Reflection.

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

Part Four - Leveraging the .NET Libraries

Finally, the Application class defines the events shown in Table 13-4.

Chapter 12 - Object Serialization and the .NET Remoting Layer

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

 

Table 13-4: Events of the Application Type

 

 

Chapter 14 - A Better Painting Framework (GDI+)

 

 

 

 

ChapterApplication15 - ProgrammingMeaningwith Windowsin LifeForms Controls

 

 

 

 

ChapterEvent16 - The System.IO Namespace

 

 

 

 

 

 

 

 

 

Chapter 17 - Data Access

with ADO.NET

 

 

 

 

ApplicationExit

Occurs when the application is just about to shut down.

 

 

Part Five - Web Applications and XML Web Services

 

 

 

 

 

Idle

Occurs when the application's message loop has finished processing and is

 

 

Chapter 18 - ASP.NET Web Pages and Web Controls

 

 

 

 

 

about to enter an idle state (meaning there are no messages to process at

 

 

Chapter 19 - ASP.NET Web Applications

 

 

 

 

 

the current time).

 

 

 

Chapter 20 - XML Web

Services

 

 

Index

Occurs when a thread in the application is about to terminate. If the main

 

 

 

 

ThreadExit

 

 

List of Figures

thread for an application is about to be shut down, this event will be raised

 

 

List of Tables

before the ApplicationExit event.

 

 

 

 

 

 

 

 

Fun with the Application Class

To illustrate some of the functionality of the Application class (as well as preview Windows Forms event handling), let's enhance our current raw MainWindow to perform the following tasks:

Display some basic information about this application on startup.

Respond to the ApplicationExit event.

Perform some preprocessing of the WM_LBUTTONDOWN message.

To begin, assume that you have extended your manifest using a number of attributes that mark the name of this fine application and the company that created it. Thus, insert a new file named assemblyinfo.cs which contains the following assembly-level attributes:

C# and the .NET Platform, Second Edition

 

// Some attributes regarding this assembly.

ISBN:1590590554

by Andrew Troelsen

[assembly:AssemblyCompany("Intertech, Inc.")]

Apress © 2003 (1200 pages)

[assembly:AssemblyProduct("A Better Window")]

This comprehensive text starts with a brief overview of the

C# language and then quickly moves to key technical and

architectural issues for .NET developers.

The constructor of our Form-derived class can obtain this information using properties of the Application, which are displayed using the Show() method of the MessageBox type:

Table of Contents

using System;

C# and the .NET Platform, Second Edition

using System.Windows.Forms;

Introduction

Part One - Introducing C# and the .NET Platform

namespace AppClassExample

Chapter 1 - The Philosophy of .NET

{

Chapter 2 - Building C# Applications

public class MainForm : Form

Part Two{- The C# Programming Language

Chapter 3 - C# Language Fundamentals

...

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

Chapter 5 - Exceptions and Object Lifetime

{ GetStats(); }

Chapter 6 - Inteprivatefaces and Collections

void GetStats()

Chapter 7 - Callback{ Interfaces, Delegates, and Events

Chapter 8 - Advanced//C#ReadType Constructionsome metadataTechniquesfrom the manifest.

Part Three - Programmingstringwith .NETinfoAssemblies= string.Format("Company: {0}\n",

Chapter 9 - Understanding .NETApplicationAssemblies .CompanyName);

info += string.Format("App Name: {0}\n",

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Application.ProductName);

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

info += string.Format("I live here: {0}",

Part Four - Leveraging the .NET Libraries

Application.StartupPath);

Chapter 12 - Object Serialization and the .NET Remoting Layer

MessageBox.Show(info);

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

When you run this application, you see a message box that displays various bits of information (Figure 13-

Chapter 18 - ASP.NET Web Pages and Web Controls

7).

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of

List of

Figure 13-7: Reading attributes via the Application type

Responding to the ApplicationExit Event

Next, let's configure this Form to respond to the ApplicationExit event. When you wish to respond to events from within a Windows Forms application, you will be happy to find that the same event logic detailed in Chapter 7 is used to handle GUI-based events. Therefore, if you wish to intercept the ApplicationExit event, you simply register an event handler using the += operator:

public class MainForm : Form

{

...

public MainForm()

{

C# and the .NET Platform, Second Edition

...

by Andrew Troelsen ISBN:1590590554

// Intercept the ApplicationExit event.

Apress © 2003 (1200 pages)

Application.ApplicationExit += new EventHandler(Form_OnExit);

}This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and

//Event handler.

architectural issues for .NET developers.

private void Form_OnExit(object sender, EventArgs evArgs)

{

MessageBox.Show("See ya!", "This app is dead...");

Table of Contents

}

C# and the .NET Platform, Second Edition

}

Introduction

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Notice that the signature of the ApplicationExit event handler must conform to a delegate of type

ChaptSystemr 2 - Building C# Applications

.EventHandler:

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

// Many GUI-based events make use of this delegate (EventHandler)

Chapter 4 - Object-Oriented Programming with C#

// which requires two parameters:

Chapter 5 - Exceptions and Object Lifetime

public delegate void EventHandler(object sender, EventArgs e);

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

As you will see, the EventHandler delegate is the most common type used to handle events under

Chapter 8 - Advanced C# Type Construction Techniques

Windows Forms, however, alternatives do exist for other events. The first parameter of the EventHandler

Part Three - Programming with .NET Assemblies

delegate is of type System.Object, which represents the object sending the event. The EventArgs

Chapter 9 - Understanding .NET Assemblies

parameter (or a descendent thereof) contains relevant information for the current event.

Chapter 10 - Processes, AppDomains, Contexts, and Threads

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

While the EventArgs parameter will always work in conjunction with the EventHandler delegate, it also

Part Four - Leveraging the .NET Libraries

functions as the base class to more specific event argument types. For example, if you have an event

Chapter 12 - Object Serialization and the .NET Remoting Layer

handler that responds to a mouse event, the MouseEventArgs parameter will contain mouse related

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

details such as the (x,y) position of the cursor. Keyboard event handlers make use of the KeyEventArgs

Chapter 14 - A Better Painting Framework (GDI+)

type. In any case, if you run the application, you will be able to respond to the termination of this

Chapter 15 - Programming with Windows Forms Controls application.

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Preprocessing Messages with the Application Class

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

The final step of this example is to perform some preprocessing logic of the WM_LBUTTONDOWN

Chapter 19 - ASP.NET Web Applications

message. As you may know, this standard Windows message is sent when the left mouse button has Chapterbeen clicked20 - XMLwithinWebtheServicesclient area of a given Form (or any GUI widget that is equipped to respond to this

Indevent)x . Now, be very aware that you will find a much simpler way to intercept standard mouse events a bit

Listlaterof inFiguresthis chapter. The point of this step is simply to illustrate how to perform custom preprocessing logic Listbeforeof Tablesa given event is fully dispatched to its handler.

When you wish to filter messages in the .NET framework, your first task is to create a new class that implements the IMessageFilter interface. This is extremely simple, given that IMessageFilter defines only one method, PreFilterMessage(). Return "true" to filter the message and prevent it from being dispatched or "false" to allow the message to continue on its way.

Within the scope of your implementation, you may examine the incoming Message.Msg field to extract the numerical value of the Windows message (in this case, WM_LBUTTONDOWN, which is the value 513). For example:

using Microsoft.Win32; // Contains Win32 specific types.

...

// Create a message filter.

public class MyMessageFilter : IMessageFilter

{

public bool PreFilterMessage(ref Message m)

C# and the .NET Platform, Second Edition

{

by Andrew Troelsen

 

ISBN:1590590554

// Intercept the left mouse

button down message.

Apress © 2003 (1200 pages)

//

WM_LBUTTONDOWN = 513.

if (m.Msg == 513)

{ This comprehensive text starts with a brief overview of the

C# language and then quickly moves to key technical and

MessageBox.Show("WM_LBUTTONDOWN is: " + m.Msg); architectural issues for .NET developers.

return true;

}

return false; // All other messages are ignored...

Table of Contents

}

C# and the .NET Platform, Second Edition

}

Introduction

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Once you have created the class that will be filtering the incoming messages, you must register a new

Chapter 2 - Building C# Applications

instance of this type using the static AddMessageFilter() method. Here is the update to your existing

PartMainFormTwo - Theclass:C# Programming Language

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C# public class MainForm : Form

Chapter 5 - Exceptions and Object Lifetime

{

Chapter 6 - Interfaces and Collections

private MyMessageFilter msgFilter = new MyMessageFilter();

Chapter 7 - Callback Interfaces, Delegates, and Events

...

Chapter public8 - AdvancedMainForm()C# Type Construction Techniques

Part Three{ - Programming with .NET Assemblies

Chapter 9 - Understanding... .NET Assemblies

Chapter 10 - Processes,// Add AppDomains,message filterCon xts,. and Threads

Application.AddMessageFilter(msgFilter);

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

}

Part Four - Leveraging the .NET Libraries

// Event handler

Chapter 12 - Object Serialization and the .NET Remoting Layer

private void Form_OnExit(object sender, EventArgs evArgs)

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

{

Chapter 14 - A Better Painting Framework (GDI+)

MessageBox.Show("See ya!", "This app is dead...");

Chapter 15 - Programming with Windows Forms Controls

// Remove message filter.

Chapter 16 - The System.IO Namespace

Application.RemoveMessageFilter(msgFilter);

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

IndexWhen you run this application, you see a message that informs you of the numerical value of the Win32

ListWMof_FiguresLBUTTONDOWN message when you click the left mouse button anywhere in the application.

List of Tables

As you can tell, filtering messages is not a task you need to perform all that often (if ever). Nevertheless, it is nice to know that Windows Forms allows you to drop down to this level of detail if you so choose.

SOURCE The AppClassExample project can be found under the Chapter 13 subdirectory.

CODE

The AnatomyC# andof thea Form.NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Now that you understand the role of the Application type, our next task is to examine the functionality of the

Apress © 2003 (1200 pages)

Form class itself. As you have seen, when you create a new window (or dialog box) you need to define a

This comprehensive text starts with a brief overview of the

new class derivingC#fromlanguageSystemand.Windowsthen quickly.Formsoves.Formto.keyThistechnicalclass gainsa d a great deal of functionality from the types in its inheritancearchite turalchainissues. Figurefor .NET13-8developersillustrates.the big picture.

Table

C# and

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part ThreeFigure- Programming13-8: The derivationwith .NETofAssembliesa custom Form

Chapter 9 - Understanding .NET Assemblies

Before we get to the real meat of the Form's inheritance chain, understand that like any type in the .NET

Chapter 10 - Processes, AppDomains, Contexts, and Threads

universe, Form ultimately derives from System.Object (which should be no surprise to you at this point). As

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

you recall from Chapter 12,MarshalByRefObject defines the behavior to remote this type by reference,

Part Four - Leveraging the .NET Libraries

rather than by value. Thus, if you remotely interact with a Form across the wire, you are manipulating a

Chapter 12 - Object Serialization and the .NET Remoting Layer

reference to the Form on the remote machine (not a local copy of the Form on the client machine).

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

Chapter 14 - A Better Painting Framework (GDI+)

Detailing each and every member of each class in the Form's inheritance chain would require a small

Chapter 15 - Programming with Windows Forms Controls

book in itself. However, it is important to understand the core behavior supplied by each base class. I Chapterassume16that- TheyouSystemwill spend.IO Natimespaceexamining the full details behind each class at your leisure.

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

The ComponentC# a d theClass.NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

The first base class of immediate interest is Component. The Component type provides a canned

Apress © 2003 (1200 pages)

implementation of the IComponent interface. This predefined interface defines a property named Site,

This comprehensive text starts with a brief overview of the

which returns (surprise,C# languagesurprise)and anthenISitequicklyinterfacemoves. Furthermore,to key technicalIComponentand inherits a single event from the IDisposable interfacearchitecturnamedl issuesDisposed:for .NET developers.

public interface IComponent : IDisposable

Table of Contents

{

C# and the .NET Platform, Second Edition

// The Site property.

Introduction

public ISite Site { get; set; }

Part One - Introducing C# and the .NET Platform

// The Disposed event.

Chapter 1 - The Philosophy of .NET

public event EventHandler Disposed;

Chapter 2 - Building C# Applications

}

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

ChapterThe ISite4 interface- Object-definesOrie tedaProgrammingnumber of methodswith C# that allow a Control to interact with the hosting container:

Chapter 5 - Exceptions and Object Lifetime

Chapterpublic6 interface- Inte aces andISiteCollections: IServiceProvider

Chapter{ 7 - Callback Interfaces, Delegates, and Events

Chapter//8 Properties- Advanced C#ofTypetheConstrucISiteioninterfaceTechniques .

Part Threepublic- ProgrammingIComponentwith .NETComponentAssemblies{ get; }

public IContainer Container { get; }

Chapter 9 - Understanding .NET Assemblies

public bool DesignMode { get; }

Chapter 10 - Processes, AppDomains, Contexts, and Threads

public string Name { get; set; }

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)

By and large, the properties defined by the ISite interface are only of interest to you if you are attempting to

Chapter 14 - A Better Painting Framework (GDI+)

build a widget that can be manipulated at design time (such as a custom Windows Forms control).

Chapter 15 - Programming with Windows Forms Controls

ChapterIn addition16 -toThetheSystSitemproperty,.IO NamespaceComponent also provides an implementation of the Dispose() method (as Chapterseen earlier17 - Datain thisAccesschapter)with. RecallADO.NETthat the Dispose() method is called when a component is no longer PartrequiredFive -. Wheneb Applicationsa Form hasandbeenXMLclosed,Web Servicesthe Dispose() method is called automatically for the Form and

for all widgets contained within that form.

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

The ControlC#Classand the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

The next base class of interest is System.Windows.Forms.Control, which establishes the common behaviors

Apress © 2003 (1200 pages)

required by any GUI-centric type. The core members of System.Windows.Forms.Control allow you to configure

This comprehensive text starts with a brief overview of the

the size and positionC# languageof a control,and extractthen quicklythe underlyingmoves to keyHWNDtechnical(i.e., andnumerical handle for a given window), as well as capture keyboardarchitecturalandissuesmouseforinput.NET. Tabledevelopers13-5.defines some of the properties to be aware of.

Table 13-5: Core Properties of the Control Type

Table of Contents

Meaning in Life

C#Controland the .NETPropertyPlatform, Second Edition

 

 

 

 

 

Introduction

Each of these properties specifies various attributes about the

 

 

Top, Left, Bottom, Right,

Part One - Introducing C# and the .NET

Platform

 

 

Bounds, ClientRectangle, Height,

current dimensions of the Control-derived object.

Chapter 1 - The Philosophy of .NET

 

 

 

Width

 

Bounds returns a Rectangle that specifies the size of the control.

Chapter 2

- Building C# Applications

ClientRectangle returns a Rectangle that corresponds to the size

 

 

 

 

Part Two - The C# Programming Language

 

 

Chapter 3

- C# Language Fundamentals

of the client area of the control.

 

 

 

ChapterCreated,4 -Disposed,Object-OrieEntedabled,ProgrammingThesewithpropertiesC# each return a Boolean that specifies the state of

ChapterFocused,5 -VisibleExceptions and Object Lifetimethe current Control.

 

Chapter 6

- Interfaces and Collections

 

 

 

Returns a numerical value (integer) that represents the HWND of

 

 

 

Handle

 

 

 

 

 

 

 

Chapter 7

- Callback Interfaces, Delegates, and Events

 

 

 

 

 

 

 

 

this Control.

 

 

 

Chapter 8

- Advanced C# Type Construction Techniques

 

 

 

 

 

PartModifierKeysThree - Programming with .NET AssembliesThis static property checks the current state of the modifier keys

 

 

Chapter 9

- Understanding .NET Assemblies(shift, control, and alt) and returns the state in a Keys type.

 

 

 

 

 

 

 

 

 

Chapter 10

- Processes, AppDomains,

 

 

Contexts, and Threads

 

 

 

MouseButtons

 

 

This static property checks the current state of the mouse buttons

 

 

 

Chapter 11

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

 

 

 

 

 

 

 

 

(left, right, and middle mouse buttons) and returns this state in a

 

 

Part Four - Leveraging the .NET LibrariesMouseButtons type.

 

 

 

Chapter 12

- Object Serialization and the

 

.NET Remoting Layer

 

 

 

 

 

 

Parent

- Building a Better Window

 

Returns a Control object that represents the parent of the current

 

 

 

Chapter 13

 

(Introducing Windows Forms)

 

 

 

 

 

 

 

 

Control.

 

 

 

Chapter 14

- A Better Painting Framework

 

 

(GDI+)

 

 

 

 

 

 

Chapter 15

- Programming with Windows

 

 

Forms Controls

 

 

 

TabIndex, TabStop

 

 

These properties are used to configure the tab order of the

 

 

 

Chapter 16

- The System.IO Namespace

 

 

Control.

 

 

 

 

 

 

 

 

 

 

 

Chapter 17

- Data Access with ADO.NET

 

 

 

The current text associated with this Control.

 

 

 

Text

 

 

 

 

 

 

Part Five - Web Applications and XML Web Services

 

 

 

 

 

 

 

 

 

 

 

Chapter 18

- ASP.NET Web Pages and Web Controls

Chapter 19

- ASP.NET Web Applications

 

 

 

 

 

The Control base class also defines a number of methods that allow you to interact with any Control-derived

Chapter 20

- XML Web Services

 

 

 

 

type. A partial list of some of the more common members appears in Table 13-6.

Index

List of Figures

Table 13-6: Select Members of the Control Type

List of Tables

GetStyle()
SetStyle()
Hide()
Show()
Invalidate()
Table of Contents

Control MethodC# and theMeaning.NET Platform,in LifeSecond Edition

by Andrew Troelsen

ISBN:1590590554

These methods are used to manipulate the style flags of the current Control

Apress © 2003 (1200 pages)

using the ControlStyles enumeration.

This comprehensive text starts with a brief overview of the

C# language and then quickly moves to key technical and

These methods indirectly set the state of the Visible property. architectural issues for .NET developers.

Forces the Control to redraw itself by forcing a paint message into the

message queue.

C# and the .NET Platform, Second Edition

Introduction

 

 

This method is overloaded to allow you to specify a specific Rectangle to

Part One - Introducing C# andrefresh,the .NETratherPlatformthan the entire client area.

 

 

 

 

 

 

 

 

 

 

Chapter 1

- The Philosophy

 

 

of .NET

 

 

 

 

OnXXXX()

 

 

The Control class defines numerous methods which can be overridden by a

 

 

 

Chapter 2

- Building C# Applications

 

 

 

 

 

 

 

 

subclass to respond to various events (e.g., OnMouseMove(),

 

 

Part Two - The C# Programming Language

 

 

 

 

 

 

 

 

OnKeyDown(), OnResize(), and so forth).

 

 

Chapter 3

- C# Language Fundamentals

 

 

Chapter 4

 

 

 

As you see later in this chapter, when you wish to intercept a GUI-based

 

 

- Object-Oriented Programming with C#

 

 

Chapter 5

 

 

 

event, you have two approaches. One approach is to simply override one of

 

 

- Exceptions and Object Lifetime

 

 

Chapter 6

 

 

 

the existing event handlers. Another is to add a custom event handler to a

 

 

- Interfaces and Collections

 

 

 

 

 

 

 

 

given delegate.

 

 

 

 

Chapter 7

- Callback Interfaces, Delegates, and Events

 

 

 

 

 

 

ChapterRefresh()8 - Advanced C# TypeForcesConstructionthe ControlTechniquesto invalidate and immediately repaint itself and any

 

 

Part Three - Programming withchildren..NET Assemblies

 

 

 

 

 

 

 

 

 

 

Chapter 9

- Understanding

 

 

.NET Assemblies

 

 

 

 

SetBounds(),

 

 

Each of these methods is used to establish the dimensions of the Control-

 

 

 

Chapter 10

- Processes, AppDomains, Contexts, and Threads

 

 

 

 

SetLocation(),

 

 

derived object.

 

 

 

Chapter 11

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

 

 

 

 

SetClientArea()

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Part Four - Leveraging the .NET Libraries

Chapter 12

- Object Serialization and the .NET Remoting Layer

 

Chapter 13

- Building a Better Window (Introducing Windows Forms)

 

Setting a Form's Styles

 

Chapter 14

- A Better Painting Framework (GDI+)

Chapter 15

- Programming with Windows Forms Controls

 

Let's examine two interesting methods of the Control type: GetStyle() and SetStyle(), both of which interact with

Chapter 16

- The System.IO Namespace

 

the ControlStyles enumeration. Win32 programmers are no doubt familiar with the WNDCLASSEX structure,

Chapter 17

- Data Access with ADO.NET

and the dozens of oddball styles that can be used to fill the various fields. While Windows Forms hides this

PartWindowsFive - Web"goo"Applicatfrom view,ons youand areXMLableW btoServicesmodify the default styles of your Form if need be. To illustrate, check

Chapout theer 18related- ASPControlStyles.NET Web Pagenumeration:s and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

public enum ControlStyles

Index

{

List of FiguresAllPaintingInWmPaint, CacheText,

List of TablesDoubleBuffer, ContainerControl,

EnableNotifyMessage, FixedHeight,

FixedWidth, Opaque,

ResizeRedraw, Selectable,

StandardClick, StandardDoubleClick,

SupportsTransparentBackColor,

UserMouse, UserPaint

}

The values of the ControlStyle enumeration may OR-ed together if you wish to specify multiple styles. And, as you would expect, a Form has a default style set (I assume you will check out online Help for full details of each value).

Assume you have a Form containing a single Button type. In the Click event handler of this Button, you can check if the Form supports a given style using GetStyle():

// Shows false!

C# and the .NET Platform, Second Edition

private void btnGetStyles_Click(object sender, System.EventArgs e)

by Andrew Troelsen

ISBN:1590590554

{

Apress © 2003 (1200 pages)

MessageBox.Show(GetStyle(ControlStyles.ResizeRedraw).ToString(),

This comprehensive text starts with a brief overview of the

"Do you have ResizeRedraw?");

C# language and then quickly moves to key technical and

}

architectural issues for .NET developers.

To set the bit of a given style (by specifying true or false) you could write:

Table of Contents

C# and the .NET Platform, Second Edition

public StyleForm()

Introduction

{

Part One - Introducing C# and the .NET Platform

...

Chapter 1 - The Philosophy of .NET

SetStyle(ControlStyles.ResizeRedraw, true);

Chapter 2 - Building C# Applications

}

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

The ResizeRedraw is one value you typically want to add to a given Form. By default this style is not active and

Chapter 5 - Exceptions and Object Lifetime

thus, a Form will not automatically redraw its client area when resized. This means, if you have intercepted a

Chapter 6 - Interfaces and Collections

Paint event (which you will do a bit later) and resize the Form, your drawing logic is not refreshed! If you wish to Chapterensure7that- theCallbackPaintInterfaces,event firesDelegates,wheneverandtheEventsuser resizes the Form, be sure to specify the ResizeRedraw styl

Chapterusing SetStyle()8 - Advanced. C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Another (equally valid) alternative to ensure correct repainting is to intercept the Form's Resize event and call

Chapter 9 - Understanding .NET Assemblies

Invalidate() directly:

Chapter 10 - Processes, AppDomains, Contexts, and Threads

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

private void StyleForm_Resize(object sender, System.EventArgs e)

Part Four - Leveraging the .NET Libraries

{

Chapter 12 - Object Serialization and the .NET Remoting Layer

Invalidate(); // This forces a repaint (more details later...)

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

Typically, you would want to intercept the Resize() event when you have additional work to do beyond triggering

Part Five - Web Applications and XML Web Services

a paint session. If you do not, setting the ControlStyles.ResizeRedraw will do the trick.

Chapter 18 - ASP.NET Web Pages and Web Controls

ChapterNow, to19illustrate- ASP.NETtheWebeffectApplicaof settingionsForm styles, assume you have handled the Form's Paint event and coded

a block of GDI+ rendering logic that draws a dashed black line around the client area rectangle (GDI+ is

Chapter 20 - XML Web Services

detailed in the next chapter, so don't sweat the details):

Index

List of Figures

List//ofGDI+Tablesrequires setting a reference to System.Drawing.dll!

using System.Drawing;

// Needed for Color, Brush, and Font types.

...

 

private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e

{

// A custom dash...

Pen customDashPen = new Pen(Color.Black, 10); float[] myDashes = {5.0f, 2.0f, 1.0f, 3.0f}; customDashPen.DashPattern = myDashes;

e.Graphics.DrawRectangle(customDashPen, ClientRectangle);

}

If the ResizeRedraw bit is set to "false," you find the ugliness shown in Figure 13-9 as you resize the Form.

Second Edition

ISBN:1590590554

starts with a brief overview of the

quickly moves to key technical and

NET developers.

Table Figureof Contents13-9: ControlStyles.ResizeRedraw = false

C# and the .NET Platform, Second Edition

If you set it to "true" you have correct rendering (Figure 13-10).

Introduction

Part One - Introducing C# and the .NET Platform

Chapter

Chapter

Part

Chapter

 

Chapter

with C#

Chapter

 

Chapter

 

Chapter

and Events

Chapter 8 - Advanced C# Type Construction Techniques

Figure 13-10: ControlStyles.ResizeRedraw = true

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

ChapterSOURCE10 - Processes,TheAppDoFormStylesains, Contexts,project isandunderTh eadsthe Chapter 13 subdirectory.

CODE

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

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