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

The Form Class# and the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

This brings us to the Form class itself, which is typically the direct base class for your custom Form types. In

Apress © 2003 (1200 pages)

addition to the large set of members inherited from the Control, ScrollableControl, and ContainerControl

This comprehensive text starts with a brief overview of the

classes, the FormC#typelanguageadds evenand thengreaterquicklyfunctionalitym ves to. Let'sk y technicalstart withandthe core properties (Table 13-14).

architectural issues for .NET developers.

Table 13-14: Properties of the Form Type

 

 

 

 

 

 

 

TableFormof Contents

 

 

Meaning in Life

 

C#Propertyand the .NET Platform, Second Edition

 

 

 

 

 

 

 

 

Introduction

 

 

Gets or sets the button on the Form that is clicked when the user presses the

 

 

AcceptButton

 

 

 

Part One - Introducing

 

 

C# and the .NET Platform

 

 

 

 

 

 

Enter key.

 

 

Chapter 1

- The Philosophy of .NET

 

 

 

 

ChapterActiveMDIChild2 - Buil ing C#EachApplicationsof these properties is used within the context of an MDI application.

 

Part Two - The C# Programming Language

 

 

IsMDIChild

 

 

 

 

Chapter 3

- C# Language Fundamentals

 

 

IsMDIContainer

 

 

 

 

 

Chapter 4

- Object-

 

Oriented Programming with C#

 

 

 

 

 

ChapterAutoScale5 - Exceptions

 

Getsand Objector setsLifetimea value indicating whether the Form will adjust its size to fit the

 

 

Chapter 6

- Interfaces

 

 

andheightCollectionsof the font used on the form and scale its controls.

 

 

 

 

 

 

 

 

 

Chapter 7

- Callback

 

 

Interfaces, Delegates, and Events

 

 

BorderStyle

 

 

Gets or sets the border style of the Form. Used in conjunction with the

 

 

Chapter 8

- Advanced

 

 

C# Type Construction Techniques

 

 

 

 

 

 

FormBorderStyle enumeration.

 

Part Three - Programming

with .NET Assemblies

 

 

 

CancelButton

 

 

Gets or sets the button control that will be clicked when the user presses the

 

Chapter 9

- Understanding .NET Assemblies

 

 

 

 

 

 

Esc key.

 

 

Chapter 10

- Processes,

 

 

AppDomains, Contexts, and Threads

 

 

 

Chapter 11

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

 

 

ControlBox

 

 

Gets or sets a value indicating whether the Form has a control box.

 

 

 

 

 

 

Part Four - Leveraging

 

 

the .NET Libraries

 

 

Menu

- Object

 

 

Gets or sets the (merged) menu for the Form.

 

Chapter 12

 

 

Serialization and the .NET Remoting Layer

 

ChapterMergedMenu13 - Building a

Better Window (Introducing Windows Forms)

 

 

 

 

 

 

 

 

Chapter 14

- A Better Painting Framework (GDI+)

 

MaximizeBox

 

 

Used to determine if this Form will enable the maximize and minimize boxes.

Chapter 15 - Programming with Windows Forms Controls

MinimizedBox

Chapter 16 - The System.IO Namespace

ChapterShowInTaskbar17 - Data AccessShouldwith ADOthis.NETForm be seen on the Windows taskbar?

 

 

 

 

 

Part Five - Web Applications and XML Web Services

 

StartPosition

 

Gets or sets the starting position of the Form at run time, as specified by the

Chapter 18

- ASP.NET Web Pages and Web Controls

 

 

 

 

FormStartPosition enumeration.

 

Chapter 19

- ASP.NET

 

Web Applications

 

WindowState

 

Configures how the Form is to be displayed on startup. Used in conjunction with

 

Chapter 20

- XML Web

 

Services

Index

 

 

the FormWindowState enumeration.

 

 

 

 

 

List of Figures

List of Tables

The truth of the matter is that the Form class does not define a great deal of additional methods. The bulk of a Form's functionality comes from the base classes you have already examined. However, Table 13-15 gives a partial list of some additional methods to be aware of.

Table 13-15: Key Methods of the Form Type

 

 

 

 

 

 

 

 

 

 

Method of theC# andFormthe .NETMeaningPlatform,inSecondLifeEdition

 

 

 

Type

 

by Andrew Troelsen

ISBN:1590590554

 

 

 

 

 

 

 

 

 

 

 

Activate()

Apress © 2003 (1200 pages)

 

 

 

 

 

 

Activate a given Form and give it focus.

 

 

 

 

This comprehensive text starts with a brief overview of the

 

 

 

 

 

 

Close()

 

C# language and then quickly moves to key technical and

 

 

 

 

 

 

Closes a Form.

 

 

 

 

 

architectural issues for .NET developers.

 

 

 

 

 

 

 

 

CenterToScreen()

 

 

Places the Form on the dead center of the screen.

 

 

 

 

 

 

 

 

LayoutMDI()

 

 

 

Arranges each child Form (as specified by the LayoutMDI

 

Table of Contents

 

 

 

enumeration) within the parent Form.

 

 

 

 

 

 

 

 

C# and the .NET Platform, Second

 

 

Edition

 

 

 

 

 

 

OnResize()

 

 

 

May be overridden to respond to Resize events.

 

 

Introduction

 

 

 

 

 

 

 

 

 

 

 

 

Part One - Introducing C# and the

 

 

.NET Platform

 

 

 

ShowDialog()

 

 

 

Displays a Form as a Modal dialog. More on dialog box programming

 

Chapter 1

- The Philosophy of .NET

 

 

 

 

 

 

 

 

at a later time.

 

 

 

Chapter 2

- Building C# Applications

 

 

Part Two - The C# Programming Language

Finally, the Form class does define a number of Events (Table 13-16).

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

Table 13-16: Select Events of the Form Type

Chapter 5 - Exceptions and Object Lifetime

ChapterForm6Event- I erfacesMeaningand CollectinonsLife

Chapter 7 - Callback Interfaces, Delegates, and Events

Activate

Sent when a Form is brought to the front of the active application.

Chapter 8 - Advanced C# Type Construction Techniques

PartClosed,Three -ClosingProgrammingThesewithevents.NET Assembliesare used to determine when the Form is about to close, or has

Chapter 9 - Understandingclosed.NET. Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

MDIChildActive

Sent when a child window is activated.

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

Fun with the Form Class

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

Chapter 14 - A Better Painting Framework (GDI+)

At this point, you should feel quite comfortable with the functionality provided by the Form class and each of

Chapter 15 - Programming with Windows Forms Controls

its parent classes. Here is a main window (MainForm) that makes use of various members in the inheritance

Chapter 16 - The System.IO Namespace chain:

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

public class MainForm: Form

Chapter 18 - ASP.NET Web Pages and Web Controls

{

Chapter 19 - ASP.NET Web Applications

...

Chapter 20 - XML Web Services

 

public MainForm

()

 

Index {

// Configure the initial look and feel of this form.

List of Figures

List of Tables

BackColor = Color.LemonChiffon;

// Background color.

 

Text = "My

Fantastic Form";

// Form's caption.

 

Size = new

Size(200, 200);

// 200 * 200.

 

CenterToScreen();

// Center Form to the screen.

 

// Handle events.

 

 

this.Resize += new EventHandler(this.Form1_Resize);

 

this.Paint

+= new PaintEventHandler(this.Form1_Paint);

}

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

{

Invalidate();

}

// Reference System.Drawing to render this string.

private void MainForm_Paint(object sender, PaintEventArgs e)

{

Graphics g = e.Graphics;

g.DrawString("Windows Forms is for building GUIs!",

 

 

C# and the .NET Platform, Second Edition

 

 

 

 

new Font("Times New Roman", 20),

 

 

by Andrew Troelsen

ISBN:1590590554

 

 

new SolidBrush(Color.Black),

 

 

 

Apress © 2003 (1200 pages)

 

// Display in client rect.

 

}

this.DisplayRectangle);

 

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.

 

 

Here, a Form object that begins life centered on the screen has been created. In addition, the Resize event

Table of Contents

has been handled. Simply call Invalidate() to force the client area to be refreshed. In this way, the text string

C# and the .NET Platform, Second Edition

rendered on the client area always fits within the bounding rectangle Form's client area (note the use of the

Introduction

DisplayRectangle property).

Part One - Introducing C# and the .NET Platform

ChapterSOURCE1 - The PhilosophyThe SimpleFormAppof .NET can be found under the Chapter 13 subdirectory.

ChapterCODE2 - 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

The Life-CycleC# andofthea.WindowsNET Platform, FormSecond EditionType

by Andrew Troelsen

ISBN:1590590554

If you have programmed user interfaces using GUI toolkits such as Java Swing, MFC or the raw Win32 API,

Apress © 2003 (1200 pages)

you are aware that Window types have a number of events which fire during its lifetime. The same holds true

This comprehensive text starts with a brief overview of the

for System.WindowsC# language.Forms.Formand -thderivedn quicklytypesmoves. Tableto key13-17technicaldocumentsand lifetime-centric Form level events.

architectural issues for .NET developers.

Table 13-17: Form Life Time Events

 

 

 

 

 

 

 

TableFormof Contents

 

 

Meaning in Life

 

C#Lifetimeand the .NET Platform, Second Edition

 

IntroductionEvent

 

 

 

 

 

 

 

 

 

Part One - Introducing

 

 

C# and the .NET Platform

 

 

Activated

 

 

Occurs whenever the Form is activated, meaning the Form has been given the

 

Chapter 1

- The Philosophy of .NET

 

 

 

 

 

 

current focus on the desktop.

 

 

Chapter 2 - Building C# Applications

 

 

 

PartClosingTwo - The C# ProgrammingOccurs whenLanguagea Form is about to be closed completely. As you will see, this

 

Chapter 3

- C# LanguagemethodFundamentalsallows you to prompt the user with the obligatory "Are you sure you

 

 

 

 

 

 

wish to close this form" message.

 

 

Chapter 4 - Object-Oriented Programming with C#

 

 

 

 

 

 

Chapter 5 - Exceptions

 

 

and Object Lifetime

 

 

Closed

 

 

 

This occurs when the Form is truly closing down and is about to be disposed.

 

 

Chapter 6 - Interfaces

 

 

and Collections

 

 

 

 

 

 

Deactivate

 

 

Occurs whenever the Form is deactivated, meaning the Form has lost current

 

 

Chapter 7

- Callback

 

 

Interfaces, Delegates, and Events

 

 

 

 

 

 

focus on the desktop.

 

 

Chapter 8

- Advanced

 

 

C# Type Construction Techniques

 

 

 

 

PartLoadThree - ProgrammingOccurswith .afterNET Assembliesthe Form has been allocated into memory, but is not yet visible on

Chapter 9 - Understandingthe screen.NET Assemblies.

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Dispose

As you have already seen, the Dispose() method is called automatically to

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming allow the type to perform any clean up.

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Of course, the true life of a Form begins when the Application.Run() method triggers the type's constructor.

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

Once the object has been allocated on the heap, the first event that fires is Load. Within Load, you are free to

Chapter 14 - A Better Painting Framework (GDI+)

configure the look and feel of Form (to augment the work preformed by the InitializeComponent() method),

Chapter 15 - Programming with Windows Forms Controls

prepare any contained child controls (such as ListBoxes, TreeViews, and whatnot), or simply allocate

Chapter 16 - The System.IO Namespace

resources used during the Form's operation (database connections, handles to remote objects, or whatnot).

Chapter 17 - Data Access with ADO.NET

PartOnceFivethe- WebLoadApplicationsevent has fired,and XMLthe nextWebeventServicesis Activate. As mentioned, this event fires when the Form Chapterreceives18focus- ASPas.NETtheWebactivePageswindowand Webon theControlsdesktop. The logical counterpart to the Activate event is (of

course) Deactivate, which fires when the Form loses focus as the active window. As you can guess, the

Chapter 19 - ASP.NET Web Applications

Activate and Deactivate events can fire numerous times over the life of a given Form type.

Chapter 20 - XML Web Services

Index

When the user has chosen to close the Form in question, two close-centric events fire: Closing and Closed.

List of Figures

The Closing event is fired first, and is an ideal place to prompt the end user with the much hated "Are you

List of Tables

sure you wish to close this application?" dialog box. As you are aware, this type of confirmation is quite helpful when you wish to ask the user if s/he wishes to save the current application-centric data. The Closing event works in conjunction with System.ComponentModel.CancelEventHandler delegate, which maps to methods that take a System.ComponentModel.CancelEventArgs type as its second argument (the first, as always is a System.Object). If you set the CancelEventArgs.Cancel property to "true," you prevent the Form from being destroyed and instruct it to return to normal operation. For example:

// Assume you have handled the Closing event in the Form. private void MainForm_Closing(object sender,

System.ComponentModel.CancelEventArgs e)

{

DialogResult dr = MessageBox.Show("Do you REALLY want to close this app?", "Closing event!", MessageBoxButtons.YesNo);

if(dr == DialogResult.No) e.Cancel = true;

else

Chapter 19 - ASP.NET Web Applications

e.Cancel = false;

}

C# and the .NET Platform, Second Edition

 

by Andrew Troelsen

ISBN:1590590554

 

 

Apress © 2003 (1200 pages)

 

Here, we displayThisa messagecompr hensivebox thattextcontainsstarts Yeswithanda briefNooverviewbuttons,ofandthecapture which button was clicked via the returned DialogResultC# languagetypeand(morethenonquicklythis typemovesandtodialogkey technicalboxes inandgeneral in Chapter 15). If the user

architectural issues for .NET developers.

clicks the No button, we set the CancelEventArgs.Cancel property to true, thereby preventing the Form from shutting down.

Table of Contents

Assuming the user does want to close the Form completely, the next event of the Form's life cycle is Closed. C#Here,and youthe .areNETablePlatform,to cleanSecondup anyEditionacquired resources, write to log files, or what have you. Last but not least,

Introductithe Dispose()n method will be called to allow the Form to clean up any contained widgets.

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

A Form Lifetime Example

Chapter 2 - Building C# Applications

PartTo solidifyTwo - ThetheC#sequenceProgrammingof eventsLanguthatgetake place during a Form's lifetime, assume you have a new Chaapplicationter 3 -thatC# Languagehandles theFundamentalsLoad, Activated, Deactivate, Closing, and Close events:

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

public MainForm()

Chapter 6 - Interfaces and Collections

{

Chapter 7 - Callback Interfaces, Delegates, and Events

InitializeComponent();

Chapter this8 - Advanced.ClosingC#+=TypenewConstruction Techniques

Part Three - ProgramSystem.ingComponentModelwith .NET Assemblies.CancelEventHandler(this.MainForm_Closing);

Chapter this9 - Understanding.Load += new.NETSystemAs emblies.EventHandler(this.MainForm_Load);

Chapter this10 - Proces.Closeds, AppDomains,+= new SystemContexts,.EventHandler(thisThreads .MainForm_Closed);

this.Activated += new System.EventHandler(this.MainForm_Activated);

Chapter 11 - Type Reflection, Late Binding, and Attribute-B sed Programming

this.Deactivate += new System.EventHandler(this.MainForm_Deactivate);

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+)

In each registered event handler, we are going to update a private System.String member variable (named

Chapter 15 - Programming with Windows Forms Controls

lifeTimeInfo) with a simple message that displays the name of the event that has just been intercepted:

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

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

Part Five - Web Applications and XML Web Services

{ lifeTimeInfo += "Load event\n"; }

Chapter 18 - ASP.NET Web Pages and Web Controls

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

{ lifeTimeInfo += "Activate event\n"; }

Chapter 20 - XML Web Services

private void MainForm_Closing(object sender,

Index System.ComponentModel.CancelEventArgs e)

List of Figures

{

List of Tables

...

lifeTimeInfo += "Closing event\n";

}

private void MainForm_Deactivate(object sender, System.EventArgs e) { lifeTimeInfo += "Deactivate event\n"; }

private void MainForm_Closed(object sender, System.EventArgs e) { lifeTimeInfo += "Closed event\n"; }

Finally, in Dispose(), display your string using a MessageBox type:

protected override void Dispose(bool disposing)

{

MessageBox.Show(lifeTimeInfo, "Life time events");

...

}

C# and the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Now, run your application and shift the Form into and out of focus a few times (to trigger the Activate and

Apress © 2003 (1200 pages)

Deactivate events). Once you shut down the Form, you will see a message box looking something like Figure

This comprehensive text starts with a brief overview of the

13-13. C# language and then quickly moves to key technical and architectural issues for .NET developers.

Table

 

C# and

Edition

Part

the .NET Platform

Chapter

.NET

Chapter

Applications

Part

Language

Chapter

Fundamentals

Chapter

Programming with C#

Chapter

Object Lifetime

ChapterFigure6 - 13Interfaces-13: FormandeventsCollections

Chapter 7 - Callback Interfaces, Delegates, and Events

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

Chapter 8 - Advanced C# Type Construction Techniques

CODE

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

Handing FormC# andLevelthe .NETEventsPlatform,aSecondla VSEdition.NET

by Andrew Troelsen

ISBN:1590590554

Although you are always free to handle Form-level events by authoring the necessary logic by hand, it is

Apress © 2003 (1200 pages)

worth pointing out that VS .NET offers design-time support as well. If you examine the IDE's Property

This comprehensive text starts with a brief overview of the

Window, you will C#noticelanguagea smallandlightningthen quicklybolt iconmoves. Onceto keyselected,technicalyouandwill find the set of events for whatever GUI widgetarchitecturalyou selectissuesfromforthe.NETdropdevelopers-down list. box mounted on the top of the Window. Simply locate the name of the event you wish to handle and type in the name to be used as an event handler (or simply double-click the event to generate a default name).

Table of Contents

C#Forandexample,the .NETFigurePlatform,13-14SecondillustratesEditionhow you could handle the Load event for a given Form.

Introduction

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part

Chapter

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Figure 13-14: Form events

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

Part Four - Leveraging the .NET Libraries

If you were now to look at the code behind your Form, you would find that the InitializeComponent()

Chapter 12 - Object Serialization and the .NET Remoting Layer

method has been updated to handle the given event, and a empty event handler has been generated

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

automatically. As you might guess, this same technique can be used to autogenerate events for any GUI

Chapter 14 - A Better Painting Framework (GDI+)

widget (as you will see over the course of this text).

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Note The default name used to generate an event handler is formed as ClassName_EventName

Chapter 17 - Data Access with ADO.NET

therefore, it is always a good idea to name your GUI types appropriately before autogenerating

Part Five - Web Applications and XML Web Services

events (unless you like manually renaming auto-generated code).

Chapter 18 - ASP.NET Web Pages and Web Controls

Note Every GUI widget has a default event, which simply refers to the event that will be handled if you

Chapter 19 - ASP.NET Web Applications

double-click the item at design time. For example, a Form's default event is Load, and if you

Chapter 20 - XML Web Services

Index double-click anywhere on a Form type, the IDE will automatically write code to handle this event.

List of Figures

List of Tables

Building MenusC# and withthe .NETWindowsPlatform, SecondFormsEdition

by Andrew Troelsen

ISBN:1590590554

Now that you understand the composition and lifecycle of the Form class, the next task is to learn how to

Apress © 2003 (1200 pages)

establish a menu system to provide some degree of user interaction. The System.Windows.Forms

This comprehensive text starts with a brief overview of the

namespace providesC# langa numberage andofthentypesquicklythat facilitatemoves tothekeybuildingtechnicalof mainand menus (e.g., menus mounted at the top of a Form),architecturas well asl issuescontextfor-sensitive.NET d veloperspop-up .menus (e.g., "right-click" menus). To begin, let's examine what it would take to build a topmost menu that allows the user to exit the application using a standard "File | Exit" menu command.

Table of Contents

C#Theandfirsttheclass.NETtoPlatform,be awareSecondof is SystemEdition .Windows.Forms.Menu, which functions as the base class for all

other menu-related classes (MainMenu, MenuItem, and ContextMenu). Be aware that

Introduction

System.Windows.Forms.Menu is an abstract class, and therefore you cannot create a direct instance of

Part One - Introducing C# and the .NET Platform

this type. Rather, you create instances of one (or more) of the derived types. The Menu class defines basic

Chapter 1 - The Philosophy of .NET

menu-centric behaviors such as providing access to an individual menu item, cloning menus, merging

Chapter 2 - Building C# Applications

menus (for MDI applications), and so forth. Figure 13-15 shows the relationship between these core types.

Part Two - The C# Programming Language

 

Chapter 3 - C# Language Fundamentals

 

Chapter

C#

Chapter

 

Chapter

 

Chapter

Events

Chapter

Techniques

Part

 

ChapterFigure9 - 13Understanding-15: Menu-centric.NET Assembliestypes of Windows Forms

Chapter 10 - Processes, AppDomains, Contexts, and Threads

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

Note that the Menu class defines a nested class named MenuItemCollection, which is inherited by the

Part Four - Leveraging the .NET Libraries

 

MainMenu, MenuItem, and ContextMenu subclasses. As you would expect, this collection holds onto a set

Chapter 12

- Object Serialization and the .NET Remoting Layer

 

of related menu items, which is accessed using the Menu.MenuItems property (more details in a moment).

Chapter 13

- Building Better Window (Introducing Windows Forms)

 

The Menu base class defines the core members shown in Table 13-18.

Chapter 14

- A Better Painting Framework (GDI+)

 

Table 13-18: Members of the Menu Type

Ch pt r 5

- Programming with Windows Forms Controls

 

 

 

 

 

 

 

 

 

 

 

Chapter 16

- The System.IO Namespace

 

 

 

ChapterMenu17Member- Data AccessMeaningwith ADO.NETin Life

 

 

 

 

 

 

 

 

 

 

 

 

 

 

PartHandleFive - Web ApplicationsThis propertyand XMLprovidesWeb Servicesaccess to the underlying Win32 HMENU handle that

Chapter 18 - ASP.NET representsWeb Pages andthis WebMenuControls.

 

Chapter 19 - ASP.NET

 

Web Applications

 

IsParent

 

This property specifies whether this menu contains any items or is the topmost

 

Chapter 20 - XML Web

Services

Index

 

item.

 

 

ListMdiListItemof Figures

 

This property returns the MenuItem that contains the list of MDI child windows.

 

 

 

 

List of Tables

 

Another property. Returns an instance of the nested

 

MenuItems

 

 

 

 

Menu.MenuItemCollection type, which represents the submenus owned by the

 

 

 

Menu derived class.

 

 

 

 

 

GetMainMenu()

 

Returns the MainMenu item that contains this menu.

 

 

 

 

 

MergeMenu()

 

Merges another menu's items with this one's as specified by their mergeType

 

 

 

and mergeOrder properties. Used to merge an MDI container's menu with that

 

 

 

of its active MDI child.

 

 

 

 

 

CloneMenu()

 

Sets this menu to be an identical (deep) copy of another menu.

Menu$MenuItemCollection Type

Perhaps the most immediately important member of the Menu class is the MenuItems property, which returns an instance of the nested Menu$MenuItemCollection type (recall that the the ;'$' notation is just a

convention to represent a nested type, and has nothing at all to do with C# or .NET code). Recall that

 

C# and the .NET Platform, Second Edition

 

nested classes can be helpful when you wish to establish a logical relationship between related types.

 

by Andrew Troelsen

ISBN:1590590554

Here, the Menu$MenuItemCollection type represents the set of all submenus owned by a Menu-derived

object.

Apress © 2003 (1200 pages)

 

 

This comprehensive text starts with a brief overview of the

For example, if youC#createdlanguagea andMainMenuthen quicklyto representmov s tothekeytopmosttechnical"File"andmenu, you would add MenuItems

architectural issues for .NET developers.

(for example, Open, Save, Close, Save As) into the collection. As you would expect,

Menu$MenuItemCollection defines members to add and remove MenuItem types, obtain the current count of MenuItems, as well as access a particular member in the collection. Table 13-19 lists some (but not all)

Table of Contents

of the core members.

C# and the .NET Platform, Second Edition

Introduction

 

 

 

Table 13-19: The Nested MenuItemCollection Type

Part One - Introducing C# and the .NET

 

Platform

 

ChapterMenu1$MenuItemCollection- The Philosophy of .NET

 

 

Meaning in Life

 

ChapterMember2 - Building C# Applications

 

 

 

 

 

 

 

 

 

 

Part Two - The C# Programming Language

 

 

 

 

 

 

Count

 

 

 

Returns the number of MenuItems in the collection.

 

 

Chapter 3 - C# Language Fundamentals

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

ChapterAdd()4 - Object-Oriented ProgrammingInsertswith C#(or removes) a new MenuItem into the collection.

Chapter 5 - Exceptions and Object Lifetime(Add adds/ remove removes. Add does not remove.) Be

 

 

 

AddRange()

aware that the Add() method has been overloaded

Chapter 6

- Interfaces and Collections

 

 

 

Remove()

numerous times to allow you to specify shortcut keys,

Chapter 7

- Callback Interfaces, Delegates, and Events

Chapter 8

 

 

 

delegates, and whatnot.

- Advanced C# Type Construction Techniques

Part Three - Programming with .NET AssembliesAddRange() is helpful in that it allows you to add an array of

Chapter 9 - Understanding .NET AssembliesMenuItems in a single call.

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Clear()

Removes all items from the collection.

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

PartContains()Four - Leveraging the .NET Libraries Used to determine if a given MenuItem is inside the

collection.

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

Building YourC# andMenuthe .NETSystemPlatfor , Second Edition

by Andrew Troelsen

ISBN:1590590554

Now that you understand the functionality of the abstract Menu class (and the nested MenuItemCollection

Apress © 2003 (1200 pages)

type), you can build your simple File menu. The process begins by creating a MainMenu object. The

This comprehensive text starts with a brief overview of the

MainMenu class representsC# languagetheandcollectionth n quicklyof topmostmoves tomenukey technicalitems (e.gand., File, Edit, View, Tools, Help, and so forth) which appeararchitecturalon a Formissuestypefor..Thus:NET developers.

public class MainForm : Form

Table of Contents

{

C# and the .NET Platform, Second Edition

// The Form's main menu.

Introduction

private MainMenu mainMenu = new MainMenu();

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

ChaptOnceryou3 -haveC# Languagecreated aFundamMainMenutalsobject, use the Menu$MenuItemCollection.Add() method to insert the Chaptertopmost4 item- Object(the -"File"Ori ntedmenu)Programming. Menu$MenuItemCollectionwith C# .Add() returns a MenuItem object that

represents the newly inserted File menu.

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

To insert the subitems (e.g., Exit), you insert MenuItem types into the Menu$MenuItemCollection

Chapter 7 - Callback Interfaces, Delegates, and Events

maintained by the File MenuItem. Finally (and most important), when you are finished populating the

Chapter 8 - Advanced C# Type Construction Techniques

MainMenu type, attach it to the owning Form using the inherited Menu property. If you fail to do so, your

Part Three - Programming with .NET Assemblies

menu system will not be visible! Here are the relevant code updates:

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads public class MainForm : Form

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

{

Part Four - Leveraging the .NET Libraries

// The Form's main menu.

Chapter 12 - Object Serialization and the .NET Remoting Layer private MainMenu mainMenu = new MainMenu();

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

Chapter 14 - A Better Painting Framework (GDI+)

{

Chapter 15 - Programming with Windows Forms Controls

// Create the 'File' Menu and add it to the MenuItemCollection.

Chapter 16 - The System.IO Namespace

MenuItem miFile = mainMenu.MenuItems.Add("&File");

Chapter 17 - Data Access with ADO.NET

// Now make the Exit MenuItem and add it to the File MenuItem.

Part Five - Web//ApplicationsThis versionand XML Webof Add()Servicestakes:

Chapter 18

- ASP.NET Web Pages and Web Controls

 

 

// 1) A new MenuItem.

Chapter 19

- ASP//.NET2)WebA newApplicationsdelegate (EventHandler).

Chapter 20

- XML//Web3) ServicesAn optional shortcut key.

Index

 

miFile.MenuItems.Add(new MenuItem("E&xit",

List of Figures

new EventHandler(this.FileExit_Clicked),

List of Tables

Shortcut.CtrlX));

// Attach main menu to the Form object. this.Menu = mainMenu;

}

...

}

Notice that if you embed an ampersand within the string name of a menu item, this marks which letter should be underlined to designate the Alt key access combination. Thus, when you specify "&File," you allow the user to activate the File menu by selecting "Alt+F."

When you added the Exit submenu item, you specified an optional shortcut flag. The System.Windows.Forms.Shortcut enumeration is fully detailed in online Help. As you might guess, this enumeration provides fields that specify traditional shortcut keys (Ctrl+C, Ctrl+V, F1, F2, Ins) as well as more exotic combinations.

Here then, is the current code for the simple menu application. Just for kicks, notice how you are able to

C# and the .NET Platform, Second Edition

set the BackColor property of the Form using the MainMenu.GetForm() method:

by Andrew Troelsen

ISBN:1590590554

Apress © 2003 (1200 pages)

// The Simple Menu Application.

This comprehensive text starts with a brief overview of the

public class MainForm : Form

C# language and then quickly moves to key technical and

{architectural issues for .NET developers.

//The Form's main menu.

private MainMenu mainMenu = new MainMenu();

Table of //ContentsRun the application.

public static void Main(string[] args)

C# and the .NET Pla form, Second Edition

{

Introduction

Application.Run(new MainForm());

Part One - Introducing C# and the .NET Platform

}

Chapter 1 - The Philosophy of .NET

// Construct the form.

Chapter 2 - Building C# Applications

public MainForm()

Part Two - The C# Programming Language

Chapter{3 - C# Language Fundamentals

// Configure the initial look and feel of this form.

Chapter 4 - Object-Oriented Programming with C#

Text = "Simple Menu";

Chapter 5 - Exceptions and Object Lifetime

CenterToScreen();

Chapter 6 - Interfaces and Collections

// Create the 'File | Exit' Menu.

Chapter 7 - Callback Interfaces, Delegates, and Events

MenuItem miFile = mainMenu.MenuItems.Add("&File");

Chapter 8 - Advanced C# Type Construction Techniques

miFile.MenuItems.Add(new MenuItem("&Exit",

Part Three - Programming with .NET Assemblies

new EventHandler(this.FileExit_Clicked),

Chapter 9 - Understanding .NET AssembliesShortcut.CtrlX));

Chapter 10 - Processes, AppDomains, Contexts, and Threads

// Attach main menu to the Form object.

Chapter 11 - Type ReflMenuction, Late Binding, and Attribute-Based Programming this. = mainMenu;

Part Four - Leveraging// MainMenuthe .NET.GetForm()Libraries returns a reference to the owning Form.

Chapter 12 - Object// ToSeriaillustrateization nd...the .NET Remoting Layer

Chapter 13 - BuildimainMenugBetter.GetForm()Window (Introducing.BackColorWindows= ColorF rms).Black;

Chapter}14 - A Better Painting Framework (GDI+)

// File | Exit Menu item handler

Chapter 15 - Programming with Windows Forms Controls

private void FileExit_Clicked(object sender, EventArgs e)

Chapter 16 - The System.IO Namespace

Chapter{17 - Data Access with ADO.NET

this.Close(); // Just close the application...

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

ListAddingof F guresAnother Topmost Menu Item

List of Tables

Now, what if you wish to add another topmost menu named "Help" that contains a single subitem named "About" (Figure 13-16)?

Figure 13-16: A more elaborate main menu

The code models the "File | Exit" menu logic almost exactly: Begin by adding a new MenuItem ("Help") to the MainMenu object. From here, add a new subitem ("About"):

public class MainForm : Form

C# and the .NET Platform, Second Edition

{

by Andrew Troelsen

ISBN:1590590554

private ApressMainMenu© 2003 (1200mainMenupages)

= new MainMenu();

...

This comprehensive text starts with a brief overview of the

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

{

architectural issues for .NET developers.

// Create the 'File | Exit' Menu.

MenuItem miFile = mainMenu.MenuItems.Add("&File");

Table of ContentsmiFile.MenuItems.Add(new MenuItem("E&xit",

C# and the .NET Platform,newSecondEventHandler(thisEdition .FileExit_Clicked),

Introduction

Shortcut.CtrlX));

 

 

Part One - Introducing// NowC#createand the .NETa 'HelpPlatform| About' menu.

Chapter 1

- TheMenuItemPhilosophymiHelpof .NET = mainMenu.MenuItems.Add("Help");

Chapter 2

- BuildingmiHelp.MenuItems.Add(newC# Applications

MenuItem("&About",

Part Two - The C# Programmingnew EventHandler(this.HelpAboutLanguage

_Clicked),

Chapter 3

- C# LanguageShortcut.CtrlA));Fundamentals

 

 

Chapter 4

- Object...-Oriented Programming with C#

 

}

Chapter 5 - Exceptions and Object Lifetime

// Help | About Menu handler

Chapter 6 - Interfaces and Collections

private void HelpAbout_Clicked(object sender, EventArgs e)

Chapter 7 - Callback Interfaces, Delegates, and Events

{

Chapter 8 - Advanced C# Type Construction Techniques

MessageBox.Show("The amazing menu app...");

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

ChapterSOURCE12 - Object SerializationThe SimpleMenuand the application.NET Remotingis locatedLay r under the Chapter 13 subdirectory.

CODE

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

Creating a C#Popand-Upthe .MenuNET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Let's now examine the process of building a context-sensitive pop-up (i.e., right-click) menu. The

Apress © 2003 (1200 pages)

ContextMenu class represents the pop-up menu itself. Like the process of building a MainMenu, your goal

This comprehensive text starts with a brief overview of the

is to add individualC#MenuItemsla guage andto thethenMenuItemCollectionquickly moves to keytotechnicalrepresentandthe possible selectable subitems. The following classarchitecturalmakes useissuesof a forpop.-NETup menudevelopersto allow. the user to configure the font size of a string rendered to the client area:

Table of Contents

namespace MainForm

C# and the .NET Platform, Second Edition

{

Introduction

// Helper enum for font size.

Part One - Introducing C# and the .NET Platform

internal enum TheFontSize

Chapter 1 - The Philosophy of .NET

{

Chapter 2 - Building C# Applications

FontSizeHuge = 30,

Part Two - The C# Programming Language

FontSizeNormal = 20,

Chapter 3

- C# Language Fundamentals

 

 

 

FontSizeTiny = 8

 

Chapter 4

- Object-Oriented Programming with C#

 

}

 

 

 

Chapter 5

- Exceptions and Object Lifetime

 

Chapter public6 - InterfacesclassandMainFormCollections : Form

 

Chapter {7

- Callback Interfaces, Delegates, and Events

 

Chapter 8

- Advanced// CurrentC# TypesizeConstructionof font.Techniques

 

Part Three - Programmingprivate withTheFontSize.NET AssembliescurrFontSize

 

Chapter 9

- Understanding= TheFontSize.FontSizeNormal;.NET Assemblies

 

Chapter 10

- Processes,// The AppDomains,Form's popupContexts,menu.and Threads

 

Chapter 11

- TypeprivateReflection,ContextMenuLate Binding, andpopUpMenuAttribute-Based= newProgrammingContextMenu();

Part Four - Leveragingpublicthestatic.NET Librariesvoid Main(string[] args)

Chapter 12

- Object{ Application.Run(newSerialization and the .NET RemotingMainForm());Layer

}

Chapter 13

- Buildingprivatea BettervoidWindowMainForm(Introducing_Resize(objectWindows Forms)sender, System.EventArgs e)

Chapter 14

 

{ Invalidate(); }

 

- A Better Painting Framework (GDI+)

 

Chapter 15

 

public MainForm()

 

- Programming with Windows Forms Controls

 

Chapter 16

 

{

 

- The System.IO Namespace

 

 

 

// Now add the subitems & attach context menu.

Chapter 17

- Data Access with ADO.NET

 

 

 

popUpMenu.MenuItems.Add("Huge",

 

Part Five - Web Applications and XML Web Services

 

 

 

new EventHandler(PopUp_Clicked));

Chapter 18

- ASP.NET Web Pages and Web Controls

 

 

 

popUpMenu.MenuItems.Add("Normal",

Chapter 19

- ASP.NET Web Applications

 

 

 

new EventHandler(PopUp_Clicked));

Chapter 20

- XML Web Services

 

 

 

popUpMenu.MenuItems.Add("Tiny",

 

Index

 

new EventHandler(PopUp_Clicked));

List of Figures

this.ContextMenu = popUpMenu;

 

List of Tables

// Handle events.

 

 

 

this.Resize += new System.EventHandler(this.MainForm_Resize);

 

 

this.Paint += new PaintEventHandler(this.MainForm_Paint);

}

// PopUp_Clicked | X Menu item handler

private void PopUp_Clicked(object sender, EventArgs e)

{

// Figure out the string name of the selected item.

MenuItem miClicked = null; if (sender is MenuItem)

miClicked = (MenuItem)sender;

else

return;

string item = miClicked.Text; if(item == "Huge")

currFontSize = TheFontSize.FontSizeHuge;

if(item == "Normal")

C# and the .NET Platform, Second Edition

currFontSize = TheFontSize.FontSizeNormal;

by Andrew Troelsen

ISBN:1590590554

if(item == "Tiny")

 

Apress © 2003 (1200 pages)

currFontSize = TheFontSize.FontSizeTiny;

This comprehensive text starts with a brief overview of the

Invalidate();

} C# language and then quickly moves to key technical and

architectural issues for .NET developers.

private void MainForm_Paint(object sender, PaintEventArgs e)

{

Table of Contents Graphics g = e.Graphics;

g.DrawString("Please click on me...",

C# and the .NET Platform, Second Edition

new Font("Times New Roman", (float)currFontSize),

Introduction

new SolidBrush(Color.Black),

Part One - Introducing C# and the .NET Platform

this.DisplayRectangle);

Chapter 1 - The Philosophy of .NET

}

Chapter}2 - Building C# Applications

Part Two - The C# Programming Language

}

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

ChapterNotice 5that-asExceptionsyou add andthe subitemsObject Lifetimeto the ContextMenu, you have assigned the same event handler to CheachpterMenuItem6 - Interfactype.sWhenand Collectioa givensitem is clicked, the flow of logic brings us to the PopUp_Clicked()

method. Using the "sender" argument, you are able to determine the textual name of the MenuItem and

Chapter 7 - Callback Interfaces, Delegates, and Events

take an appropriate course of action (which works just fine, assuming you are not interested in localizing

Chapter 8 - Advanced C# Type Construction Techniques

the application).

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Also notice that once you have created a ContextMenu, you associate it to the Form using the

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Control.ContextMenu property. Be aware that any control can be assigned a context menu. For example,

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

you could create a Button object on a dialog box that responds to a particular context menu. In this way,

Part Four - Leveraging the .NET Libraries

the menu would only be displayed if the mouse button were clicked while within the bounding rectangle of

Chapter 12 - Object Serialization and the .NET Remoting Layer the button.

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

Adorning YourC# andMenuthe .NETSystemPlatfor , Second Edition

by Andrew Troelsen

ISBN:1590590554

The MenuItem class also defines a number of members that allow you to check, enable, and hide a given

Apress © 2003 (1200 pages)

menu item. Table 13-20 gives a rundown of some of the interesting properties of MenuItem.

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.

Table 13-20: More Details of the MenuItem Type

 

 

 

 

 

 

 

 

 

 

 

MenuItem

 

 

 

Meaning in Life

 

TableMemberof Contents

 

 

 

 

 

 

 

 

 

 

 

C# and the .NET Platform,

 

Second Edition

 

 

 

Checked

 

 

 

Gets or sets a value indicating whether a check mark appears beside the

 

Introduction

 

 

 

text of the menu item

 

 

 

 

 

 

 

 

 

Part One - Introducing

 

 

C# and the .NET Platform

 

 

 

 

ChapterDefaultItem1 - The PhilosophyGetsofor.NETsets a value indicating whether the menu item is the default

 

 

 

 

 

 

 

 

 

 

Chapter 2

- Building C# Applications

 

 

 

Enabled

 

 

 

 

Gets or sets a value indicating whether the menu item is enabled

 

Part Two - The C# Programming Language

 

 

ChaptIndexr 3

- C# LanguageGetsFundamentalsor sets the menu item's position in its parent menu

 

 

 

 

 

 

 

 

 

 

Chapter 4

- Object-Oriented Programming with C#

 

 

 

MergeOrder

 

 

 

Gets or sets the relative position of the menu item when its menu is merged

 

 

 

Chapter 5

- Exceptions and Object Lifetime

 

 

 

 

 

 

 

 

with another

 

 

 

Chapter 6

- Interfaces

 

 

 

and Collections

 

 

 

 

 

 

 

 

ChapterMergeType7 - Callback

 

 

 

Interfaces,Gets or setsDelegates,a valueandthatEventsindicates the behavior of this menu item when its

 

 

 

Chapter 8

- Advanced

 

 

 

menu is merged with another

 

 

 

 

 

 

C# Type Construction Techniques

 

 

 

 

 

 

 

Part Three - Programming

 

 

 

with .NET Assemblies

 

 

 

OwnerDraw

 

 

 

Gets or sets a value indicating whether code that you provide draws the

 

Chapter 9

- Understanding .NET Assemblies

 

 

 

 

 

 

 

 

menu item or Windows draws the menu item

 

 

 

Chapter 10

- Processes,

 

 

 

AppDomains, Contexts, and Threads

 

 

 

 

 

 

 

 

RadioCheck

 

 

 

Gets or sets a value that indicates whether the menu item, if checked,

 

 

 

Chapter 11

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

 

 

 

 

 

 

 

 

displays a radio-button mark instead of a check mark

 

Part Four - Leveraging

 

the .NET Libraries

 

 

 

 

 

 

 

 

 

 

 

 

Chapter 12

- Object

 

Serialization and the .NET Remoting Layer

 

 

 

Shortcut

 

 

 

 

Gets or sets the shortcut key associated with the menu item

 

 

 

 

 

 

 

 

 

 

 

 

Chapter 13

- Building a

 

 

 

Better Window (Introducing Windows Forms)

 

 

 

ShowShortcut

 

 

 

Gets or sets a value that indicates whether the shortcut key that is

 

 

 

Chapter 14

- A Better

 

 

 

Painting Framework (GDI+)

 

 

 

 

 

 

 

 

associated with the menu item is displayed next to the menu item caption

 

 

 

Chapter 15

- Programming

 

with Windows Forms Controls

 

 

 

 

 

 

 

Text

- The System

 

 

 

Gets or sets the text of the menu item

 

 

 

Chapter 16

 

 

 

.IO Namespace

 

 

 

 

 

 

 

 

 

 

Chapter 17 - Data Access with ADO.NET

PartTo illustrateFive - WebfurtherApplicationsuse of theandMenuItemXML Web Servictype, let's extend the previous pop-up menu to display a check

Chaptermark next18 -toASPthe.NETcurrentlyWeb PagselectedandmenuW b Controlsitem. Setting a check mark on a given menu item is not at all Chapterdifficult19(just- ASPset.theNETCheckedW b Applicationsproperty to true). However, tracking which menu item should be checked

does require some additional logic. One possible approach is to define distinct MenuItem objects that map

Chapter 20 - XML Web Services

to each possible submenu item and an additional MenuItem that represents the currently selected item:

Index

List of Figures

Listpublicof Tablesclass MainForm : Form

{

...

// Used to keep track of the current checked item.

private MenuItem currentCheckedItem;

// Marks the item checked.

private MenuItem checkedHuge;

private MenuItem checkedNormal;

private MenuItem checkedTiny;

...

}

The next step is to associate each of these MenuItems to the correct submenu. Thus, you would update

the constructor as follows:

// Construct the form.

currentCheckedItem = checkedNormal;
currFontSize = TheFontSize. FontSizeNormal;

public MainForm()

{

 

C# and the .NET Platform, Second Edition

 

...

by Andrew Troelsen

ISBN:1590590554

 

 

 

 

Apress © 2003 (1200 pages)

// Set each MenuItem to the correct submenu.

This comprehensiveContextMenutext s arts with a brief overview of the checkedHuge = this. .MenuItems[0];

C# language and then quickly moves to key technical and checkedNormal = this.ContextMenu.MenuItems[1];

architectural issues for .NET developers. checkedTiny = this.ContextMenu.MenuItems[2];

// Now check the 'Normal' menu item.

currentCheckedItem = checkedNormal;

Table of Contents

currentCheckedItem.Checked = true;

C# and the .NET Platform, Second Edition

}

Introduction

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

At this point, you have a way to programmatically identify each subitem, as well as the currently checked PartitemTwo(which- ThehasC#beenProgramminginitially setLanguageto checkedNormal). The last step is to update the PopUp_Clicked() event Chandlerpter 3to-checkC# Languagethe correctFundamentalsMenuItem in response to the user selection (see Figure 13-17 for a test run):

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

private void PopUp_Clicked(object sender, EventArgs e)

Chapter 6 - Interfaces and Collections

{

Chapter 7 - Callback Intheerfaces, Delegates,checkedand Ev nts

// Uncheck currently item.

Chapter currentCheckedItem8 - Advanced C# Type Constru.Checkedtion Techniques= false;

Part...Three - Programming with .NET Assemblies

Chapter //9 -BasedUnd rstaondingselection,.NET Assembliesestablish the current checked menu item.

Chapter if(item10 - Processes,== "Huge")AppDomains, Contexts, and Threads

{

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

currFontSize = TheFontSize.FontSizeHuge;

Part Four - Leveraging the .NET Libraries

currentCheckedItem = checkedHuge;

Chapter 12 - Object Serialization and the .NET Remoting Layer

}

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

if(item == "Normal")

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

if(item == "Tiny")

Chapter 18 - ASP.NET Web Pages and Web Controls

{

Chapter 19 - ASP.NET Web Applications

currFontSize = TheFontSize. FontSizeTiny;

Chapter 20 - XML Web Services

currentCheckedItem = checkedTiny;

Index }

List of Figures

// Now check it.

List of Tables true currentCheckedItem.Checked = ;

Invalidate();

}

Figure 13-17: Check-marking a menu item

C# and the .NET Platform, Second Edition

SOURCE The PopUpMenu project is contained under the Chapter 13 subdirectory.

CODE by Andrew Troelsen ISBN:1590590554

Apress © 2003 (1200 pages)

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.

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

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

Building a MenuC# a d theUsing.NET Platform,VisualSecondStudioEdition.NET

by Andrew Troelsen

ISBN:1590590554

Indeed, knowledge is power. On the other hand, now that you understand how you can write raw C# code

Apress © 2003 (1200 pages)

to create and configure a menu system, let's examine how Visual Studio .NET can offer some design-time

This comprehensive text starts with a brief overview of the

assistance. To begin,C# languageassumeandthatthenyouquicklyhave createdmoves atonewkey C#technicalWindowsand Application project workspace.

architectural issues for .NET developers.

Using the Toolbox window, double-click the MainMenu icon. Once you do, you see a new icon appear at the icon tray of the design-time template. Furthermore, you see a design-time representation of your menu

Tableattachedof Contentsto the top of your Form. To add new menu items, simply double-click a slot and type away!

C#Considerand theFigure.NET Platform,13-18. Second Edition

Introduction

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part

Chapter

 

Chapter

 

Chapter

Programming

Part

 

Chapter

 

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

Figure 13-18: The integrated menu editor of VS .NET

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

As far as handling events for a given item (as well as configuring a number of other properties), select the

Chapter 16 - The System.IO Namespace

MenuItem you wish to configure using the VS .NET Properties window (Figure 13-19).

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter

Chapter

Chapter

Index

List of

List of

Figure 13-19: Handing menu-centric events using VS .NET

Once you enter the name of our event handler, the Visual Studio .NET IDE automatically generates stub code for the event handler:

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

{

// Respond to File | Exit selection...

}

C# and the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Be aware, that asApressyou modify© 2003 your(1200 menuspages) at design time, the IDE is updating the InitializeComponent() helper function, asThiswellcompreheas addingsivemembertext startsvariableswith a tobriefrepresentoverviewtheoftypesthe you are manipulating at design time. If you examineC# languagethe code,andthingsthen(Iquicklyhope) lookm vesveryto familiarkey technical. and

architectural issues for .NET developers.

Note VS .NET also supports design-time configuration of pop-up menus. Simply drag a ContextMenu item onto your Form and edit the selections using the menu editor. Once this has been done,

Table of Contents

assign this object to the ContextMenu property of the widget you wish to leverage this pop-up.

C# and the .NET Platform, Second Edition

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

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

UnderstandingC# andStatusthe .NET PlBarstform, Second Edition

by Andrew Troelsen

ISBN:1590590554

In addition to a menu system, many Forms also maintain a status bar. Status bars may be divided into any

Apress © 2003 (1200 pages)

number of "panes." Panes hold some textual (or graphical) information such as menu help strings, or

This comprehensive text starts with a brief overview of the other application-C#specificlanguageinformationand then. ThequicklyStatusBarmoves totypekeyderivestechnicaldirectlyand from

System.Windowsarchitectural.Forms.Controlissues. In foraddition.NET developersto the inherited. members, StatusBar defines the core

properties shown in Table 13-21.

Table of Contents

 

 

 

 

 

 

Table 13-21: Select StatusBar Properties

C# and the .NET Platform,

 

Second Edition

 

 

IntroductionStatusBar

 

Meaning in Life

 

 

PartPropertyOne - Introducing C#

and the .NET Platform

 

 

 

 

 

 

 

 

 

 

 

 

Chapter

1

- The Philosophy

 

of .NET

 

 

 

 

 

BackgroundImage

 

Gets or sets the image rendered on the background of the StatusBar

 

 

 

Chapter

2

- Building C#

 

Applications

 

 

 

 

 

 

 

 

 

control

 

 

Part Two - The C# Programming Language

 

 

 

 

ChapterFont

3

- C# Language

 

FundamentalsGets or sets the font the StatusBar control will use to display information

 

 

 

 

 

 

 

 

Chapter

4

- Object-Oriented

 

Programming with C#

 

 

 

 

 

ForeColor

 

Gets or sets the foreground color of the control

 

 

 

 

 

Chapter

5

- Exceptions and

Object Lifetime

 

 

 

 

 

 

 

 

 

Panels

- Interfaces and

Returns a nested StatusBarPanelCollection type that contains each

 

 

 

Chapter

6

Collections

 

 

 

 

 

 

 

 

 

Panel maintained by the StatusBar (much like the menu pattern)

 

 

 

Chapter

7

- Callback Interfaces, Delegates, and Events

 

 

 

 

 

 

 

 

 

Chapter

8

- Advanced C#

 

Type Construction Tech iques

 

 

 

 

 

ShowPanels

 

Gets or sets a value indicating whether panels should be shown

 

 

 

 

 

 

 

 

Part Three - Programming

 

with .NET Assemblies

 

 

 

 

 

SizingGrip

 

Gets or sets a value indicating whether a sizing grip will be rendered on

 

 

Chapter

9

- Understanding

 

.NET Assemblies

 

 

 

 

 

 

 

 

 

the corner of the StatusBar control

 

 

 

 

Chapter

10

- Processes,

 

AppDomains, Contexts, and Threads

 

 

Chapter

11

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

Part Four - Leveraging the .NET Libraries

Once you create a StatusBar, your next task is to add any number of panels (represented by the

Chapter 12 - Object Serialization and the .NET Remoting Layer

StatusBarPanel class) into the nested StatusBar$StatusBarPanelCollection. Be aware that the constructor

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

of StatusBarPanel automatically configures the new panel with a default look and feel (therefore, if you

Chapter 14 - A Better Painting Framework (GDI+)

are happy with this initial configuration, your programming task is made even simpler). Table 13-22 lists of

Chapterthe core15members- Programmingof the StatusBarPanelwith Windows FormstypeControls.

Chapter 16 - The System.IO Namespace

ChTablept r 137-22:- DataPropertiesAccess withof theADOStatusBarPanel.NET Type

Part Five - Web Applications and XML Web Services

StatusBarPanel

Meaning in Life

Chapter 18 - ASP.NET Web Pages and Web Controls

Property

Chapter 19 - ASP.NET Web Applications

ChapterAlignment20 - XML Web ServicesDetermines the alignment of text in the pane.

Index

 

The default value is HorizontalAlignment.Left.

 

 

 

List of Figures

 

 

 

 

ListAutoSizeof Tables

 

Determines if this pane should automatically resize (and how). Default

 

 

 

value is StatusBarPanelAutoSize.None.

 

 

 

 

 

BorderStyle

 

Configures border style. Default value is

 

 

 

StatusBarPanelBorderStyle.Sunken.

 

 

 

 

 

Icon

 

Is there an icon in the pane? A null reference is the default (e.g., no

 

 

 

icon).

 

 

 

 

 

MinWidth

 

Default is 10.

 

 

 

 

 

Style

 

What does this pane contain? Default is StatusBarPanelStyle.Text, but

 

 

 

there may be other types as specified by the StatusBarPanelStyle

 

 

 

enumeration.

 

 

 

 

 

Text

 

Caption of pane. The default is an empty string.

 

 

 

 

 

ToolTipText

 

Any tool-tip? An empty string is the default.

 

 

 

 

 

 

 

 

Width

C# and theDefault.NET Platform,is 100.

Second Edition

 

 

 

 

 

 

 

 

 

 

by Andrew Troelsen

ISBN:1590590554

Apress © 2003 (1200 pages)

Building a StatusThis comprehensiveBar text starts with a brief overview of the

C# language and then quickly moves to key technical and

architectural issues for .NET developers.

To illustrate, let's construct a StatusBar object that is divided into two panes. The first pane is used to show helpful prompts describing the functionality of each menu selection. The second pane displays the current

system time. And let's place a small icon on the far left side of the first pane (just to keep things

Table of Contents

interesting). Check out Figure 13-20.

C# and the .NET Platform, Second Edition

Introduction

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter 6 - Interfaces and Collections

Figure 13-20: A custom status bar

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Assume you have updated the SimpleMenu application created earlier in this chapter, to support this

Part Three - Programming with .NET Assemblies

status bar. Like any Control-derived type, the StatusBar needs to be added to the Form's Controls

Chapter 9 - Understanding .NET Assemblies

collection (more details on this collection in Chapter 15). As you might guess, this collection contains an

Chapter 10 - Processes, AppDomains, Contexts, and Threads

entry for any GUI widget mounted on the client area, including StatusBars types. Here is the status bar

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

Part Four - Leveraging the .NET Libraries

Chapter 12

- Object Serialization and the .NET Remoting Layer

Chapterpublic13class- BuildingMainForma Better Window: Form(Introducing Windows Forms)

Chapter{

14

- A Better Painting Framework (GDI+)

Chapter //15

-MemberProgrammingdatawithforWindowsthe statusForms Controlsbar, and each pane.

 

private StatusBar statusBar = new StatusBar();

Chapter 16

- The System.IO Namespace

 

 

private StatusBarPanel sbPnlPrompt = new StatusBarPanel();

Chapter 17

- Data Access with ADO.NET

 

 

private StatusBarPanel sbPnlTime = new StatusBarPanel();

Part Five - Web Applications and XML Web Services

 

public MainForm ()

 

Chapter 18

- ASP.NET Web Pages and Web Controls

 

{

 

 

Chapter 19

- ASP.NET Web Applications

 

 

 

...

 

Chapter 20

- XML Web Services

// Helper function.

Index

}

BuildStatBar();

 

 

List of Figures

 

List of Tablesprivate void BuildStatBar()

{

// Configure the status bar.

statusBar.ShowPanels = true;

statusBar.Size = new System.Drawing.Size(212, 20);

statusBar.Location = new System.Drawing.Point(0, 216);

// AddRange() allows you to add a set of panes at once.

statusBar.Panels.AddRange(new StatusBarPanel[]

{sbPnlPrompt, sbPnlTime});

//Configure prompt panel.

sbPnlPrompt.BorderStyle = StatusBarPanelBorderStyle.None;

sbPnlPrompt.AutoSize = StatusBarPanelAutoSize.Spring;

sbPnlPrompt.Width = 62;

sbPnlPrompt.Text = "Ready";

// Configure time pane.

sbPnlTime.AutoSize = StatusBarPanelAutoSize.Spring;

sbPnlTime.Width = 120;

 

C# and the .NET Platform, Second Edition

// Add an icon.

ISBN:1590590554

 

by Andrew Troelsen

try

 

 

{

Apress © 2003 (1200 pages)

 

This comprehensive text starts with a brief overvi w of the

 

 

// This icon must be in the

same app directory.

 

C# language and then quickly moves to key technical and

 

architectural// Chapterissues for14 .NETwilldevelopers.illustrate how to embed

 

 

// resources into your assembly!

 

 

Icon i = new Icon("status.ico");

Table of Contents

 

sbPnlPrompt.Icon = i;

 

C# and the .NET}Platform, Second Edition

 

Introduction catch(Exception e)

 

Part One - Introducing{

C# and the .NET Platform

 

 

 

MessageBox.Show(e.Message);

 

Chapter 1 - The Philosophy of .NET

}

Chapter 2 - Building C# Applications

// Now add this new status bar to the Form's Controls collection.

Part Two - The C# Programming Language

this.Controls.Add(statusBar);

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

Working with the Timer Type

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Recall that the second pane should display the current time. The first step to take to achieve this design

Chapter 10 - Processes, AppDomains, Contexts, and Threads

goal is to add a Timer member variable to the Form. If you have a Visual Basic background, you should Chapterunderstand11 - thisTypeobjectReflection,quiteLatewell.Binding,Win32/C++and Attributeprogrammers-BasedalsoProgrammingunderstand the notion of timers given the

PartWMFour_TIMER- Leveragingmessagethe. Regardless.NET Librariesof your background, a Windows Forms Timer object is simply a type

Chapterthat calls12some- ObjectmethodSerialization(specifiedandbythethe.NETTickRemotingevent) atLayergiven interval (specified by the Interval property).

ChTablept r1313-23- Buildinglists somea BettercoreWindowmembers(Introducing. Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

ChTablepter 1315-23:- ProgrammingThe Timer Typewith Windows Forms Controls

Chapter 16 - The System.IO Namespace

Timer Meaning in Life

Chapter 17 - Data Access with ADO.NET

Member

Part Five - Web Applications and XML Web Services

ChapterEnabled18 - ASP.NETThisWebpropertyPages enablesd W b orControlsdisables the Timer's ability to fire the Tick event. You Chapter 19 - ASP.NETmayWebalsoApplicationsuse Start() and Stop() to achieve the same effect.

Chapter 20 - XML Web Services

Interval

Sets the number of milliseconds between ticks.

Index

Start()

List of Figures

List of Tables

Stop()

OnTick()

Tick

Like the Enabled property, these methods control the

firing of the Tick event.

This member may be overridden in a custom class deriving from Timer.

The Tick event adds a new event handler to the underlying MulticastDelegate.

Thus, you can update our class as follows:

public class MainForm : Form

{

...

private Timer timer1 = new Timer();

public MainForm ()

{

// Configure the timer.

timer1.Interval = 1000;

Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 12 - Object Serialization and the .NET Remoting Layer
Part Four - Leveraging the .NET Libraries

timer1.Enabled = true;

C# and the .NET Platform, Second Edition timer1.Tick += new EventHandler(timer1_Tick);

by Andrew Troelsen

ISBN:1590590554

...

 

}Apress © 2003 (1200 pages)

This comprehensive text starts with a brief overview of thesecond

// This method will be called (roughly) every .

C# language and then quickly moves to key technical and private void timer1_Tick(object sender, EventArgs e)

architectural issues for .NET developers.

{

DateTime t = DateTime.Now;

string s = t.ToLongTimeString();

Table of Contents

// Change text of pane to current time.

C# and the .NET Platform, Second Edition sbPnlTime.Text = s;

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

ChapterNotice 3that-theC# TimerLanguageeventFundamentalshandler makes use of the DateTime type. Here, you simply find the current

Chaptersystem4time- Objectusing-theOrientedNow pProperty,grammiandg withuse itC#to set the Text property of the correct StatusBarPanel

Chapterobject.5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

ChapterDisplaying7 - CallbackMenuInterfaces,SelectionDelegates, andPromptsEvents

Chapter 8 - Advanced C# Type Construction Techniques

PartFinally,Threeyou- Programmingmust configurewiththe.NETfirstAssembliespane to hold menu help strings. As you know, most applications send

Chaptera small9bit-ofUnderstandingtext information.NETtoAssembliesthe first pane of a status bar whenever the end user selects a menu item

Chapter(e.g., "This10 -terminatesProcesses, AppDomains,the application")Contexts,. and Threads

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

Assume the menu system for this application is identical to the Simple Menu application. This time, however, you need to respond to the Select event of each subitem. When the user selects "File | Exit" or "Help | About" you tell the first StatusBarPanel object to display a given text message. Note, you also

handle the MenuComplete event (described in the bold code comment below). Here is the update:

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

public class MainForm: Form

Chapter 16 - The System.IO Namespace

{

Chapter 17 - Data Access with ADO.NET

...

Part Five - Web Applications and XML Web Services

public MainForm ()

Chapter 18 - ASP.NET Web Pages and Web Controls

{

Chapter 19 - ASP.NET Web Applications

 

 

...

 

 

Chapter 20 - XML Web Services

 

 

//

The MenuComplete event is sent when the user clicks off

Index

//

the menu. We want to capture this event in order to

List of Figures

//

set the text of the first pane to "Ready". If we did not,

List of Tables

//

the StatusBarPanel text would always be based on the last menu

 

//

selected!

 

 

this.MenuComplete += new EventHandler(StatusForm_MenuDone);

}

BuildMenuSystem();

 

 

void FileExit_Selected(object sender, EventArgs e)

private

{ sbPnlPrompt.Text = "Terminates this app"; }

private

void HelpAbout_Selected(object sender, EventArgs e)

{ sbPnlPrompt.Text = "Displays app info"; }

private

void StatusForm_MenuDone(object sender, EventArgs e)

{

sbPnlPrompt.Text = "Ready";

// See big comment in ctor...

}

 

 

 

// Helper functions.

private void BuildMenuSystem()

{

// First make the main menu.

C# and the .NET Platform, Second Edition mainMenu = new MainMenu();

by Andrew Troelsen

ISBN:1590590554

// Create the 'File' Menu.

 

Apress © 2003 (1200 pages)

MenuItem miFile = mainMenu.MenuItems.Add("&File");

This comprehensive text starts with a brief overview of the miFile.MenuItems.Add(new MenuItem("E&xit",

C# language and then quickly moves to key technical and

new EventHandler(this.FileExit_Clicked), architectural issues for .NET developers.

Shortcut.CtrlX));

// Handle the Select event for the Exit menu item.

miFile.MenuItems[0].Select += new EventHandler(FileExit_Selected);

Table of Contents

// Now create a 'Help | About' menu.

C# and the .NET Platform, Second Edition

MenuItem miHelp = mainMenu.MenuItems.Add("Help");

Introduction

miHelp.MenuItems.Add(new MenuItem("&About",

Part One - Introducing C# and the .NET Platform

new EventHandler(this.HelpAbout_Clicked),

Chapter 1 - The Philosophy of .NET

Shortcut.CtrlA));

Chapter 2 - Building C# Applications

// Handle the Select event for the About menu item.

Part Two - The C# Programming Language

miHelp.MenuItems[0].Select +=

Chapter 3 - C# Language Fundamentals

new EventHandler(HelpAbout_Selected);

Chapter 4 - Object-Oriented Programming with C#

// Attach main menu to the Form object.

Chapter 5 - Exceptions and Object Lifetime

this.Menu = mainMenu;

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

Excellent! As you may guess, the Visual Studio IDE also provides some design-time assistance to facilitate

Chapter 10 - Processes, AppDomains, Contexts, and Threads

the building of status bar objects. In just a bit, you examine how to build a toolbar using tools provided by

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

the IDE. Once you understand this process, you should have no problems designing status bars using the

Part Four - Leveraging the .NET Libraries

design-time tools.

Chapter 12 - Object Serialization and the .NET Remoting Layer

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

SOURCE The StatusBarApp project is included under the Chapter 13 subdirectory.

Chapter 14 - A Better Painting Framework (GDI+)

CODE

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

ImageIndex
Style
Text
ToolTipText
Visible
List of Tables
List of Figures
Index

Building a ToolC# andBarthe .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

The final Form level GUI item to examine in this chapter is the ToolBar type. As you know, tool bars typically

Apress © 2003 (1200 pages)

provide an alternate means to activate a given menu item. Thus, if the user would rather click a Save button,

This comprehensive text starts with a brief overview of the

this has the sameC#effectlanguageas selectingand then"Filequickly| Savemoves." In tothekeyWindowstechnicalFormsand namespace, a handful of types are defined to allow youarchitecturalto build suchissuesa beastfor .NET. Let'sdevelopersstart with. the ToolBar class itself. Note the core properties as seen in Table 13-24.

Table of Contents

 

 

 

 

 

 

Table 13-24: Properties of the ToolBar Type

C# and the .NET Platform,

 

 

Second Edition

 

 

 

 

IntroductionToolBar

 

 

Meaning in Life

 

 

PartPropertyOne - Introducing

 

C# and the .NET Platform

 

 

 

 

 

 

 

 

 

Chapter 1 - The Philosophy of .NET

 

 

 

 

BorderStyle

 

 

The kind of border around this control, as specified by the BorderStyle

 

 

 

Chapter 2

- Building C# Applications

 

 

 

 

 

 

 

 

enumeration.

 

 

Part Two - The C# Programming Language

 

 

 

ChapterButtons3

- C# LanguageTheFundamentalscollection of buttons belonging to the toolbar (e.g.,

 

 

 

 

 

 

 

 

ToolBar$ToolBarButtonCollection).

 

 

 

Chapter 4 - Object-Oriented Programming with C#

 

 

 

 

 

 

 

 

 

Chapter 5 - Exceptions

 

 

and Object Lifetime

 

 

 

 

ButtonSize

 

 

Determines the size of a button in the ToolBar.

 

 

 

 

Chapter 6 - Interfaces

 

 

and Collections

 

 

 

 

 

 

 

 

 

 

ImageList

 

 

Returns the ImageList control that maintains the images for this ToolBar.

 

 

 

Chapter 7 - Callback

 

 

Interfaces, Delegates, and Events

 

 

 

 

 

 

 

 

Chapter 8

- Advanced

 

 

C# Type Construction Techniqu s

 

 

 

 

ImageSize

 

 

The method to return the size of the images within the toolbar's image list.

 

 

 

 

 

 

 

 

 

Part Three - Programming

 

 

with .NET Assemblies

 

 

 

 

ShowToolTips

 

 

Indicates whether or not the ToolBar will show tool tips for each button.

 

 

 

Chapter 9 - Understanding

.NET Assemblies

 

 

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Wrappable ToolBar buttons can optionally "wrap" to the next line when the ToolBar

Chapter 11 - Type Reflection,becomesLate Binditoo narrowg, andtoAttribincludete-Basedall buttonsProgrammingon the same line.

Part Four - Leveraging the .NET Libraries

ChapterWhen a12Form- ObjectmaintainsSerializationToolBarand the(or .two),NET Remotingthe goal isLayerto create some number of individual ToolBarButton

Chapterobjects13and- Buildingadd thema Betterto the WindowToolBar(Intr$ToolBarButtoducing WindowsCollectionForms)type. Each button may contain text, images,

Chapteror both14. To- keepA BetterthingsPaintingsimple,Frameworklet's build(GDI+)a toolbar containing two buttons displaying text prompts only. Table

Chapter13-25 presents15 - Prograsomemingimportantwith WindowsmembersFormsof theControlsToolBarButton.

Chapter 16 - The System.IO Namespace

Table 13-25: Properties of the ToolBarButton Type

Ch pter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

ToolBarButton

Meaning in Life

Chapter 18 - ASP.NET Web Pages and Web Controls

Property

Chapter 19 - ASP.NET Web Applications

ChapterDropDownMenu20 - XML Web ServicesToolBarButtons can optionally specify a pop-up menu that is shown whenever the drop-down button is pressed. This property lets you control just which menu is shown. Note that this is only shown if the Style property is set to DropDownButton.

Returns the index of the image that this ToolBarButton is using. The index comes from the parent ToolBar's ImageList.

Returns the style of the ToolBar button. This will form the

ToolBarButtonStyle enumeration.

The caption that will be displayed in this ToolBar button.

If the parent ToolBar has the ShowToolTips property turned on, then this property describes the text that will be displayed for this button.

Indicates whether the button is visible or not. If the button is not visible, it will not be shown and will be unable to receive user input.

Your custom toolbar will contain two buttons, echoing the behavior supplied by the Save and Exit menu items. Here is the code update:

public class MainForm: Form

C# and the .NET Platform, Second Edition

{

by Andrew Troelsen

ISBN:1590590554

// State data for the toolbar and two buttons.

Apress © 2003 (1200 pages)

private ToolBarButton tbSaveButton = new ToolBarButton();

This comprehensive text starts with a brief overview of the

private ToolBarButton tbExitButton = new ToolBarButton();

C# language and then quickly moves to key technical and

private ToolBar toolBar = new ToolBar(); architectural issues for .NET developers.

public MainForm()

{

...

Table of Contents

BuildToolBar(); // Helper function.

C# and the .NET Platform, Second Edition

}

Introduction

private void BuildToolBar()

Part One - Introducing C# and the .NET Platform

{

Chapter 1 - The Philosophy of .NET

// Configure each button.

Chapter 2 - Building C# Applications

tbSaveButton.Text = "Save";

Part Two - The C# Programming Language

tbSaveButton.ToolTipText = "Save";

Chapter 3 - C# Language Fundamentals tbExitButton.Text = "Exit";

Chapter 4 - Object-Oriented Programming with C# tbExitButton.ToolTipText = "Exit";

Chapter 5 - Exceptions and Object Lifetime

// Configure ToolBar and add buttons.

Chapter 6 - Interfaces and Collections

toolBar.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;

Chapter 7 - Callback Interfaces, Delegates, and Events

toolBar.ShowToolTips = true;

Chapter 8 - Advanced C# Type Construction Techniques

toolBar.Buttons.AddRange(new ToolBarButton[]

Part Three - Programming with .NET Assemblies

{ tbSaveButton, tbExitButton} );

Chapter 9 - Understanding .NET Assemblies

toolBar.ButtonClick += new

Chapter 10 - Processes,ToolBarButtonClickEventHandler(ToolBarAppDomains, Contexts, Thre ds _Clicked));

Chapter 11 - Type// Reflection,Add theLatenewBinding,bar toandtheAttributeControls-Based Programmingcollection.

Part Four - Leveragingthis.Controlsthe .NET Libraries.Add(toolBar);

Chapter }12 - Object Serialization and the .NET Remoting Layer

Chapter //13 -ButtonBuilding aclickBetter Windowhandler(Introducing. Windows Forms)

private void ToolBar_Clicked(object sender, ToolBarButtonClickEventArgs e)

Chapter 14 - A B tter Painting Framework (GDI+)

{

Chapter 15 - Programming with Windows Forms Controls

MessageBox.Show(e.Button.ToolTipText);

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

When you run the application, things will look quite bland (after all, how many toolbars display only text)? You

Index

will add some images in just a moment, but first let's analyze some code. The BuildToolBar() helper function

List of Figures

begins by configuring some basic properties for each ToolBarButton. Next, add them to the ToolBar Listcollectionof Tablesusing the AddRange() method (rather than calling Add() multiple times). To handle the Click events for a given button, you must handle the ButtonClick event.

toolBar.ButtonClick += new ToolBarButtonClickEventHandler(ToolBar_Clicked);

The ToolBarButtonClickEventHandler delegate can only call methods taking a second parameter of type ToolBarButtonClickEventArgs. This type may be examined to determine which button sent the event, using the Button property:

private void ToolBar_Clicked(object sender, ToolBarButtonClickEventArgs e)

{

// Just show the corresponding tool bar text.

MessageBox.Show(e.Button.ToolTipText);

}

C# and the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Adding Images to Your Toolbar Buttons

 

Apress © 2003 (1200 pages)

 

This comprehensive text starts with a brief overview of the

Real Toolbar buttons contain images. When you wish to configure your buttons to do so, the first step is to

C# language and then quickly moves to key technical and

have the Form create an ImageList type. This class represents a set of images that are consumed by some architectural issues for .NET developers.

other type (like a ToolBar). If you have ever created a toolbar using Visual Basic 6.0, you should feel right at home with this aspect of Windows Forms. Let's update your existing ToolBarForm to make use of two icons

for display purposes, in addition to simple text strings. Here is the relevant update:

Table of Contents

C# and the .NET Platform, Second Edition

public class MainForm: Form

Introduction

{

Part One - Introducing C# and the .NET Platform

// Contains the images used by the toolbar.

Chapter 1 - The Philosophy of .NET

private ImageList toolBarIcons = new ImageList();

Chapter 2 - Building C# Applications

...

Part Two - The C# Programming Language

private void BuildToolBar()

Chapter 3 - C# Language Fundamentals

{

Chapter 4 - Object-Oriented Programming with C#

// Configure save button.

Chapter 5 - Exceptions and Object Lifetime tbSaveButton.ImageIndex = 0;

Chapter 6 - Interfaces and Collections tbSaveButton.ToolTipText = "Save";

Chapter 7 - Callback Interfaces, Delegates, and Events

// Configure exit button.

Chapter 8 - Advanced C# Type Construction Techniques tbExitButton.ImageIndex = 1;

Part Three - Programming with .NET Assemblies

tbExitButton.ToolTipText = "Exit";

Chapter 9 - Understanding .NET Assemblies

// Create ToolBar and add buttons.

Chapter 10 - Processes, AppDomains, Contexts, and Threads

toolBar.ImageList = toolBarIcons;

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

...

Part Four - Leveraging the .NET Libraries

// Load images (again, the icons need to be in the app dir).

Chapter 12 - Object Serialization and the .NET Remoting Layer

toolBarIcons.ImageSize = new System.Drawing.Size(32, 32);

Chapter 13 - BuildingtoolBarIconsBetter Window.Images(Introducing.Add(newWindowsIcon("filesaveForms) .ico"));

Chapter 14 - A toolBarIconsBetter Painting Framework.Images(GDI+).Add(new Icon("fileexit.ico"));

Chapter 15 - ProgrammingtoolBarIconswith Windows.ColorDepthForms Contr= ColorDepthls .Depth16Bit;

toolBarIcons.TransparentColor = System.Drawing.Color.Transparent;

Chapter 16 - The System. O 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

Notice the following points:

Index

ListofYouFiguresmust tell each ToolBarButton which image to use, via the ImageIndex property.

List of Tables

You add new images to the ImageList class using the Images.Add() method.

The ToolBar itself must be told which ImageList it is associated with using the ImageList property.

If you now run the application (Figure 13-21), you will see a much more pleasing end result (if you wish these buttons to look more standard, simply adjust the size to 16 × 16):

Edition

ISBN:1590590554

a brief overview of the

to key technical and

developers.

Table

Figure 13-21: A custom tool bar

C# and the .NET Platform, Second Edition

Introduction

 

Part One - Introducing C# and the .NET Platform

SOURCE

The SimpleToolBar project is included under the Chapter 13 subdirectory.

Chapter 1 - The Philosophy of .NET

CODE

 

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

Building ToolBarsC# and theat.NETDesignPlatform,TimeSecond Edition

by Andrew Troelsen

ISBN:1590590554

As you would guess, VS .NET has design-time support for constructing toolbar entities. The first step is to

Apress © 2003 (1200 pages)

drag a ToolBar from the Toolbox window onto your design-time template. Design-time configuration of the

This comprehensive text starts with a brief overview of the

ToolBar is accomplishedC# languageusingandthethenPropertiesquickly movesWindowto. Forkey example,technical andif you wish to add buttons to the ToolBar type, doublearchitectural-click theissButtonses for property.NET developers. This opens. a dialog that allows you to add, remove, and configure the individual ToolBarButton items (Figure 13-22).

Table of Contents

C# and

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part

Chapter

Chapter Threads

ChapterFigure11 - 13Type-22:Reflection,ToolbarsLatelaBinding,VS .NETand Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

ChapterAdding13 - anBuildingImageListBetter Windowat (IntroduciDesigngTimeWindows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Notice how this same dialog also allows you to assign an iconic image to each button using the

Chapter 15 - Progra ming with Windows Forms Controls

ImageIndex property. However, this property is useless until you add an ImageList type to your current

Chapter 16 - The System.IO Namespace

project. To add an ImageList member to a Form at design time, return to the Toolbox window and double-

Chapter 17 - Data Access with ADO.NET

click the icon. At this point, you can use the Properties window to add the individual images using the

Part Five - Web Applications and XML Web Services

Images property. Once you have added each image file to the ImageList, inform the ToolBar which

Chapter 18 - ASP.NET Web Pages and Web Controls

ImageList it is to make use of using the Properties window (Figure 13-23).

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of

List of

Figure 13-23: Assigning an ImageList via VS .NET

At this point, return to the ToolBar button editor and map a given image in the ImageList to each button (Figure 13-24).

Edition

ISBN:1590590554

brief overview of the

to key technical and

.

Table

C# and

Part

Chapter

Chapter

Part

Chapter 3 - C# Language Fundamentals

Figure 13-24: Assigning images to ToolBar buttons

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Cool! Now that you understand how to make use of the Visual Studio .NET IDE to configure a ToolBar

Chapter 6 - Interfaces and Collections

type, I assume you will continue to explore similar design-time configurations. For example, using (more or

Chapter 7 - Callback Interfaces, Delegates, and Events

less) the same process, you can design a fully functional status bar with minimal coding on your part.

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 Five - Web Applications and XML Web Services
Chapter 17 - Data Access with ADO.NET
Part Two - The C# Programming Language
Chapter 2 - Building C# Applications

Building anC#MDIand theApplication.NET Platf rm, Second Edition

by Andrew Troelsen

ISBN:1590590554

To wrap up your initial look at Windows Forms, I'll close this chapter by examining how to configure a

Apress © 2003 (1200 pages)

Form to function as a parent to any number of child windows (i.e., an MDI container). MDI applications

This comprehensive text starts with a brief overview of the

allow the user to C#havelangmultipleage andwindowsthen quicklyopen movesat a singleto keytime,t chnicalwith eachnd window representing a given "document" of thearchiteapplicationtural issues. By wayforof.NETan example,develop rsVS. .NET is an MDI application in that you are able to have multiple documents open from within an instance of the application.

TableWhenofyouContentsare building MDI applications using Windows Forms, your first task is to (of course) create a C#brand-thenew.NETWindowsPlatform,ApplicationSecond Edition. The initial Form of the application typically hosts a menuing system that

allows the user to create new documents (such as File | New) as well as arrange existing open windows

Intr duction

(cascade, vertical tile, and horizontal tile).

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

The child windows are interesting in that you typically have a prototypical Form that functions as a basis for each child window. Given that Forms are class types, any private data defined in the child Form will be

unique to a given instance. For example, if you were to create an MDI word processing application, you

Chapter 3 - C# Language Fundamentals

might create a child Form that maintained a collection of Strings to represent a given line of text. If the user

Chapter 4 - Object-Oriented Programming with C#

created five new child windows, each Form would maintain its own copy of the underlying collection and

Chapter 5 - Exceptions and Object Lifetime could be treated individually.

Chapter 6 - Interfaces and Collections

ChapterAdditionally,7 - CallbackMDI applicationsInterfaces,allowDelegates,you toand"mergeEv ntsmenus." As mentioned previously, parent windows

typically have a menu system that allows the user to spawn and organize additional child windows.

Chapter 8 - Advanced C# Type Construction Techniques

However, what if the child window also maintains a menuing system? If the user maximizes a particular

Part Three - Programming with .NET Assemblies

child window, you need to merge the child's menu system within the parent Form to allow the user to

Chapter 9 - Understanding .NET Assemblies

activate items from each menu system. The Windows Forms namespace defines a number of properties,

Chapter 10 - Processes, AppDomains, Contexts, and Threads

methods, and events that allow you to programmatically merge menu systems. In addition, there is a

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

"default merge" system, which works in a good number of cases. I leave it as a task for the interested

Part Four - Leveraging the .NET Libraries

reader to investigate this aspect of MDI applications.

Chapter 12 - Object Serialization and the .NET Remoting Layer

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

ChapterBuilding14 - A theBett rParentainting FrameworkForm (GDI+)

Chapter 15 - Programming with Windows Forms Controls

To illustrate the basics of building an MDI application, begin by creating a brand-new Windows Application

Chapter 16 - The System.IO Namespace

named MDIApp. Almost all of the MDI infrastructure can be assigned to your initial Form using various design-time tools. To begin, locate the IsMdiContainer property in the Property window and set it to True. If

you look at the design-time Form, you see that the client area has been modified to visually represent a

Chapter 18 - ASP.NET Web Pages and Web Controls container of child windows.

Chapter 19 - ASP.NET Web Applications

ChapterNext up,20place- XMLaWnewb ServicesMainMenu widget on your main Form. This menu specifies three topmost MenuItems

Inameddex "File," "Window," and "Arrange Windows." The File menu contains two subitems named "New"

Listandof"ExitFigures." The Window does not contain any subitems, as you will programmatically add new items as the Listuserof createsTables additional child windows. Finally, the Arrange Window menu defines three subitems named "Cascade," "Vertical," and "Horizontal." Figure 13-25 offers a high-level design-time view.

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

ISBN:1590590554

overview of the

technical and

Table

C# and

Part

Chapter

Chapter

Part

ChapterFigure3 - 13C#-25:LanguageThe parentFundamentalswindow's menu system

Chapter 4 - Object-Oriented Programming with C#

Given that you already dove into the muck of coding raw menu logic during this chapter, simply use the

Chapter 5 - Exceptions and Object Lifetime

IDE to generate event handlers for each submenu. You'll implement the File | New handler in the next

Chapter 6 - Interfaces and Collections

section—however, here is the code behind the remaining menu selections (remember, the Window menu

Chapter 7 - Callback Interfaces, Delegates, and Events

does not have any sub-items just yet):

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

// Handle close event and arrange all child windows.

Chapter 9 - Understanding .NET Assemblies

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

Chapter 10 - Processes, AppDomains, Contexts, and Threads

{ this.Close(); }

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

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

Part Four - Leveraging the .NET Libraries

{ LayoutMdi(MdiLayout.Cascade); }

Chapter 12 - Object Serialization and the .NET Remoting Layer

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

{ LayoutMdi(MdiLayout.TileVertical); }

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

Chapter 15 - Programming with Windows Forms Controls

{ LayoutMdi(MdiLayout.TileHorizontal); }

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

PartTheFivemain- WebpointApplicationsof interest hereand XMLis theWebuseServicesof the LayoutMdi() method and the corresponding MdiLayout

Chapterenumeration18 - ASP. The.NETcodeW bbehindPages eachand WebmenuControlsselect handler should be quite clear. When the user selects a

Chaptergiven arrangement,19 - ASP.NETyouWebtellApplicationsthe parent Form to automatically reposition any and all child windows.

Chapter 20 - XML Web Services

Before you move on to the child Form, you need to add one design-time property to the topmost Window

Index

menu item. The MdiList property may be set to true for a given topmost menu, to inform the hosting Form to automatically list the name of each child window as a possible menu selection. Enable this behavior for the topmost Windows menu item. By default, this list is the value of the child's Text property followed by a numerical suffix (i.e., Form1, Form2, Form3, and so on).

Building the Child Form

Now that you have the shell of an MDI container Form, you need to create an additional Form that functions as the prototype for a given child window. Begin by inserting a new Form type into your current project (using the Project | Add Windows Form... menu selection) named KidPrototypeForm, and handle the Click event. In the generated event handler, randomly set the background color of the client area. In addition, print out the "stringified" value of the new Color object into the child's caption bar. The following logic should do the trick:

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

{

// Get three random numbers

// Set the Parent Form of the Child window.

int r, g, b;

C# and the .NET Platform, Second Edition

Random ran = new Random();

r

=

by Andrew Troelsen

ISBN:1590590554

ran.Next(0,

255);

 

g

=

Apress © 2003 (1200 pages)

 

ran.Next(0,

255);

 

This comprehensive text starts with a brief overview of the b = ran.Next(0, 255);

C# language and then quickly moves to key technical and

Color currColor = Color.FromArgb(r, g, b); architectural issues for .NET developers.

this.BackColor = currColor;

this.Text = currColor.ToString();

}

Table of Contents

C# and the .NET Platform, Second Edition

Introduction

PartSpawningOne - IntroducingChildC# andWindowsthe .NET Platform

Chapter 1 - The Philosophy of .NET

Your final order of business is to flesh out the details behind the parent Form's "File New" event handler.

Chapter 2 - Building C# Applications

Now that you have defined a child Form, the logic is simple: Create and show a new instance of the

Part Two - The C# Programming Language

ChildForm type. Furthermore, you need to set the value of the child Form's MdiParent property to point to

Chapter 3 - C# Language Fundamentals

the containing Form (in this case, your main window). Note that the child Form may also access the

Chapter 4 - Object-Oriented Programming with C#

MdiParent property directly whenever it needs to manipulate (or communicate with) its parent window.

Chapter 5 - Exceptions and Object Lifetime

Here is the update:

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

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

Chapter 8 - Advanced C# Type Construction Techniques

{

Part Three - Programming with .NET Assemblies

// Make a new child window.

Chapter 9 - Understanding .NET Assemblies

KidPrototypeForm newChild = new KidPrototypeForm();

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming newChild.MdiParent = this;

Part Four - Leveraging the .NET Libraries

// Display the new form.

Chapter 12 - Object Serialization and the .NET Remoting Layer

newChild.Show();

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

}

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Now, to take this application out for a test drive, begin by creating a set of new child windows and click on

Chapter 16 - The System.IO Namespace

each one to establish a unique background color (see Figure 13-26).

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter

Chapter

Chapter

Index

List of

List of

Figure 13-26: Spawning child windows

As you can see, if you access the Arrange Window menu items, you can instruct the parent Form to vertically tile, horizontally tile, or cascade the child Forms.

SOURCE

CODE

C# andThe theSimpleMdiApp.NET Platform,projectSecano dbeEditionfound under the Chapter 13 subdirectory.

by Andrew Troelsen

ISBN:1590590554

Apress © 2003 (1200 pages)

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.

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

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

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