- •Table of Contents
- •C# and the .NET Platform, Second Edition
- •Introduction
- •Part One: Introducing C# and the .NET Platform
- •Part Two: The C# Programming Language
- •Part Three: Programming with .NET Assemblies
- •Part Four: Leveraging the .NET Libraries
- •Part Five: Web Applications and XML Web Services
- •Obtaining This Book's Source Code
- •The .NET Solution
- •What C# Brings to the Table
- •The Role of the Assembly Manifest
- •Summary
- •Chapter 2: Building C# Applications
- •Summary
- •Chapter 3: C# Language Fundamentals
- •Defining Program Constants
- •Defining Custom Class Methods
- •C# Enumerations
- •Summary
- •The Second Pillar: C#'s Inheritance Support
- •Summary
- •Catching Exceptions
- •Finalizing a Type
- •Garbage Collection Optimizations
- •Summary
- •Chapter 6: Interfaces and Collections
- •Building Comparable Objects (IComparable)
- •Summary
- •Summary
- •Internal Representation of Type Indexers
- •Summary
- •An Overview of .NET Assemblies
- •Understanding Delayed Signing
- •Using a Shared Assembly
- •GAC Internals
- •Summary
- •Spawning Secondary Threads
- •A More Elaborate Threading Example
- •Summary
- •Summary
- •Object Persistence in the .NET Framework
- •The .NET Remoting Namespaces
- •Understanding the .NET Remoting Framework
- •All Together Now!
- •Terms of the .NET Remoting Trade
- •Testing the Remoting Application
- •Revisiting the Activation Mode of WKO Types
- •Deploying the Server to a Remote Machine
- •Summary
- •Control Events
- •The Form Class
- •Summary
- •Regarding the Disposal of System.Drawing Types
- •Understanding the Graphics Class
- •Summary
- •The TextBox Control
- •Working with Panel Controls
- •Configuring a Control's Anchoring Behavior
- •Summary
- •Chapter 16: The System.IO Namespace
- •The Static Members of the Directory Class
- •The Abstract Stream Class
- •Summary
- •The Role of ADO.NET Data Providers
- •The Types of System.Data
- •Selecting a Data Provider
- •The Types of the System.Data.OleDb Namespace
- •Working with the OleDbDataReader
- •Summary
- •Submitting the Form Data (GET and POST)
- •Some Benefits of ASP.NET
- •Creating an ASP.NET Web Application by Hand
- •The Composition of an ASP.NET Page
- •The Derivation of an ASP.NET Page
Understanding the Graphics Class |
|
C# and t .NET Platform, Second Edition |
|
by Andrew Troelsen |
ISBN:1590590554 |
Now that you have seen various ways to obtain a Graphics object, you need to understand exactly how to
Apr ss © 2003 (1200 pages)
manipulate it. The System.Drawing.Graphics object is your gateway to GDI+ rendering functionality. This
This comprehensive text starts with a brief overview of the
class represents C#a validlanguagedeviceandcontextth n quickly(e.g., HDC)movescoupledto k y technicalwith a slewandof methods that allow you to render text, imagesarchitectural(icons, bitmaps,issues forand.NETso on),developersas well. as numerous geometric patterns. Table 14-8 gives a partial list of intriguing members.
Table of Contents |
|
|
|
|
|
|
|||
|
Table 14-8: Members of the Graphics Class |
||||||||
C# and the .NET Platform, |
|
|
|
Second Edition |
|
|
|||
|
|
|
|||||||
IntroductionGraphics |
|
|
|
Meaning in Life |
|
|
|||
PartMethodsOne - Introducing C# |
|
|
|
and the .NET Platform |
|
|
|||
|
|
|
|
|
|||||
|
|
Chapter 1 - The Philosophy |
|
|
|
of .NET |
|
|
|
|
|
FromHdc() |
|
|
|
These static methods provide a way to obtain a valid Graphics object |
|
|
|
|
Chapter 2 - Building C# |
|
|
|
Applications |
|
|
||
|
|
FromHwnd() |
|
|
|
from a given image (e.g., icon, bitmap, etc.) or GUI widget. |
|
|
|
Part Two - The C# Programming Language |
|
|
|||||||
ChapterFromImage()3 - C# Language Fundamentals |
|
|
|||||||
|
|
|
|
|
|
||||
|
|
Chapter 4 |
- Object-Oriented Programming with C# |
|
|
||||
|
|
Clear() |
|
|
|
Fills a Graphics object with a specified color, erasing the current drawing |
|
|
|
|
Chapter 5 |
- Exceptions and Object Lifetime |
|
|
|||||
|
|
|
|
|
|
|
surface in the process. |
|
|
|
|
Chapter 6 |
- Interfaces and Collections |
|
|||||
|
|
DrawArc() |
|
|
|
These methods are used to render a given image or geometric pattern. |
|||
Chapter 7 |
- Callback Interfaces, Delegates, and Events |
||||||||
ChapterDrawBezier()8 - Advanced C# Type Construction Techniques |
Part Three - Programming with .NET Assemblies
DrawBeziers()
Chapter 9 - Understanding .NET Assemblies
DrawCurve()
Chapter 10 - Processes, AppDomains, Contexts, and Threads
DrawEllipse()
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
PartDrawIcon()Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
DrawLine()
Chapter 13 - Building a Better Window (Introducing Windows Forms)
DrawLines()
Chapter 14 - A Better Painting Framework (GDI+)
DrawPie()
Chapter 15 - Programming with Windows Forms Controls
ChapterDrawPath()16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
DrawRectangle()
Part Five - Web Applications and XML Web Services
DrawRectangles()
Chapter 18 - ASP.NET Web Pages and Web Controls
DrawString()
Chapter 19 - ASP.NET Web Applications
|
|
|
|
|
Chapter 20 - XML Web Services |
||
|
FillEllipse() |
|
These methods are used to fill the interior of a given geometric shape. |
Index |
|
|
|
|
FillPath() |
|
|
List of Figures |
|
|
|
|
FillPie() |
|
|
List of Tables |
|
|
|
|
FillPolygon() |
|
|
|
FillRectangle() |
|
|
|
|
|
|
|
MeasureString() |
|
Returns a Size structure that represents the bounds of a given block of |
|
|
|
text. |
As well as providing a number of rendering methods, the Graphics class defines additional members that control the details of the current rendering operation. In more concrete terms, the Graphics type allows you to configure the state of the Graphics object using the property set in Table 14-9.
Table 14-9: Stateful Properties of the Graphics Class
|
Graphics |
C# and |
theMeaning.NET Platform,in LifeSecond Edition |
|
|
Property |
by Andrew Troelsen |
ISBN:1590590554 |
|
|
|
|
|
|
|
Clip |
Apress |
© 2003 (1200 pages) |
|
|
This |
These properties allow you to set the clipping options used with the |
||
|
|
comprehensive text starts with a brief overview of the |
||
|
ClipBounds |
|
current Graphics object. |
|
|
C# language and then quickly moves to key technical and |
|||
|
|
architectural issues for .NET developers. |
|
|
|
VisibleClipBounds |
|
||
|
IsClipEmpty |
|
|
|
Table of Contents |
|
|||
|
IsVisibleClipEmpty |
|
||
|
|
|
|
|
C# and the .NET Platform, |
Second Edition |
|
||
|
Transform |
|
Allows you to transform "world coordinates" (more details later). |
|
|
Introduction |
|
|
|
|
|
|
|
PartPageUnitOne - Introducing C# andThesetheproperties.NET Platformallow you to configure the point of origin for your
Chapter 1 - The Philosophyrenderingof .NET operations, as well as configure the unit of measurement. PageScale
Chapter 2 - Building C# Applications
DpiX
Part Two - The C# Programming Language
ChapterDpiY 3 |
- C# Language Fundamentals |
||||||||
|
|
|
|
|
|
|
|
||
|
|
Chapter 4 |
- Object-Oriented Programming with C# |
|
|||||
|
|
SmoothingMode |
|
|
These properties allow you to configure the smoothness of geometric |
|
|||
|
Chapter 5 |
- Exceptions and Object Lifetime |
|
||||||
|
|
PixelOffsetMode |
|
|
objects and text. These are set with corresponding enumerations defined |
|
|||
|
Chapter 6 |
- Interfaces and Collections |
|
||||||
|
|
|
|
|
|
|
in the System.Drawing and System.Drawing.Drawing2D namespaces. |
|
|
|
ChapterTextRenderingHint7 - Callback Interfaces, Delegates, and Events |
|
|||||||
|
|
|
|
|
|
|
|
||
|
|
Chapter 8 |
- Advanced C# |
|
|
Type Construction Techniques |
|
||
|
|
CompositingMode |
|
|
The CompositingMode property determines whether drawing overwrites |
|
|||
Part Three - Programming |
|
|
with .NET Assemblies |
|
|||||
|
|
CompositingQuality |
|
|
the background or is blended with the background. The value is set with |
|
|||
Chapter 9 |
- Understanding |
|
|
.NET Assemblies |
|
||||
|
|
|
|
|
|
|
the corresponding CompositingMode enumeration defined in the |
|
|
Chapter 10 |
- Processes, |
|
|
AppDomains, Contexts, and Threads |
|
||||
|
|
|
|
|
|
|
System.Drawing.Drawing2D namespace. The CompositingQuality |
|
|
Chapter 11 |
- Type Reflection, Late Binding, and Attribute-Based Programming |
|
|||||||
|
|
|
|
|
|
|
property specifies the complexity of the blending process. |
|
|
|
|
|
|
|
|||||
Part Four - Leveraging the |
|
|
|
.NET Libraries |
|
||||
|
|
InterpolationMode |
|
|
|
Specifies how data is interpolated between endpoints, using a related |
|
||
Chapter 12 |
- Object Serialization and the .NET Remoting Layer |
|
|||||||
|
|
|
|
|
|
|
enumeration. |
|
|
|
|
Chapter 13 |
- Building a Better Window (Introducing Windows Forms) |
|
|
||||
Chapter 14 |
- A Better Painting Framework (GDI+) |
||||||||
Chapter 15 |
- Programming with Windows Forms Controls |
||||||||
|
During the course of this chapter you will check out how to configure a number of these stateful properties. |
||||||||
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 GDI+ CoordinateC# and the .NETSystemsPlatfor , Second Edition
by Andrew Troelsen |
ISBN:1590590554 |
Next up, you need a bit of background regarding the underlying coordinate system. GDI+ defines three
Apress © 2003 (1200 pages)
distinct coordinate systems (Table 14-10), which are used by the runtime to determine the location and
This comprehensive text starts with a brief overview of the size of the elementC#tolanguagebe renderedand then. quickly moves to key technical and
architectural issues for .NET developers.
Table 14-10: The GDI+ Coordinate Systems
|
|
|
|
|
TableGDI+of Contents |
|
|
Meaning in Life |
|
C#Coordinateand the .NET Platform, |
Second Edition |
|||
IntroductionSystem |
|
|
|
|
|
|
|
|
|
Part One - Introducing C# and the .NET Platform |
||||
|
World |
|
|
World coordinates represent an abstraction of the size of a given GDI+ type, |
Chapter 1 - The Philosophy of .NET |
||||
|
Coordinates |
|
|
irrespective of the unit of measurement. |
Chapter 2 - Building C# Applications
For example, if you draw a rectangle using the dimensions of (0, 0, 100,
Part Two - The C# Programming Language
100), you have specified a rectangle 100 × 100 "things" in size.
Chapter 3 - C# Language Fundamentals |
|||||||
Chapter 4 - Object-OrientedAs youProgrammingmay guess,withthe C#default thing is a pixel, but this can be configured to |
|||||||
|
|
Chapter 5 - Exceptions |
|
|
be another unit of measure (inch, centimeter, etc.). |
||
|
|
|
|
and Object Lifetime |
|||
|
|
|
|
|
|||
Chapter 6 |
- Interfaces and Collections |
||||||
|
|
Page |
|
|
|
|
Page coordinates represent an offset applied to the original world |
Chapter 7 |
- Callback Interfaces, Delegates, and Events |
||||||
|
|
Coordinates |
|
|
coordinates. This is helpful in that you are not the one in charge of manually |
||
Chapter 8 |
- Advanced C# Type C n truction Techniques |
||||||
|
|
|
|
|
|
|
applying offsets in your code (should you need them). |
Part Three - Programming with .NET Assemblies
For example, if you have a Form that needs to maintain a 100 × 100 pixel
Chapter 9 - Understanding .NET Assemblies
border, you can specify a (100 ×100) page coordinate to allow all rending to
Chapter 10 - Processes, AppDomains, Contexts, and Threads
begin at point (100 × 100). In your code base however, you are able to
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
specify simple world coordinates (thereby avoiding the need to manually
Part Four - Leveraging the .NET Libraries
calculate the offset).
|
|
|
|
|
|
|
|
Chapter 12 - Object |
Serialization and the .NET Remoting Layer |
|
|||
|
|
Device |
- Building a |
|
Device coordinates represent the result of applying page coordinates to the |
|
|
Chapter 13 |
|
Better Window (Introducing Windows Forms) |
|
||
|
|
Coordinates |
|
original world coordinates. This coordinate system is used to determine |
|
|
|
Chapter 14 |
- A Better |
Painting Framework (GDI+) |
|
||
|
|
|
|
|
exactly where the GDI+ type will be rendered on the Control-derived type. |
|
|
|
Chapter 15 |
- Programming |
with Windows Forms Controls |
|
Chapter 16 - The System.IO Namespace
When you are programming with GDI+, you tend to think in terms of "world coordinates." Simply put, this
Chapter 17 - Data Access with ADO.NET
coordinate system is the baseline used to determine the size and location of a GDI+ type:
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
// Render a rectangle by specifying world coordinates.
Chapter 19 - ASP.NET Web Applications
myGraphicsObject.DrawRectangle(10, 10, 100, 100);
Chapter 20 - XML Web Services
Index
List of Figures
List of Tables
Under the hood of GDI+, your world coordinates are automatically mapped in terms of page coordinates, and are then mapped into device coordinates. In many cases, you will never directly make use of page or device coordinates unless you wish to apply some sort of graphical transformation. Given that the previous line of code did not specify any transformational page coordinate logic, the world, page, and device coordinates are identical.
If you do wish to apply various transformations before rendering your GDI+ logic, you will make use of various members of the Graphics type (such as the TranslateTransform() method) to specify various "page coordinates" to your existing world coordinate system before the rendering operation. The result is the set of device coordinates that will be used to render the GDI+ type to the target device:
// Specify page coordinate offsets (10 * 10).
myGraphicsObject.TranslateTransform(10, 10);
//Render a rectangle by specifying world coordinates.
//However! Given the previous offset,
//this rectangle is really drawn at (20 ,20)
// and is 110 * 110 pixels in size.
C# and the .NET Platform, Second Edition myGraphicsObject.DrawRectangle(10, 10, 100, 100);
by Andrew Troelsen |
ISBN:1590590554 |
Apress © 2003 (1200 pages)
In this case, the rectangleThis comprehensiveis actuallytextrenderedstarts withitha upperbrief overviewleft pointofofthe(20, 20) and a lower right point of (110, 110). C# language and then quickly moves to key technical and
architectural issues for .NET developers.
The Default Unit of Measure
Table of Contents
As suggested in the last example, the default unit of measure is pixel-based and places the origin in the
C# and the .NET Platform, Second Edition
upper left corner with the x-axis increasing to the right and the y-axis increasing downward (Figure 14-2).
Introduction
Part One - Introducing C# and the .NET Platform
Chapter
Chapter
Part
Chapter
Chapter
Chapter
Chapter
Chapter
Chapter
Part
Chapter
Chapter Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Figure 14-2: The default coordinate system of GDI+
Part Four - Leveraging the .NET Libraries
ChapterAgain, if12you- ObjectrenderSerializationRectangleandasthefollows:.NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
private void MainForm_Paint(object sender, PaintEventArgs e)
Chapter 15 - Programming with Windows Forms Controls
{
Chapter //16 -SetThe Systemup world.IO Namespacecoordinates using the default unit of measure.
Chapter Graphics17 - Data Accessg = withe.Graphics;ADO.NET
Part Fiveg-.WebDrawRectangle(newApplic tions and XMLPen(ColorWeb Services.Red, 5), 10, 10, 100, 100);
Chapter} 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
you would see a square rendered 10 pixels down and in from the top left client edge of the Form, which
Index
spans 90 pixels in both directions (Figure 14-3). Given that you have not applied any page transformations,
the world, page, and device coordinate values are identical.
List of Tables
Figure 14-3: Rendering via pixel units
In most cases, the default measurement system will most likely be your unit of choice. However, like most things in the .NET Framework, you are able to configure the GDI+ mapping mode to your liking.
SpecifyingC#anandAlternativehe .NET Platform,UnitSecondof MeasureEdition
by Andrew Troelsen |
ISBN:1590590554 |
If you do not wish to render images using a pixel-based unit of measure, you are able to change this
Apress © 2003 (1200 pages)
default setting by setting the PageUnit property of the Graphics object to alter the units used by the page
This comprehensive text starts with a brief overview of the
coordinate systemC#. ThelanguPageUnitand thenpropertyquicklycanmovesbe assignedto key technicalany memberand of the GraphicsUnit enumeration (Table 14-11). architectural issues for .NET developers.
Table 14-11: The GraphicsUnit Enumeration
Table of Contents |
|
C#GraphicsUnitand the .NET Platform,ValueSecondDescriptionEdition |
|
Introduction |
Specifies 1/75 inch as the unit of measure |
Display |
|
Part One - Introducing C# and the .NET Platform |
ChapterDocument1 - The Philosophy of .NETSpecifies the document unit (1/300 inch) as the unit of measure
|
|
|
|
|
|
|
|
Chapter 2 - Building C# Applications |
|
||||
|
|
Inch |
|
|
Specifies the inch as the unit of measure |
|
Part Two - The C# Programming |
|
Language |
|
|||
|
|
|||||
ChapterMillimeter3 - C# Language FundamentalsSpecifies the millimeter as the unit of measure |
|
|||||
|
|
|
|
|
||
|
|
Chapter 4 - Object-Oriented |
|
Programming with C# |
|
|
|
|
Pixel |
|
|
Specifies a device pixel as the unit of measure |
|
|
|
Chapter 5 - Exceptions and Object Lifetime |
|
|||
|
|
|
||||
|
ChapterPoint 6 - Interfaces and CollectionsSpecifies a printer's point (1/72 inch) as the unit of measure |
|
||||
|
|
|
|
|
|
|
Chapter 7 - Callback Interfaces, Delegates, and Events |
||||||
Chapter 8 |
- Advanced C# Type Construction Techniques |
For example, if you update your previous rendering code as follows:
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
private void MainForm_Paint(object sender, PaintEventArgs e)
Chapter 10 - Processes, AppDomains, Contexts, and Threads
{
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
// Draw a rectangle in inches...not pixels.
Part Four - Leveraging the .NET Libraries
Graphics g = e.Graphics;
Chapter 12 - Object Serialization and the .NET Remoting Layer g.PageUnit = GraphicsUnit.Inch;
Chapter 13 - Building a Better Window (Introducing Windows Forms) g.DrawRectangle(new Pen(Color.Red, 5), 0, 0, 100, 100);
Chapter 14 - A Better Painting Framework (GDI+)
}
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Chapteryou find17a -radicallyData Accessdifferentwith rectangleADO.NET (Figure 14-4).
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter
Chapter
Index
List of
List of
Figure 14-4: Rendering via inch units
The reason that 95% (or so) of the Form's client area is now filled in is due to the fact that you have configured a Pen with a five inch nib! The rectangle itself is 100 × 100 inches in size! In fact, the small gray box you see located in the lower right corner is the upper left interior of the rectangle! As you would guess, if you specify alternative values to the Graphics.PageUnit property, you would find the rectangle rendered in various units of measurement.
Specifying an Alternative Point of Origin |
|
C# and the .NET Platform, Second Edition |
|
by Andrew Troelsen |
ISBN:1590590554 |
Recall that when you make use of the default coordinate and measurement system, point (0, 0) is at the
extreme upper left of the client area. Again, this is typically what you desire. However, what if you wish to
This comprehensive text starts with a brief overview of the
alter the location where rendering begins? For example, let's assume that your application always needs
to reserve a 100-pixel boundary around the Form's client area (for whatever reason). You need to ensure architectural issues for .NET developers.
that all GDI+ operations take place somewhere within this internal region.
One approach you could take is to offset all your rendering code manually. This, of course, is a huge
Table of Contents
bother, in that you would need to constantly apply some offset value to each and every rendering
operation. It would be far better (and simpler) if you could set a property that says, in effect, "Although I
Introduction
might say render a rectangle with a point of origin at (0, 0), make sure you begin at point (100, 100)." This
would simplify your life a great deal, as you can continue to specify your plotting points without
Chapter 1 - The Philosophy of .NET modification.
Chapter 2 - Building C# Applications
PartIn GDI+,Two -youThecanC# Programmingadjust the pointLanguageof origin by setting the transformation value using the
ChapterTranslateTransform()3 - C# LanguagemethodFun amentalsof the Graphics class, which allows you to specify a page coordinate system
Chapterthat will4be-appliedObject-Orientedto your originalProgrammingworld coordinatewith C# specifications. For example:
Chapter 5 - Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections
private void MainForm_Paint(object sender, PaintEventArgs e)
Chapter{ 7 - Callback Interfaces, Delegates, and Events
Chapter Graphics8 - Advancedg C#= Type.Graphics;Construction Techniques
Part Three//- ProgrammingSet page coordinatewith .NET Assembliesto (100, 100).
Chapter g9.TranslateTransform(100,- Understanding .NET Assemblies 100);
// World origin is still (0, 0, 100, 100),
Chapter 10 - Processes, AppDomain , Contexts, and Threads
// however device origin is now (100, 100, 200, 200).
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
g.DrawRectangle(new Pen(Color.Red, 5), 0, 0, 100, 100);
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+)
Here, we have set our world coordinate values (0, 0, 100, 100). However, the page coordinate values have
Chapter 15 - Programming with Windows Forms Controls
specified an offset of (100, 100). Given this, the device coordinates map to (100, 100, 200, 200). Thus,
Chapter 16 - The System.IO Namespace
although the call to DrawRectangle() looks as if you are rendering a rectangle on the upper left of the
Chapter 17 - Data Access with ADO.NET
Form, the following rendering has taken place (Figure 14-5).
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter
Chapter
Index
List of
List of
Figure 14-5: The result of applying page offsets
To help you experiment with some of the ways to alter the default GDI+ mapping system, the companion code contains a sample application named CoorSystem. Using two topmost menu items, you are able to alter the point of origin as well as the unit of measurement (Figure 14-6).
C# and the .NET Platform, Second Edition
ISBN:1590590554
of the
and
Table
C# and
Part
Chapter
Chapter
Part Two - The C# Programming Language
Figure 14-6: Altering coordinate and measurement modes
Chapter 3 - C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C#
Now that you have a better understanding of the underlying transformations used to determine where to
Chapter 5 - Exceptions and Object Lifetime
render a given GDI+ type onto a target device, the next order of business is to examine details of color
Chapter 6 - Interfaces and Collections
manipulation.
Chapter 7 - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques
SOURCE The CoorSystem project is included under the Chapter 14 subdirectory.
Part Three - Programming with .NET Assemblies
CODE
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
EstablishingC#and Activethe .NET Platform,Color Second Edition
by Andrew Troelsen |
ISBN:1590590554 |
Many of the rendering methods defined by the Graphics class require you to specify the color that should
Apress © 2003 (1200 pages)
be used during the drawing process. The System.Drawing.Color structure represents an alpha-red-green-
This comprehensive text starts with a brief overview of the
blue (ARGB) colorC#constantlanguage. Mostand thenof thequicklyColormovestype'stofunctionalitykey technicalcomesand by way of a number of static read-only properties,architecturalwhich returnissuesafornew.NET(correctlydeve opersconfigured),. Color type:
// One of many predefined colors...
Table of Contents
Color c = Color.PapayaWhip;
C# and the .NET Platform, Second Edition
Introduction
PartThereOneare- Introducingother waysC#youandcanthecreate.NET aPlatformColor type. Regardless of the method you use, you are then able Chapterto extract1 relevant- The Phinformationlosophy .NETusing any of the members listed in Table 14-12 (in addition to the set of
Chstaticpterread2 -onlyBuildingproperties)C# Applications.
Part Two - The C# Programming Language
ChTablept r 143 -12:- C#MembersLanguageofFundamentalsthe Color Type
Chapter 4 - Object-Oriented Programming with C#
Color Member |
Meaning in Life |
Chapter 5 - Exceptions and Object Lifetime
ChapterFromArgb()6 - Interfaces andReturnsCollectionsa new Color object based on numerical red, green, and blue
Chapter 7 - Callback Interfvaluesces,.Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques
FromKnownColor() Returns a new Color object based on a member of the KnownColor
Part Three - Programming with .NET Assemblies
enumeration.
Chapter 9 - Understanding .NET Assemblies
ChapterFromName()10 - Processes, AppDomains,Returns newContexts,ColorandobjectThrebasedds on a string name (e.g., "Red").
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
|
|
A, R, G, B |
|
|
These properties return the value assigned to the alpha, red, green, and |
|
Part Four - Leveraging the .NET Libraries |
||||||
|
|
|
|
|
blue aspect of a Color object. |
|
|
Chapter 12 - Object Serialization and the .NET Remoting Layer |
|
||||
|
|
|
||||
|
ChapterIsNamedColor()13 - Building a BetterTheseWindowmembers(Introducingcan be Windowsapplied toForms)a Color object to determine if the |
|
||||
|
Chapter 14 - A Better PaintingcurrentFrameworkARGB values(GDI+)have a predefined name (e.g., "Red") and if so, |
|
||||
|
|
Name |
|
|
retrievewith Windowsit via theFormsNameControlsproperty. |
|
|
Chapter 15 - Programming |
|
|
|
||
|
|
|
|
|
||
|
|
Chapter 16 - The System.IO |
Namespace |
|
||
|
|
GetBrightness() |
|
|
GDI+ Color types have an associated Hue-Saturation-Brightness (HSB) |
|
|
Chapter 17 - Data Access |
with ADO.NET |
|
|||
|
|
GetHue() |
|
|
value. These methods retrieve the specifics. |
|
Part Five - Web Applications |
and XML Web Services |
|
||||
|
ChapterGetSaturation()18 - ASP.NET Web Pages and Web Controls |
|
||||
|
|
|
|
|
|
|
|
|
Chapter 19 - ASP.NET Web Applications |
|
|||
|
|
ToArgb() |
|
|
Returns the ARGB value of the Color type, or the KnownColor |
|
|
Chapter 20 - XML Web Services |
|
||||
|
|
ToKnownColor() |
|
|
enumeration value based on a valid Color object. |
|
|
Index |
|
|
|
|
|
|
|
|
|
|
||
List of Figures |
|
|
|
|
List of Tables
Examining the ColorDialog Class
On a related note, the System.Windows.Forms namespace provides a predefined dialog box class (ColorDialog) that can be used to prompt the end user for his or her color selection (Figure 14-7).
Edition
ISBN:1590590554
a brief overview of the
to key technical and
.
Table
C# and
Part One - Introducing C# and the .NET Platform
Figure 14-7: The stock .NET color dialog
Chapter 1 - The Philosophy of .NET
Chapter 2 - Building C# Applications
PartWorkingTwo -withThe thisC# Programmingdialog is simple:Languageusing a valid instance of the ColorDialog type, call ShowDialog() to
display the dialog modally. Once the user has closed the dialog, you can extract the corresponding Color
Chapter 3 - C# Language Fundamentals
object using the ColorDialog.Color property.
Chapter 4 - Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime
For example, assume you wish to allow the user to configure the background color of the Form's client
Chapter 6 - Interfaces and Collections
area using the ColorDialog. To keep things simple, let's assume that when the user clicks anywhere on
Chapter 7 - Callback Interfaces, Delegates, and Events
the client area, you show the ColorDialog object and act accordingly. Here is the code:
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
public class ColorDlgForm : System.Windows.Forms.Form
Chapter 9 - Understanding .NET Assemblies
{
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming private ColorDialog colorDlg;
Part Four - Leveraging the .NET Libraries
public ColorDlgForm()
Chapter 12 - Object Serialization and the .NET Remoting Layer
{
Chapter 13 - Building a Better Window (Introducing Windows Forms)
colorDlg = new ColorDialog();
Chapter 14 - A Better Painting Framework (GDI+)
Text = "Click on me to change the color";
Chapter 15 - Programming with Windows Forms Controls this.MouseUp +=
Chapter 16 - The Systemnew.IOMouseEventHandler(thisNamespace .ColorDlgForm_MouseUp);
Chapter }17 - Data Access with ADO.NET
Part...Five - Web Applications and XML Web Services
Chapter private18 - ASP.NETvoidWebColorDlgFormPages and Web ControlsMouseUp(object sender, MouseEventArgs e)
{
Chapter 19 - ASP.NET Web Applications
if (colorDlg.ShowDialog() != DialogResult.Cancel)
Chapter 20 - XML Web Services
Index {
currColor = colorDlg.Color;
List of Figures
this.BackColor = currColor;
List of Tables
// Show current color.
string strARGB = colorDlg.Color.ToString();
MessageBox.Show(strARGB, "Color is:");
}
}
}
Although there has not yet been a formal discussion of how to manipulate dialog boxes, the previous code should not raise too many eyebrows. Notice that you are able to determine which button has been clicked (OK or Cancel) by testing the return value of ShowDialog() against the DialogResult enumeration. You will see additional stock dialog boxes used in this chapter. Later, in Chapter 15, you learn how to build custom dialogs to gather (and validate) user input.
SOURCE The ColorDlg application is included under the Chapter 14 subdirectory.
CODE
C# and the .NET Platform, Second Edition
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
ManipulatingC# andFontsthe .NET Platform, Second Edition
by Andrew Troelsen |
ISBN:1590590554 |
Next, let's examine the specifics of the Font class (and related types). The System.Drawing.Font type
Apress © 2003 (1200 pages)
represents a given font installed on the user's machine. While the Font class defines a number of
This comprehensive text starts with a brief overview of the overloaded constructors,C# languagehereandarethensomequicklycommonmovesoptions:o key technical and
architectural issues for .NET developers.
// Create a Font of a given type name and size.
Font f = new Font("Times New Roman", 12);
Table of Contents
// Create a Font with a given name, size, and style set.
C# and the .NET Platform, Second Edition
Font f2 = new Font("WingDings", 50, FontStyle.Bold | FontStyle.Underline);
Introduction
Part One - Introducing C# and the .NET Platform
ChapterHere, f21 has- ThebeenPhilosophycreated ofusing.NETa set of FontStyle flags. The members of this enumeration allow you to
Chapterconfigure2 a- nBuildingmberC#of propertiesAp licationsof the Font object such as bold or italic (if you require more than one
PartFontStyle,Two - ThesimplyC# ProgrammOR eachitemng Lantogether)uage . Table 14-13 lists your choices.
Chapter 3 - C# Language Fundamentals
ChTablept r 144 -13:- ObjectThe-FontStyleOriented PrograEnumerationming with C#
|
Chapter 5 - Exceptions and Object Lifetime |
|
Meaning in Life |
|
FontStyle Enumeration Member |
|
|
|
Chapter 6 - Interfaces and Collections |
|
|
|
Bold |
|
Bold text |
|
Chapter 7 - Callback Interfaces, Delegates, and Events |
|
|
|
|
|
|
|
Chapter 8 - Advanced C# Type Construction Techniques |
|
Italic text |
|
Italic |
|
|
Part Three - Programming with .NET Assemblies |
|
|
|
|
|
||
|
Regular |
|
Normal text |
|
Chapter 9 - Understanding .NET Assemblies |
|
|
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Strikeout Text with a line through the middle
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Underline |
Underlined text |
Part Four - Leveraging the .NET Libraries |
|
Chapter 12 - Object Serialization and the .NET Remoting Layer
ChaptOnceryou13 -haveBuildingconfigureda BettertheWindlookwand(Introducingfeel of yourWindFontwsobject,Forms)the next obvious task is to pass it as a Chparameterpter 14 -toA theBetterGraphicsPainting.DrawString()Framework (GDI+)method. Although DrawString() has also been overloaded a
number of times, each variation typically requires the same basic information: a string to draw, the font to
Chapter 15 - Programming with Windows Forms Controls
draw it in, a brush used for rendering, and a location to place it. For example:
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
Part// FiveOne- Wversion:b ApplicationsvoidandDrawString(String,XML Web Services Font, Brush, Point);
Chapterg.DrawString("My18 - ASP.NET Webstring",Pages and newW b ControlsFont("Pop", 25),
new SolidBrush(Color.Black), new Point(0,0));
Chapter 19 - ASP.NET Web Applications
// Another version: void DrawString(String, Font, Brush, float, float);
Chapter 20 - XML Web Services
g.DrawString("Another string", new Font("Times New Roman", 16),
Index
new SolidBrush(Color.Red), 40, 40);
List of Figures
List of Tables
In each of these examples, you have made use of a SolidBrush type (of a particular color). It is possible to configure a number of brush types. For the time being, a solid brush fits the bill; you see more exotic brush types a bit later in this chapter. Once you have created a valid Font type, you are able to extract its current settings using a number of properties (e.g., Bold, Italic, Unit, Height, Size, FontFamily, and so forth).
Working with Font Families
The System.Drawing namespace also defines the FontFamily type, which abstracts a group of typefaces having a similar basic design but having certain style variations (such as point size). A family of fonts, like Verdana, can include several fonts that differ in style and size. For example, 12-point Verdana bold and 24point Verdana italic are different fonts within the Verdana font family.
The constructor of the FontFamily type takes a string representing the name of the font family you are attempting to capture. Once you create the generic family, you are then able to create a more specific Font object (in the following code, assume "g" is an object of type Graphics):
C# and the .NET Platform, Second Edition
// Make a family of fonts.
by Andrew Troelsen ISBN:1590590554
FontFamily myFamily = new FontFamily("Verdana");
Apress © 2003 (1200 pages)
// Pass family into ctor of Font.
This comprehensive text starts with a brief overview of the
Font myFont = new Font(myFamily, 12);
C# language and then quickly moves to key technical and g.DrawString("Hello?", myFont, Brushes.Blue, 10, 10);
architectural issues for .NET developers.
Of greater interest is the ability to gather statistics regarding a given family of fonts. For example, let's say
Table of Contents
you were building a text-processing application and wish to determine the average width of a character in a
C# and the .NET Platform, Second Edition
particular FontFamily. What if you wish to know the ascending and descending values for a given
Introduction
character? To answer such questions, the FontFamily type defines the key members shown in Table 14-14.
Part One - Introducing C# and the .NET Platform |
||||||
|
Note that each requires you to specify the font style using the FontStyle enumeration. |
|||||
Chapter 1 |
- The Philosophy of .NET |
|||||
Chapter 2 |
- Building C# Applications |
|||||
|
Table 14-14: Members of the FontFamily Type |
|||||
Part Two - The C# Programming Language |
|
|||||
ChapterFontFamily3 - C# Language FundamentalsMeaning in Life |
|
|||||
ChapterMember4 |
- Object-Oriented Programming with C# |
|
||||
|
|
|
|
|
|
|
|
|
Chapter 5 |
- Exceptions and |
|
Object Lifetime |
|
|
|
GetCellAscent() |
|
Returns the ascender metric for the members in this family |
|
|
|
|
Chapter 6 |
- Interfaces and |
|
Collections |
|
|
|
|
|
|||
|
ChapterGetCellDescent()7 - Callback Interfaces,ReturnsDelegates,the descenderand Eventsmetric for members in this family |
|
||||
|
|
|
|
|
|
|
|
|
Chapter 8 |
- Advanced C# |
|
Type Construction Techniques |
|
|
|
GetLineSpacing() |
|
Returns the distance between two consecutive lines of text for this |
|
|
Part Three - Programming |
|
with .NET Assemblies |
|
|||
|
|
|
|
|
FontFamily with the specified FontStyle |
|
|
Chapter 9 |
- Understanding |
|
.NET Assemblies |
|
|
|
|
|
|
|||
|
|
GetName() |
|
Returns the name of this FontFamily in the specified language |
|
|
|
Chapter 10 |
- Processes, |
AppDomains, Contexts, and Threads |
|
||
|
|
|||||
|
|
Chapter 11 |
- Type Reflection, |
|
Late Binding, and Attribute-Based Programming |
|
|
|
IsStyleAvailable() |
|
Indicates whether the specified FontStyle is available |
|
|
Part Four - Leveraging the |
|
.NET Libraries |
|
|||
Chapter 12 |
- Object Serialization and the .NET Remoting Layer |
|||||
|
To illustrate, here is a Paint handler that prints a number of characteristics of the Verdana font family: |
|||||
Chapter 13 |
- Building a Better Window (Introducing Windows Forms) |
|||||
Chapter 14 |
- A Better Painting Framework (GDI+) |
|||||
|
private void MainForm_Paint(object sender, PaintEventArgs e) |
|||||
Chapter 15 |
- Programming with Windows Forms Controls |
|||||
{ |
|
|
|
|
||
Chapter 16 |
- The System.IO Namespace |
|||||
|
|
Graphics g = e.Graphics; |
||||
Chapter 17 |
- Data Access with ADO.NET |
|||||
|
|
FontFamily myFamily = new FontFamily("Verdana"); |
Part Five - Web Applications and XML Web Services |
|
Font myFont = new Font(myFamily, 12); |
|
Chapter 18 - ASP.NET Web Pages and Web Controls |
|
int y = 0; |
// Get pixel height of font. |
Chapter 19 - ASP.NET Web Applications |
|
int fontHeight = myFont.Height; |
Chapter //20 -ShowXML WebunitsServicesof measurement for FontFamily members.
Index this.Text = "Measurements are in GraphicsUnit." + myFont.Unit.ToString();
g.DrawString("The Verdana family.", myFont, Brushes.Blue, 10, y);
List of Figures
y += 20;
List of Tables
// Print our family ties...
g.DrawString("Ascent for bold Verdana: " + myFamily.GetCellAscent(FontStyle.Bold), myFont, Brushes.Black, 10, y + fontHeight);
y += 20;
g.DrawString("Descent for bold Verdana: " + myFamily.GetCellDescent(FontStyle.Bold), myFont, Brushes.Black, 10, y + fontHeight);
y += 20;
g.DrawString("Line spacing for bold Verdana: " + myFamily.GetLineSpacing(FontStyle.Bold), myFont, Brushes.Black, 10, y + fontHeight);
y += 20;
g.DrawString("Height for bold Verdana: " + myFamily.GetEmHeight(FontStyle.Bold),
myFont, Brushes.Black, 10,
C# and the .NET Platform, Second Edition y += 20;
}by Andrew Troelsen Apress © 2003 (1200 pages)
y + fontHeight);
ISBN:1590590554
This comprehensive text starts with a brief overview of the Figure 14-8 showsC#thelanguageresult. and then quickly moves to key technical and
architectural issues for .NET developers.
Table
C# and
Part
Chapter
Chapter
Part
Chapter
Chapter
Figure 14-8: Gathering statistics of the Verdana font family
Chapter 5 - Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections
Note that these members of the FontFamily type return values using GraphicsUnit.Point (not Pixel) as the
Chapter 7 - Callback Interfaces, Delegates, and Events
unit of measure, which corresponds to 1/72 inch. You are free to transform these values to other units of
Chapter 8 - Advanced C# Type Construction Techniques measure as you see fit.
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
Understanding Font Metrics
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
If you have not worked with Fonts using this level of detail before, here are a few words regarding character
Part Four - Leveraging the .NET Libraries
measurements. The dimensions of a given Font are all based on the baseline value, which is the imaginary
Chapter 12 - Object Serialization and the .NET Remoting Layer
line on which each character "sits." Some characters (such as "j," "y," or "g") have a portion that drops
Chapter 13 - Building a Better Window (Introducing Windows Forms)
below this baseline. This is called the descending value. The ascending value represents the amount a
Chapter 14 - A Better Painting Framework (GDI+)
given character rises above the baseline. The leading value represents the difference between the height
Chapter 15 - Programming with Windows Forms Controls
and ascent, where height is the total distance between the leading and descending values.
Chapter 16 - The System.IO Namespace
To keep all these items fixed in your mind, ponder Figure 14-9 (the baseline is identified by the thicker line
Chapter 17 - Data Access with ADO.NET
toward the bottom).
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter
Chapter
Index
List of
List of
Figure 14-9: Font metrics
SOURCE The FontFamily application is included under the Chapter 14 subdirectory.
CODE
Building a FontC# andApplicationthe .NET Platform, Second Edition
by Andrew Troelsen |
ISBN:1590590554 |
Now, let's build a more complex application that allows the user to manipulate a Font object maintained by
Apress © 2003 (1200 pages)
a main Form. The application will allow the user to select the current font face from a predefined set using
This comprehensive text starts with a brief overview of the the "Configure | FontC# languageFace" menuand thenselectionquickly. moves to key technical and
architectural issues for .NET developers.
Let's also allow the user to indirectly control the size of the Font object using a Windows Forms Timer object. If the user activates the Timer using the "Configure | Swell?" menu item, the size of the Font object
Tableincreasesof Contentsat a regular interval (to a maximum upper limit). In this way, the text appears to swell and thus
C#providesand thea.NETsimplePlatforanimation, Secondof "breathing"Edition text.
Introduction
Finally, add a final menu item under the Configure menu named "List All Fonts," which will be used to list all
Part One - Introducing C# and the .NET Platform
fonts installed on the end-user's machine. Figure 14-10 shows the menu UI logic (the File menu simply
Chapter 1 - The Philosophy of .NET allows the user to exit the application).
Chapter 2 - Building C# Applications
Part Two - The C# Programming Language
Chapter
Chapter
Chapter
Chapter
Chapter
Chapter
Part
Chapter
Chapter
Chapter |
Programming |
Part
Chapter
Chapter
Chapter
Chapter 15 - Programming with Windows Forms Controls
Figure 14-10: Menu layout of the FontApp project
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
To begin implementing our application, update the main Form with a Timer member variable (named
Part Five - Web Applications and XML Web Services
timer), a string to represent the current font face (named fontFace), and an integer (named swellValue) to
Chapter 18 - ASP.NET Web Pages and Web Controls
represent the amount to adjust the font size. In addition to configuring the basic look and feel of the Form,
Chapter 19 - ASP.NET Web Applications
configure your timer to emit a Tick event every 100 milliseconds:
Chapter 20 - XML Web Services |
|
|
Index |
FontForm : System.Windows.Forms.Form |
|
Listpublicof Figuresclass |
|
|
List{ of Tables |
Timer timer; |
|
private |
|
|
private |
int swellValue; |
// The default font face. |
private |
string fontFace = " WingDings"; |
public FontForm()
{
// The menu system has been designed using the IDE...
InitializeComponent(); timer = new Timer(); Text = "Font App"; Width = 425;
Height = 150;
BackColor = Color.Honeydew;
CenterToScreen();
// Configure the Timer.
timer.Enabled = true;
timer.Interval = 100;
timer.Tick += new EventHandler(FontForm_OnTimer);
|
} |
C# and the .NET Platform, Second Edition |
|
|
} |
by Andrew Troelsen |
ISBN:1590590554 |
||
|
||||
|
Apress © 2003 (1200 pages) |
|
||
|
|
|
This comprehensive text starts with a brief overview of the
In the Tick event C#handler,languageincreaseand thenthe quicklyvalue ofmovesthe swellValueto key technicdatalmember,and and refresh your client area
architectural issues for .NET developers.
via the Invalidate() method. Recall that the swellValue integer will be added to the current font size to provide a simple animation (assume swellValue has a maximum upper limit of 50). To help reduce the
flicker that can occur when redrawing the entire client area, you only refresh the minimum dirty rectangular
Table of Contents region:
C# and the .NET Platform, Second Edition
Introduction
private void FontForm_OnTimer(object sender, EventArgs e)
Part One - Introducing C# and the .NET Platform
{
Chapter 1 - The Philosophy of .NET
// Increase current swellValue by 5.
Chapter 2 - Building C# Applications swellValue += 5;
Part Two - The C# Programming Language
// If this value is greater than or equal to 50, reset to zero.
Chapter 3 - C# Language Fundamentals if(swellValue >= 50)
Chapter 4 - Object-Oriented Programming with C# swellValue = 0;
Chapter 5 - Exceptions and Object Lifetime
// Just invalidate the 'minimal dirty rectangle to help reduce flicker.
Chapter 6 - Interfaces and Collections
Invalidate(new Rectangle(0, 0, ClientRectangle.Width, 100));
Chapter 7 - Callback Interfaces, Delegates, and Events
}
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Now that the upper 100 pixels of your client area are refreshed with each tick of the Timer, you better have
Chapter 9 - Understanding .NET Assemblies
something to render! In the Form's Paint handler, create a Font object based on the user-defined font face
Chapter 10 - Processes, AppDomains, Contexts, and Threads
(as selected from the appropriate menu item) and current swellValue (as dictated by the timer). Once you
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
have your Font object fully configured, render a message into the center of the dirty rectangle:
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
private void FontForm_Paint(object sender, PaintEventArgs e)
Chapter 13 - Building a Better Window (Introducing Windows Forms)
{
Chapter 14 - A Better Painting Framework (GDI+)
Graphics g = e.Graphics;
Chapter 15 - Programming with Windows Forms Controls
// The font size can be between 12 and 62,
Chapter 16 - The System.IO Namespace
// based on the current swellValue.
Chapter 17 - Data Access with ADO.NET
Font theFont = new Font(fontFace, 12 + swellValue);
Part Five - Web Applications and XML Web Services
string message = "Hello GDI+";
Chapter 18 - ASP.NET Web Pages and Web Controls
// Display message in the center of the rect.
Chapter 19 - ASP.NET Web Applications
float windowCenter = this.DisplayRectangle.Width/2;
Chapter 20 - XML Web Services
SizeF stringSize = g.MeasureString(message, theFont);
Index float startPos = windowCenter - (stringSize.Width/2);
List of Figures
g.DrawString(message, theFont, new SolidBrush(Color.Blue), startPos, 10);
List of Tables
}
As you would guess, if a user selects a specific font face, the Clicked handler for each menu selection is in charge of updating the fontFace string variable and invalidating the client area. The sample code for this example takes this a bit further to ensure that the user's font of preference is identified with a check mark. Given that the previous chapter has already pounded out the details of menu manipulations, I'll assume you will implement these details as you see fit.
The menu handler for the Swell menu item will be used to allow the user to stop or start the swelling of the text (i.e., enable or disable the animation). Thus, configure the Clicked handler to enable or disable the Timer as follows:
private void ConfigSwell_Clicked(object sender, EventArgs e)
{
timer.Enabled = !timer.Enabled;
mainMenu.MenuItems[1].MenuItems[0].Checked = timer.Enabled;
C# and the .NET Platform, Second Edition
}
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
EnumeratingarchitecturInstalledissuesFontsf r .NET deve(a laopersSystem. .Drawing.Text)
Next, let's expand the FontApp to programmatically discover the set of installed fonts on the target machine.
TableDoingofsoContentsgives you a chance to explore another namespace of GDI+, System.Drawing.Text. This
namespace contains a (small) handful of useful types that can be used to discover and manipulate the set
C# and the .NET Platform, Second Edition
Introductionof fonts installed on the target machine. The highlights are shown in Table 14-15. |
||||||
Part One - Introducing C# and the .NET Platform |
||||||
|
ChapterTable 141 -15:- TheThePhilosophyText Typeof .NET |
|||||
|
|
|
|
|
|
|
|
|
Chapter 2 - Building C# Applications |
Meaning in Life |
|
|
|
|
|
System.Drawing.Text |
|
|
|
|
Part Two - The C# Programming |
Language |
|
|
|||
|
|
Type |
|
|
|
|
|
Chapter 3 - C# Language Fundamentals |
|
|
|||
|
|
|
|
|||
|
ChapterInstalledFontCollection4 - Object-Oriented ProgrammingRepresentswith theC# set of all fonts installed on the target system. |
|
|
|||
|
|
|
|
|
||
|
|
Chapter 5 - Exceptions and Object |
|
Lifetime |
|
|
|
|
PrivateFontCollection |
|
Encapsulates a collection of specific Font types. |
|
|
|
|
Chapter 6 - Interfaces and Collections |
|
|
||
|
|
|
||||
|
ChapterLineSpacing7 - Callback Interfaces, Delegates,This enumerationand Eventsspecifies the spacing between lines of text in a |
|
|
|||
|
|
Chapter 8 - Advanced C# Type |
|
text string that spans more than a single line. |
|
|
|
|
Construction Techniques |
|
|
Part Three - Programming with .NET Assemblies
TextRenderingHint Another enumeration that allows you to specify the quality of the
Chapter 9 - Understanding .NET Assemblies
current text rendering operation. For example, the Text value
Chapter 10 - Processes, AppDomains,representsContext , and Threads
a fast (but low quality) rendering. AntiAliased marks
Chapter 11 - Type Reflection, Late Binding,better qualityand Attributea slower-Bas drenderingProgrammingcycle.
Part Four - Leveraging the .NET Libraries
ChapterWhen the12 -userObjectselectsSerializationthe "Configureand the|.ListNET AllRemFonts"ting Layermenu item, the corresponding Clicked handler
Chaptercreates13an-instanceBuilding aofBetterthe InstalledFontCollectionWindow (I tr ducing Windowsclass. ThisForms)class maintains an array named FontFamily,
Chapterwhich represents14 - A BetterthePaintingset of allFramewfonts onrkthe(GDI+)target machine, and may be obtained using the ChapterInstalledFontCollection15 - Programming.Familieswith Windpropertyws Forms. UsingControlsthe FontFamily.Name property, you are able to extract the
font face (e.g., Times New Roman, Arial, etc.) for each font.
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
Here, you have added a private string data member named installedFonts to hold each font face. The logic in the "List Installed Fonts" menu handler creates an instance of the InstalledFontCollection type, reads the
name of each string, and adds the new font face to the private installedFonts data member:
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
public class FontForm : System.Windows.Forms.Form
Index
{
List of Figures
// Holds the list of fonts.
List of Tables
private string installedFonts;
// Menu handler to get the list of installed fonts.
private void mnuConfigShowFonts_Clicked(object sender, EventArgs e)
{
InstalledFontCollection fonts = new InstalledFontCollection(); for(int i = 0; i < fonts.Families.Length; i++)
installedFonts += fonts.Families[i].Name + " ";
//This time, we need to invalidate the entire client area,
//as we will paint the installedFonts string on the lower half
//of the client rectangle.
Invalidate();
}
...
}
The final task is to render the installedFonts string to the client area, directly below the screen real estate
C# and the .NET Platform, Second Edition that is used for your swelling text:
by Andrew Troelsen |
ISBN:1590590554 |
Apress © 2003 (1200 pages)
private void FontForm_Paint(object sender, PaintEventArgs e)
This comprehensive text starts with a brief overview of the
{
C# language and then quickly moves to key technical and
Graphics g = e.Graphics;
architectural issues for .NET developers.
Font theFont = new Font(fontFace, 12 + swellValue);
string message = "Hello GDI+";
Table of //ContentsDisplay message in the center of the window!
float windowCenter = this.DisplayRectangle.Width/2;
C# and the .NET Platform, Second Edition
SizeF stringSize = e.Graphics.MeasureString(message, theFont);
Introduction
float startPos = windowCenter - (stringSize.Width/2);
Part One - Introducing C# and the .NET Platform
g.DrawString(message, theFont, new SolidBrush(Color.Blue), startPos, 10);
Chapter 1 - The Philosophy of .NET
// Show installed fonts in the rectangle below the swell area.
Chapter 2 - Building C# Applications
Rectangle myRect = new Rectangle(0, 100,
Part Two - The C# Programming Language
ClientRectangle.Width, ClientRectangle.Height);
Chapter 3 - C# Language Fundamentals
// Paint this area of the Form black.
Chapter 4 - Object-Oriented Programming with C#
g.FillRectangle(new SolidBrush(Color.Black), myRect);
Chapter 5 - Exceptions and Object Lifetime g.DrawString(installedFonts, new Font("Arial", 12),
Chapter 6 - Interfaces and Collections
new SolidBrush(Color.White), myRect);
Chapter 7 - Callback Interfaces, Delegates, and Events
}
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
ChapterRecall 9that-theUnderstandingsize of the "dirty.NET Assemblirectangle"s has been mapped to the upper 100 pixels of the client rectangle.
ChapterBecause10you- Processes,Tick handlerAppDonlymains,invalidatesCont xts,a portionand Threadsof the Form, the remaining area is not redrawn when
Chapterthe Tick11event- TypehasReflection,been sentLate(toBinding,help optimizeand Attheributerendering-Based Programmiof the clientgarea).
Part Four - Leveraging the .NET Libraries
As a final touch, to ensure proper redrawing let's handle the Resize event to ensure that if the user resizes
Chapter 12 - Object Serialization and the .NET Remoting Layer
the Form, the lower part of client rectangle is redrawn correctly:
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
private void FontForm_Resize(object sender, System.EventArgs e)
Chapter 15 - Programming with Windows Forms Controls
{
Chapter 16 - The System.IO Namespace
Rectangle myRect = new Rectangle(0, 100,
Chapter 17 - Data Access with ADO.NET
ClientRectangle.Width, ClientRectangle.Height);
Part Five - Web Applications and XML Web Services
Invalidate(myRect);
Chapter 18 - ASP.NET Web Pages and Web Controls
}
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
IndexWith that, Figure 14-11 shows the result.
List of Figures
List of Tables
Figure 14-11: The FontApp application in action
SOURCE The FontApp application is included under the Chapter 14 subdirectory.
CODE
The FontDialogC# andClassthe .NET Platform, Second Edition
by Andrew Troelsen |
ISBN:1590590554 |
As you might assume, there is a default font dialog box (FontDialog), as seen in Figure 14-12.
Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the moves to key technical and
developers.
Table
C# and
Part
Chapter
Chapter
Part
Chapter
Chapter
ChapterFigure5 - 14Exceptions-12: TheandstockObject.NETLifetimeFont dialog
Chapter 6 - Interfaces and Collections
Chapter 7 - Callback Interfaces, Delegates, and Events
Like the ColorDialog type examined earlier in this chapter, when you wish to work with the FontDialog, simply call the ShowDialog() method. Using the Font property, you may extract the characteristics of the
current selection for use in the application. To illustrate, here is a new Form that mimics the logic of the
Chapter 9 - Understanding .NET Assemblies
previous ColorDlgForm (i.e., click the form to launch the File dialog and render GDI+ logic onto the form's
Chapter 10 - Processes, AppDomains, Contexts, and Threads client area).
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
public class FontDlgForm : System.Windows.Forms.Form
Chapter 12 - Object Serialization and the .NET Remoting Layer
{
Chapter 13 - Building a Better Window (Introducing Windows Forms)
private FontDialog fontDlg;
Chapter 14 - A Better Painting Framework (GDI+)
private Font currFont;
Chapter 15 - Programming with Windows Forms Controls
private void FontDlgForm_Paint(object sender, PaintEventArgs e)
Chapter 16 - The System.IO Namespace
{
Chapter 17 - Data Access with ADO.NET
Graphics g = e.Graphics;
Part Five - Web Applications and XML Web Services
g.DrawString("Testing...", currFont,
Chapter 18 - ASP.NET Web Pages and Web Controls
new SolidBrush(Color.Black), 0, 0);
Chapter }19 - ASP.NET Web Applications
Chapter public20 - XML WebFontDlgForm()Services
Index {
List of Figures
List of Tables
}
CenterToScreen();
fontDlg = new FontDialog(); fontDlg.ShowHelp = true;
Text = "Click on me to change the font"; currFont = new Font("Times New Roman", 12);
...
// Event handler for MouseUp event.
private void FontDlgForm_MouseUp(object sender, MouseEventArgs e)
{
if (fontDlg.ShowDialog() != DialogResult.Cancel)
{
currFont = fontDlg.Font; Invalidate();
}
}
}
SOURCE
CODE
C# and the .NET Platform, Second Edition |
|
by Andrew Troelsen |
ISBN:1590590554 |
The FontDlgForm application is included under the Chapter 14 subdirectory.
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
Survey of theC# andSystemthe .NET.DrawingPlatform, Second.Drawing2DEdition Namespace
by Andrew Troelsen |
ISBN:1590590554 |
Now that you have manipulated Font types, the next task is to examine how to manipulate Pen and Brush
Apress © 2003 (1200 pages)
objects to render geometric patterns. While you could do so making use of nothing more than the types
This comprehensive text starts with a brief overview of the
found in the SystemC#.languageDrawing namespace,and then quicklyyoumovesshouldtobekeyawaretechnicthatl manyand of the more "sexy" pen and brush configurationsarchitectur(for example,l issuestheforHatchBrush.NET developerstype. used at the beginning of this chapter) require types defined within the System.Drawing.Drawing2D namespace.
TableThisofadditionalContentsGDI+ namespace (which is substantially smaller than System.Drawing) provides a number C#of andclassesthe .thatNET allowP atform,youSecondto modifyEditionthe line cap (triangle, diamond, etc.) used for a given pen, build
textured brushes, as well as work with vector graphic manipulations. Some core types to be aware of,
Introduction
grouped by related functionality, are shown in Table 14-16.
Part One - Introducing C# and the .NET Platform
Chapter 1 - The Philosophy of .NET
Table 14-16: The Classes of System.Drawing.Drawing2D
Chapter 2 - Building C# Applications
|
|
|
|
|
|
Part Two - The C# Programming Language |
|
Meaning in Life |
|
||
|
System.Drawing.Drawing2D |
|
|
||
Chapter 3 |
- C# Language Fundamentals |
|
|
|
|
|
Class |
- Object-Oriented Programming |
|
with C# |
|
|
Chapter 4 |
|
|
||
|
|
|
|||
|
ChapterAdjustableArrowCap5 - Exceptions and Object LifetimePen caps are used to paint the beginning and end points of |
|
|||
|
Chapter 6 |
- Interfaces and Collections |
|
a given line. These types represent an adjustable arrow- |
|
|
CustomLineCap |
|
shaped and user-defined cap. |
|
|
|
Chapter 7 |
|
|
|
|
|
- Callback Interfaces, Delegates, and Events |
|
|||
|
|
|
|
|
|
|
Chapter 8 |
- Advanced C# Type Construction Techniques |
|
||
|
Blend |
|
|
Used to define a blend pattern (and colors) used in |
|
Part Three - Programming with .NET Assemblies |
|
||||
|
ColorBlend |
|
conjunction with a LinearGradientBrush. |
|
|
|
Chapter 9 |
- Understanding .NET Assemblies |
|
||
|
|
||||
|
ChapterGraphicsPath10 - Processes, AppDomains, Contexts,A GraphicsPathand Threadsobject represents a series of connected |
|
|||
|
Chapter 11 |
- Type Reflection, Late Binding,linesand Attributeand curves-Based. ThisProgrammingclass allows you to insert just about |
|
||
|
GraphicsPathIterator |
|
|
|
|
Part Four - Leveraging the .NET Libraries any type of geometrical pattern (arcs, rectangles, lines, |
|
||||
|
PathData |
|
|
|
|
Chapter 12 |
- Object Serialization and the .NETstrings,Remotingpolygons,Layeretc.) into the path. PathData holds the |
|
|||
|
Chapter 13 |
- Building a Better Window |
|
(IntroducinggraphicalWindowsdata thatForms)makes up a path. |
|
|
|
|
|||
|
Chapter 14 |
- A Better Painting Framework |
|
(GDI+) |
|
|
HatchBrush |
|
Exotic brush types. |
|
|
|
Chapter 15 |
- Programming with Windows |
|
Forms Controls |
|
|
LinearGradientBrush |
|
|
|
|
|
Chapter 16 |
- The System.IO Namespace |
|
|
|
|
PathGradientBrush |
|
|
|
|
|
Chapter 17 |
- Data Access with ADO.NET |
|
|
|
Part Five - Web Applications and XML Web Services
Also be aware that the System.Drawing.Drawing2D namespace defines another set of enumerations that
Chapter 18 - ASP.NET Web Pages and Web Controls
are used in conjunction with these core types. Table 14-17 gives a quick rundown.
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Table 14-17: The Enumerations of System.Drawing.Drawing2D
Index
List of Figures
List of Tables
|
|
|
|
|
|
|
|
|
|
|
System.DrawingC# and.Drawing2Dthe .NET Platform, SecondMeaningEd tion in Life |
|
|||
|
|
|
Enumerationby Andrew Troelsen |
ISBN:1590590554 |
|
||
|
|
|
|
|
|
|
|
|
|
|
DashStyle |
Apress © 2003 (1200 pages) |
|
Specifies the style of dashed lines drawn with a |
|
|
|
|
|
|
|
||
|
|
|
|
This comprehensive text starts with a brief overview of the |
|
||
|
|
|
|
|
|
Pen |
|
|
|
|
|
C# language and then quickly moves to key technical and |
|
||
|
|
|
|
|
|
|
|
|
|
|
FillMode |
architectural issues for .NET developers. |
|
||
|
|
|
|
|
Specifies how the interior of a closed path is filled |
|
|
|
|
|
|
|
|
|
|
|
|
|
HatchStyle |
|
|
Specifies the different patterns available for |
|
Table of Contents |
|
|
HatchBrush objects |
|
|||
|
|
|
|
|
|||
C# and the .NET Platform, Second Edition |
|
Specifies the direction to apply a linear gradient |
|
||||
|
|
|
LinearGradientMode |
|
|
||
|
Introduction |
|
|
|
|
||
|
|
|
|
|
|||
|
|
|
|
|
Specifies the current cap styles used by a Pen |
|
|
|
|
|
LineCap |
|
|
|
|
Part One - Introducing C# and the .NET Platform |
|
|
|
||||
|
|
|
|
|
|||
|
|
|
Chapter 1 - The Philosophy of .NET |
|
Specifies the alignment of a Pen in relation to the |
|
|
|
|
|
PenAlignment |
|
|
|
|
|
Chapter 2 - Building C# Applications |
|
line being drawn |
|
|||
Part Two - The C# Programming Language |
|
|
|||||
|
|
|
|||||
ChapterPenType3 - C# Language Fundamentals |
|
Specifies the type of fill a Pen uses to fill lines |
|
||||
|
|
|
|
||||
|
|
|
Chapter 4 - Object-Oriented Programming with C# |
|
Specifies the overall quality used to render a |
|
|
|
|
|
QualityMode |
|
|
|
|
|
Chapter 5 - Exceptions and Object Lifetime |
|
graphic image |
|
|||
|
|
|
SmoothingMode |
|
|
||
|
Chapter 6 - Interfaces and Collections |
|
|
|
|||
|
ChapterRenderingHint7 - Callback Interfaces, Delegates, and Events |
|
|||||
|
|
|
|
|
|
|
|
Chapter 8 - Advanced C# Type Construction Techniques |
|||||||
Part Three - Programming with .NET Assemblies |
|
|
ChapterEstablishing9 - Understandingthe Rendering.NET Ass mblies Quality
Chapter 10 - Processes, AppDomains, Contexts, and Threads
ChapterNotice 11that-someType Reflectioof the n,umeratLate Bionsnding,defineda Attributein the System-Based .ProgrammingDrawing.Drawing2D namespace (such as
PartQualityModeFour - Leveragingand SmoothingMode)the .NET Librariesallow you to configure the overall quality of the current rendering Chapteroperation12.-WhenObjectyouSerializationobtain Graphicsand the .NETobject,Remotingit has aLayerdefault rendering mode, which is a middle-of-the-
road combination of speed and overall quality. Let's examine one way to tweak a Graphics object to
Chapter 13 - Building a Better Window (Introducing Windows Forms)
override these default values.
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
The SmoothingMode enumeration (Table 14-18) is typically used to control how the GDI+ objects being
Chapter 16 - The System.IO Namespace
rendered with the current Graphics object are antialiased (or not).
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Table 14-18: Various SmoothingMode Values
Chapter 18 - ASP.NET Web Pages and Web Controls
SmoothingMode Meaning in Life
Chapter 19 - ASP.NET Web Applications
Value
Chapter 20 - XML Web Services
Index
AntiAlias
List of Figures
List of Tables
HighQuality
HighSpeed
Specifies antialiased rendering. The AntiAlias mode uses shades of gray or color to smooth the edges of lines and curves, and is effective on CRT screens as well as LCD screens.
Specifies high-quality, lower-performance rendering. The high-quality mode uses more sophisticated techniques that take advantage of the subpixel resolution of LCD screens.
A single pixel on an LCD screen is divided into three stripes that are set to various shades to produce the line or curve that appears the smoothest to the human eye.
Specifies low-quality, high-performance rendering. The high-speed mode does not smooth the item being rendered; pixels are either on or off.
When you wish to override the default rendering quality for a current GDI+ rendering operation, make use of the SmoothingMode property of the Graphics object:
private void MainForm_Paint(object sender, PaintEventArgs e)
C# and the .NET Platform, Second Edition
{
by Andrew Troelsen |
ISBN:1590590554 |
Graphics g = e.Graphics;
Apress © 2003 (1200 pages)
// Set quality of GDI+ object rendering.
This comprehensive text starts with a brief overview of the g.SmoothingMode = SmoothingMode.AntiAlias;
C# language and then quickly moves to key technical and
...
architectural issues for .NET developers.
}
Table of Contents
Be aware that the SmoothingMode property is only used to control the quality of rendering GDI+ objects,
not textual information. If you wish to modify the rendering quality for Font types, you need to set the
Introduction
TextRenderingHint property using the related System.Drawing.Text.TextRenderingHint enumeration:
Part One - Introducing C# and the .NET Platform
Chapter 1 - The Philosophy of .NET
public enum System.Drawing.Text.TextRenderingHint
Chapter 2 - Building C# Applications
{
Part Two - The C# Programming Language
AntiAlias, AntiAliasGridFit,
Chapter 3 - C# Language Fundamentals
ClearTypeGridFit, SingleBitPerPixel,
Chapter 4 - Object-Oriented Programming with C#
SingleBitPerPixelGridFit, SystemDefault
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 Pens
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
GDI+ Pen objects are used to draw lines (not too much of a stretch there!). However, a pen in and of itself
Chapter 10 - Processes, AppDomains, Contexts, and Threads
is of little value. When you need to render a geometric shape onto a Control-derived type, you send a pass
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
valid Pen type to any number of render methods defined by the Graphics class. In general, the
Part Four - Leveraging the .NET Libraries
DrawXXXX() methods are used to render some set of lines to a graphics surface, and are typically used
Chapter 12 - Object Serialization and the .NET Remoting Layer
with Pen objects. The Graphics class also defines a number of FillXXXX() methods that render an image
Chapter 13 - Building a Better Window (Introducing Windows Forms) using some sort of Brush-derived type (more on those in just a minute).
Chapter 14 - A Better Painting Framework (GDI+)
Although you have seen many drawing members earlier in the chapter, here they are again (Table 14-19)
Chapter 15 - Programming with Windows Forms Controls
in a bit more detail (be aware that each of these methods have been overloaded a number of times).
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
Table 14-19: Drawing Members of the Graphics Class
Part Five - Web Applications and XML Web Services
|
|
|
|
|
Chapter 18 - ASP.NET Web Pages |
and Web Controls |
|
|
Drawing Method of |
|
Meaning in Life |
|
Chapter 19 - ASP.NET Web Applications |
||
|
Graphics Type |
|
|
|
Chapter 20 - XML Web Services |
|
|
|
|
|
|
IndexDrawArc() |
|
This method renders an arc given a pen, and an ellipse on which to |
|
List of Figures |
|
base the angle of the arc. |
|
|
|
|
|
List of Tables |
|
Given four points, this method draws a cubic Bezier curve (or a |
|
|
DrawBezier() |
|
|
|
DrawBeziers() |
|
number of Beziers). |
|
|
|
|
|
|
|
|
|
DrawCurve() |
|
Draws a curve defined by an array of points. |
|
|
|
|
|
DrawEllipse() |
|
Draws the outline of an ellipse within the scope of a bounding |
|
|
|
rectangle. |
|
|
|
|
|
DrawLine() |
|
Given a Point (or an array of Point types), these methods connect |
|
DrawLines() |
|
the dots (if you will). |
|
|
|
|
|
DrawPath() |
|
Using the GraphicsPath type defined in the |
|
|
|
System.Drawing.Drawing2D namespace, this method renders a |
|
|
|
collection of lines/curves as specified by the path. |
|
|
|
|
|
DrawPie() |
|
Draws the outline of a pie section defined by an ellipse and two |
|
|
|
radial lines. |
DrawPolygon() Draws the outline of a polygon defined by an array of Point types.
C# and the .NET Platform, Second Edition
by Andrew |
Troelsen |
ISBN:1590590554 |
DrawRectangle() |
Renders a box, or a whole bunch of boxes, based on top-left- |
|
Apress © 2003 |
(1200 pages) |
|
DrawRectangles() |
bottom-right coordinates. This can be specified using Rectangle |
|
This comprehensive text starts with |
brief overview of the |
|
|
types, integers, or floating point numbers. |
|
C# language |
and then quickly moves to key technical and |
architectural issues for .NET developers.
Now that you better understand the core methods used to render geometric images, you can examine the Pen class itself. This class defines a small set of constructors that allow you to determine the initial color
and width of the pen nib (you can also construct a new Pen based on an existing Brush object...more
Table of Contents
later). Most of a Pen's functionality comes by way of its supported properties. Table 14-20 gives a partial
C# and the .NET Platform, Second Edition
list.
Introduction
Part One - Introducing C# and the .NET Platform
Table 14-20: Pen Properties
Chapter 1 - The Philosophy of .NET
|
Chapter 2 |
- Building |
|
C# Applcations |
|
|
||
|
Pen Property |
|
|
|
Meaning in Life |
|
||
Part Two - The C# Programming Language |
|
|||||||
|
||||||||
|
Brush |
|
|
|
|
Determines the Brush used by this Pen. |
|
|
|
Chapter 3 |
- C# Language Fundamentals |
|
|||||
|
|
|
|
|
|
|
|
|
|
Chapter 4 |
- Object- |
|
Oriented Programming with C# |
|
|||
|
Color |
|
|
|
|
Determines the Color type used by this Pen. |
|
|
|
Chapter 5 |
- Exceptions |
|
|
|
and Object Lifetime |
|
|
|
|
|
|
|
||||
|
CompoundArray |
|
|
|
Gets or sets an array of custom dashes and spaces. |
|
||
|
Chapter 6 |
- Interfaces |
|
|
|
and Collections |
|
|
|
|
|
|
|
||||
|
Chapter 7 |
- Callback |
|
|
|
Interfaces, Delegates, and Events |
|
|
|
CustomStartCap |
|
|
|
Gets or sets a custom cap style to use at the beginning or end of lines drawn |
|
||
|
Chapter 8 |
- Advanced |
|
|
|
C# Type Construction Techniques |
|
|
|
CustomEndCap |
|
|
|
with this Pen. Cap styles are simply the term used to describe how the initial |
|
||
Part Three - Programming |
|
and final stroke of the Pen should look and feel. These properties allow you |
|
|||||
|
with .NET Assemblies |
|
||||||
Chapter 9 |
|
|
|
|
to build customcaps for your Pen types. |
|
||
- Understanding .NET A se |
blies |
|
||||||
|
|
|
|
|
|
|
|
|
|
Chapter 10 |
- Processes, |
|
|
AppDomains, Contexts, and Threads |
|
||
|
DashCap |
|
|
|
Gets or sets the cap style used at the beginning or end of dashed lines drawn |
|
||
|
Chapter 11 |
- Type Reflection, Late Binding, and Attribute-Based Programming |
|
|||||
|
|
|
|
|
|
with this Pen. |
|
|
Part Four - Leveraging |
|
|
|
the .NET Libraries |
|
|||
|
|
|
|
|||||
ChapterDashOffset12 - Object |
|
|
|
SerializationGets or setsand thedistance.NET Remotingfrom theLayerstart of a line to the beginning of a dash |
|
|||
Chapter 13 |
- Building a |
|
patternBet Window. |
(Introducing Windows Forms) |
|
|||
|
|
|
|
|
|
|
||
|
Chapter 14 |
- A Better |
|
|
|
Painting Framework (GDI+) |
|
|
|
DashPattern |
|
|
|
Gets or sets an array of custom dashes and spaces. The dashes are made |
|
||
|
Chapter 15 |
- Programming with Windows Forms Controls |
|
|||||
|
|
|
|
|
|
up of line segments. |
|
|
|
Chapter 16 |
- The System.IO Namespace |
|
|||||
|
|
|||||||
|
ChapterDashStyle17 - Data AccessGetswithorADO.NETsets the style used for dashed lines drawn with this Pen. |
|
||||||
|
|
|
|
|
|
|||
Part Five - Web Applications and XML Web Services |
|
|||||||
|
LineJoin |
|
|
|
|
Gets or sets the join style for the ends of two overlapping lines drawn with this |
|
|
Chapter 18 |
- ASP.NET Web Pages and Web Controls |
|
||||||
|
|
|
|
|
|
Pen. |
|
|
|
Chapter 19 |
- ASP.NET |
|
|
|
Web Applications |
|
|
|
|
|
|
|||||
|
PenType |
|
|
|
Gets the style of lines drawn with this Pen. |
|
||
|
Chapter 20 |
- XML Web |
|
|
|
Services |
|
|
Index
StartCap
List of Figures
EndCap
List of Tables
Width
Gets or sets the predefined cap style used at the beginning or end of lines drawn with this Pen. Set the cap of your Pen using the LineCap enumeration defined in the System.Drawing.Drawing2D namespace.
Gets or sets the width of this Pen.
Remember that in addition to the Pen type, GDI+ also provides a Pens collection. Using a number of static properties, you are able to retrieve a Pen (or a given color) on the fly, rather than creating a custom Pen by hand. Be aware, however, that the Pen types returned will always have a width of 1. If you require a more exotic pen, you will need to build a Pen type by hand.
First, let's render some geometric images using simple Pen types. Assume we have a main Form object, which is capable of responding to paint requests. The implementation is as follows:
private void MainForm_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
// Make a big blue pen.
Pen bluePen = new Pen(Color.Blue, 20);
C# and the .NET Platform, Second Edition
// Get a stock pen from the Pens type.
by Andrew Troelsen |
|
ISBN:1590590554 |
Pen pen2 = Pens.Firebrick; |
|
|
Apress © 2003 (1200 pages) |
|
|
// Render some shapes with the pens. |
|
|
Th s comprehensive text starts with a brief overview of the |
||
g.DrawEllipse(bluePen, |
10, 10, 100, 100); |
C# language and then quickly moves to key technical and g.DrawLine(pen2, 10, 130, 110, 130);
architectural issues for .NET developers. g.DrawPie(Pens.Black, 150, 10, 120, 150, 90, 80);
// Draw a purple dashed polygon as well...
Pen pen3 = new Pen(Color.Purple, 5);
Table of Contents
pen3.DashStyle = DashStyle.DashDotDot;
C# and the .NET Platform, Second Edition
g.DrawPolygon(pen3, new Point[]{new Point(30, 140),
Introduction
new Point(265, 200), new Point(100, 225),
new Point(190, 190), new Point(50, 330),
Chapter 1 - The Philosophy of .NET
new Point(20, 180)});
Chapter 2 - Building C# Applications
// And a rectangle containing some text...
Part Two - The C# Programming Language
Rectangle r = new Rectangle(150, 10, 130, 60);
Chapter 3 - C# Language Fundamentals g.DrawRectangle(Pens.Blue, r);
Chapter 4 - Object-Oriented Programming with C# g.DrawString("Hello out there...How are ya?",
Chapter 5 - Exceptions and Object Lifetime
new Font("Arial", 12), Brushes.Black, r);
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
Notice that the Pen that is used to render your polygon makes use of the DashStyle enumeration (defined
Chapter 9 - Understanding .NET Assemblies
in System.Drawing.Drawing2D). This is the .NET equivalent of the raw Win32 pen style flags (e.g.,
Chapter 10 - Processes, AppDomains, Contexts, and Threads
PS_SOLID).Table 14-21 lists your choices.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
Table 14-21: Dash Styles |
||||||
|
Chapter 12 - Object Serialization and the .NET Remoting Layer |
|||||
|
|
|
|
|
|
|
|
Chapter 13 - Building a Better Window (I troducing Windows Forms) |
|
|
|||
|
DashStyle |
|
|
Meaning in Life |
|
|
|
Chapter 14 - A Better Painting Framework (GDI+) |
|
|
|||
|
Value |
|
|
|
|
|
|
|
|
|
|
|
|
|
Chapter 15 - Programming |
|
with Windows Forms Controls |
|
||
|
Custom |
|
|
Specifies a user-defined custom dash style |
|
|
|
Chapter 16 - The System.IO |
|
|
Namespace |
|
|
|
|
|
||||
|
Chapter 17 - Data Access |
|
|
with ADO.NET |
|
|
|
Dash |
|
|
Specifies a line comprised of dashes |
|
|
|
|
|
|
|
|
|
Part Five - Web Applications |
|
|
and XML Web Services |
|
|
|
|
DashDot |
|
|
Specifies a line comprised of an alternating pattern of dash-dot-dash-dot |
|
|
|
Chapter 18 - ASP.NET Web |
|
|
Pages and Web Controls |
|
|
|
|
ChapterDashDotDot19 - ASP.NET Web SpecifiesA plicationsline comprised of an alternating pattern of dash-dot-dot-dash-
Chapter 20 - XML Web Servicesdot-dot
|
|
|
|
Index |
|
Specifies a line comprised of dots |
|
|
Dot |
|
|
List of Figures |
|
|
|
|
|
||
|
|
||
ListSolidf Tables |
|
Specifies a solid line |
|
|
|
|
|
In addition to the preconfigured DashStyles, you are also able to define custom dash types using the DashPattern property of the Pen type: (see Figure 14-13 for complete output).
ISBN:1590590554
overview of the technical and
Table
C# and
Part
Chapter
Chapter
Part
Chapter
Chapter
Chapter
Chapter
Chapter
Chapter
Part Three - Programming with .NET Assemblies
Figure 14-13: Working with Pen types
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
// Draw custom dash pattern all around the boarder of the form.
Part Four - Leveraging the .NET Libraries
Pen customDashPen = new Pen(Color.BlueViolet, 5);
Chapter 12 - Object Serialization and the .NET Remoting Layer float[] myDashes = { 5.0f, 2 0f, 1.0f, 3.0f} ;
ChaptercustomDashPen13 - Building.DashPatternBetter Window=(IntroducingmyDashes;Windows Forms)
Chapterg.DrawRectangle(customDashPen,14 - A Better Painting Framework (GDI+)ClientRectangle);
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace
SOURCE The PenApp project is included under the Chapter 14 subdirectory.
Chapter 17 - Data Access with ADO.NET
CODE
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
ChapterWorking19 - ASPwith.NET WebPenApplicCapstions
Chapter 20 - XML Web Services
If you examined the output of the previous pen example, you should have noticed that the beginning and
Index
end of each line was rendered using a standard pen protocol (an end cap composed of 90 degree angles). Using the LineCap enumeration however, you are able to build Pens that exhibit a bit more flair. The core values of this enumeration are seen in Table 14-22.
Table 14-22: LineCap Values
|
|
|
|
|
|
|
|
|
|
|
|
LineCap ValuesC# and the |
|
|
.NETMeaningPlatform,in SecondLife |
Edition |
|
||
|
|
|
|
|
|
|
|
|
|
|
|
ArrowAnchor |
by Andrew |
|
Troelsen |
ISBN:1590590554 |
|||
|
|
Apress © 2003 |
|
|
Specifies an arrow-shaped cap |
|
|||
|
|
|
|
|
|
(1200 pages) |
|
|
|
|
|
DiamondAnchorThis comprehensiveSpecifiest xtastartsdiamondwithanchorbrief overviewcap |
of the |
||||||
|
|
|
|
|
|
|
|
||
|
|
Flat |
|
C# language |
|
and then quickly moves to key technical and |
|||
|
|
|
architectural |
|
|
issuSpecifiess for .aNETflatdevlineloperscap . |
|
||
|
|
|
|
|
|
|
|
|
|
|
|
Round |
|
|
|
|
Specifies a round line cap |
|
|
|
|
|
|
|
|
|
|
|
|
Table of Co |
tents |
|
|
|
Specifies a round anchor cap |
|
|||
|
|
RoundAnchor |
|
|
|
|
|||
|
|
|
|
|
|
||||
C# and the .NET Platform, Second Edition |
|
|
|||||||
|
|
Square |
|
|
|
|
Specifies a square line cap |
|
|
|
Introduction |
|
|
|
|
|
|
||
|
|
|
|
|
|
|
|||
Part One - I troducing C# and |
|
|
the .NET Platform |
|
|
||||
|
|
SquareAnchor |
|
|
|
Specifies no line cap |
|
|
|
|
|
|
|
|
|
|
|||
|
|
Chapter 1 - The Philosophy of |
|
|
.NET |
|
|
||
|
|
Triangle |
|
|
|
|
Specifies a triangular line cap |
|
|
|
|
Chapter 2 |
- Building C# Applications |
|
|
Part Two - The C# Programming Language
To illustrate, the following Pens application draws a series of lines using each of the LineCap styles. First,
Chapter 3 - C# Language Fundamentals
the result can be seen in Figure 14-14.
Chapter 4 - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime Chapter
Chapter
Chapter
Part
Chapter |
|
Chapter |
|
Chapter |
Based Programming |
Part |
|
Chapter |
Layer |
Chapter |
Forms) |
Chapter |
|
Chapter |
|
Chapter |
|
Chapter |
|
Part |
|
Chapter |
|
Chapter |
|
Chapter |
|
Index |
|
List of |
|
List of |
|
Figure 14-14: Working with pen caps
The code simply loops through each member of the LineCap enumeration, and prints out the name of the item (e.g., ArrowAnchor) and then configures and draws a line with the current cap:
private void MainForm_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Pen thePen |
= new Pen(Color.Black, 10); |
|
C# and the .NET Platform, Second Edition |
|
|
int yOffSet = 10; |
ISBN:1590590554 |
|
by Andrew Troelsen |
||
// Get all |
members of the LineCap enum. |
|
Apress © 2003 (1200 pages)
Array obj = Enum.GetValues(typeof(LineCap));
This comprehensive text starts with a brief overview of the
// Draw a line with a LineCap member.
C# language and then quickly moves to key technical and for(int x = 0; x < obj.Length; x++)
architectural issues for .NET developers.
{
// Get next cap and configure pen.
LineCap temp = (LineCap)obj.GetValue(x);
Table of Contents
thePen.StartCap = temp;
C# and the .NET Platform, Second Edition thePen.EndCap = temp;
Introduction
// Print name of LineCap enum.
Part One - Introducing C# and the .NET Platform
g.DrawString(temp.ToString(), new Font("Times New Roman", 10),
Chapter 1 - The Philosophy of .NET
new SolidBrush(Color.Black), 0, yOffSet);
Chapter 2 - Building C# Applications
// Draw a line with the correct cap.
Part Two - The C# Programming Language
g.DrawLine(thePen, 100, yOffSet, Width - 50, yOffSet);
Chapter 3 - C# Language Fundamentals
yOffSet += 40;
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
SOURCE The PenCapApp project is included under the Chapter 14 subdirectory.
Chapter 9 - Understanding .NET Assemblies
CODE
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
PartWorkingFour - Leveragingwith theSolid.NET LibBrushesaries
Chapter 12 - Object Serialization and the .NET Remoting Layer
So much for drawing lines. GDI+ Brush-derived types are used to fill the space between the lines, with a
Chapter 13 - Building a Better Window (Introducing Windows Forms)
given color, pattern, or image. Recall that the Brush class is an abstract type, and cannot be directly
Chapter 14 - A Better Painting Framework (GDI+)
created. Rather, this type serves as a base class to the other related brush types (for example, SolidBrush,
Chapter 15 - Programming with Windows Forms Controls
HatchBrush, LinearGradientBrush, and so forth). In addition to the aforementioned Brush-derived types, the System.Drawing namespace also defines two types that return a configured brush using a number of static properties: Brushes and SystemBrushes. Using a properly configured brush, you are able to call any number of methods [such as DrawString()], as well as the following set of FillXXXX() methods (Table 14-
Chapter 18 - ASP.NET Web Pages and Web Controls
23).
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services |
|
|
|
||
|
Table 14-23: Fill Methods of the Graphics Type |
||||
|
Index |
|
Meaning in Life |
|
|
ListFillof FiguresMethod of Graphics |
|
|
|||
ListClassof Tables |
|
|
|
||
|
|
|
|
|
|
|
|
FillClosedCurve() |
|
Fills the interior of a closed curve defined by an array of |
|
|
|
|
|
points |
|
|
|
|
|
|
|
|
|
FillEllipse() |
|
Fills the interior of an ellipse defined by a bounding |
|
|
|
|
|
rectangle |
|
|
|
|
|
|
|
|
|
FillPath() |
|
Fills the interior of a path |
|
|
|
|
|
|
|
|
|
FillPie() |
|
Fills the interior of a pie section |
|
|
|
|
|
|
|
|
|
FillPolygon() |
|
Fills the interior of a polygon defined by an array of points |
|
|
|
|
|
|
|
|
|
FillRectangle() |
|
Fills the interior of a rectangle (or a number of rectangles) |
|
|
|
FillRectangles() |
|
with a Brush |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
FillRegion() |
|
Fills the interior of a Region |
|
|
|
|
|
|
|
Also recall, that you are able to build a custom Pen type by making use of a given brush. In this way, you
C# and the .NET Platform, Second Edition
are able to build some brush of interest (for example, a brush that paints a bitmap image) and render
by Andrew Troelsen ISBN:1590590554
geometric patterns with configured Pen. To illustrate, here is a small sample program that makes use of
Apress © 2003 (1200 pages)
the SolidBrush and Brushes types [the output of this program (Figure 14-15) should look familiar...]
This comprehensive text starts with a brief overview of the
C# language and then quickly moves to key technical and
Table
C# and
Part
Chapter
Chapter
Part
Chapter
Chapter
Chapter
Chapter
Chapter
Chapter
Part
Chapter
Chapter
Chapter |
Based Programming |
Part
Chapter 12 - Object Serialization and the .NET Remoting Layer
Figure 14-15: Working with Brush types
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
If you can't tell, this application is little more than the original Pens application, making use of the
Chapter 15 - Programming with Windows Forms Controls
FillXXXX() methods and SolidBrush types, rather than pens and the related DrawXXXX() methods. Here is
Chapter 16 - The System.IO Namespace
the implementation of the paint handler:
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapterprivate18 -voidASP.NETMainFormWeb PagesPaint(objectnd Web Controlssender, PaintEventArgs e)
{
Chapter 19 - ASP.NET Web Applications
Graphics g = e.Graphics;
Chapter 20 - XML Web Services
Index // Make a blue SolidBrush.
SolidBrush blueBrush = new SolidBrush(Color.Blue);
List of Figures
// Get a stock brush from the Brushes type.
List of Tables
SolidBrush pen2 = (SolidBrush)Brushes.Firebrick;
// Render some shapes with the brushes.
g.FillEllipse(blueBrush, 10, 10, 100, 100); g.FillPie(Brushes.Black, 150, 10, 120, 150, 90, 80);
// Draw a purple polygon as well...
SolidBrush brush3= new SolidBrush(Color.Purple); g.FillPolygon(brush3, new Point[]{ new Point(30, 140),
new Point(265, 200), new Point(100, 225), new Point(190, 190), new Point(50, 330), new Point(20, 180)});
// And a rectangle with some text...
Rectangle r = new Rectangle(150, 10, 130, 60); g.FillRectangle(Brushes.Blue, r); g.DrawString("Hello out there...How are ya?",
new Font("Arial", 12), Brushes.White, r);
}
SOURCE
CODE
C# and the .NET Platform, Second Edition
by Andrew Troelsen |
ISBN:1590590554 |
Apress © 2003 (1200 pages)
ThisThecomprehensiveSolidBrushApptext startsprojectwisthincludeda brief overviewunder theof theChapter 14 subdirectory.
C# language and then quickly moves to key technical and architectural issues for .NET developers.
Working with Hatch Style Brushes
Table of Contents
The System.Drawing.Drawing2D namespace defines another Brush-derived type named HatchBrush.
C# and the .NET Platform, Second Edition
This type allows you to fill a region using a (very large) number of predefined patterns, represented by the
Introduction
HatchStyle enumeration. Here are some (but not all) of the hatch values (Table 14-24).
Part One - Introducing C# and the .NET Platform
Chapter 1 |
- The Philosophy of .NET |
|
|
||||
|
Table 14-24: Values of the HatchStyle Enumeration |
||||||
|
|
Chapter 2 |
- Building C# Applications |
|
|
|
|
|
|
|
|
|
|
||
Part Two - The C# Programming Language |
|
||||||
|
|
HatchStyle Enumeration |
Meaning in Life |
|
|||
ChapterValue3 |
- C# Language Fundamentals |
|
|||||
|
|
|
|
|
|
||
|
|
Chapter 4 |
- Object-Oriented Programming with C# |
|
|||
|
|
BackwardDiagonal |
Creates a brush consisting of backward diagonal lines |
|
|||
|
|
Chapter 5 |
- Exceptions and Object Lifetime |
|
|||
|
|
Cross |
- Interfaces and Collections |
|
|
Creates a brush consisting of horizontal and vertical crossing |
|
|
Chapter 6 |
|
|
|
|
||
|
Chapter 7 |
- Callback Interfaces, Delegates,linesand Events |
|
||||
|
|
|
|
|
|
||
|
|
Chapter 8 |
- Advanced C# Type Construction Techniques |
|
|||
|
|
DiagonalCross |
Creates a brush consisting of diagonal crossing lines |
|
|||
Part Three - Programming with .NET |
|
Assemblies |
|
||||
|
|
||||||
ChapterForwardDiagonal9 - Understanding .NET AssembliesCreates a brush consisting of forward diagonal lines |
|
||||||
|
|
|
|
|
|
||
|
|
Chapter 10 |
- Processes, AppDomains, |
|
Contexts, and Threads |
|
|
|
|
Hollow |
|
|
|
Configures a "hollow" brush that doesn't paint anything |
|
|
|
Chapter 11 |
- Type Reflection, Late Binding, and Attribute-Based Programming |
|
|||
|
|
|
|||||
PartHorizontalFour - Leveraging the .NET LibrariesCreates a brush consisting of horizontal lines |
|
||||||
|
|
|
|
|
|
||
|
|
Chapter 12 |
- Object Serialization and the .NET Remoting Layer |
|
|||
|
|
Pattern |
|
|
|
Creates a Brush with a pattern consisting of a custom bitmap |
|
|
|
Chapter 13 |
- Building a Better Window |
|
(Introducing Windows Forms) |
|
|
|
|
|
|
||||
|
ChapterSolid 14 |
- A Better Painting Framework |
|
Creates(GDI+)a solid colored brush (as an alternative to using the |
|
||
|
Chapter 15 |
- Programming with Windows |
|
SolidBrushForms Controlstype directly) |
|
||
|
|
|
|
|
|
|
|
|
|
Chapter 16 |
- The System.IO Namespace |
|
|
A brush consisting of vertical lines |
|
|
|
Vertical |
|
|
|
|
|
|
|
Chapter 17 |
- Data Access with ADO.NET |
|
|
|
|
Part Five - Web Applications and XML Web Services
In addition, when constructing a HatchBrush, you need to specify the foreground and background colors to
Chapter 18 - ASP.NET Web Pages and Web Controls
use during the fill operation. To illustrate, let's rework the logic seen previously from the PenCapApp
Chapter 19 - ASP.NET Web Applications
example. The output renders a filled oval for the first ten hatch values (Figure 14-16).
Chapter 20 - XML Web Services
Index
List of
List of
Figure 14-16: The hatch styles
Here is the code C#behinda dtheForm:.NET Platform, Second Edition
by Andrew Troelsen |
ISBN:1590590554 |
Apress © 2003 (1200 pages)
private void MainForm_Paint(object sender, PaintEventArgs e)
{This comprehensive text starts with a brief overview of the
C# language and then quickly moves to key technical and
Graphics g = e.Graphics;
architectural issues for .NET developers. int yOffSet = 10;
// Get all members of the HatchStyle enum.
Array obj = Enum.GetValues(typeof(HatchStyle));
Table of Contents
// Draw an oval with first 10 HatchStyle values.
C# and the .NET Platform, Second Edition for(int x = 0; x < 10; x++)
Introduction
{
Part One - Introducing C# and the .NET Platform
// Configure Brush.
Chapter 1 - The Philosophy of .NET
HatchStyle temp = (HatchStyle)obj.GetValue(x);
Chapter 2 - Building C# Applications
HatchBrush theBrush = new HatchBrush(temp,
Part Two - The C# Programming Language
Color.White, Color.Black
Chapter 3 - C# Language Fundamentals
// Print name of HatchStyle enum.
Chapter 4 - Object-Oriented Programming with C#
g.DrawString(temp.ToString(), new Font("Times New Roman", 10),
Chapter 5 - Exceptions and Object Lifetime
new SolidBrush(Color.Black), 0, yOffSet);
Chapter 6 - Interfaces// FillandaCollerectangleions with the correct brush.
Chapter 7 - Callbackg. FillEllipse(theBrush,Interfaces, Delegates, and Events150, yOffSet, 200, 25);
Chapter 8 - AdvancedyOffSetC#+=Type40;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
SOURCE The BrushStyles application is included under the Chapter 14 subdirectory.
Chapter 13 - Building a Better Window (Introducing Windows Forms)
CODE
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Working with Textured Brushes
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
Next, we have the TextureBrush type. This type allows you to attach a bitmap image to a brush, which can
Part Five - Web Applications and XML Web Services
then be used in conjunction with a fill operation. In just a few pages, you will learn about the details of the
Chapter 18 - ASP.NET Web Pages and Web Controls
GDI+ Image class. For the time being, understand that a TextureBrush is assigned an Image reference for
Chapter 19 - ASP.NET Web Applications
use during its lifetime. The image itself is typically found stored in some local file (*.bmp, *.gif, *.jpg) or
Chapter 20 - XML Web Services embedded into a .NET assembly.
Index
Let's build a sample application that makes use of the TextureBrush type. One brush is used to paint the
List of Figures
entire client area with the image found in a file named "clouds.bmp," while the other brush is used to paint
List of Tables
text with the image found within "soap bubbles.bmp" (yes, you can use TextureBrush types to render text as well!). The output is shown in Figure 14-17.
Figure 14-17: Bitmaps as brushes
C# and the .NET Platform, Second Edition
The code is very bysimpleAndrew. ToTroelsenbegin, your Form-derived class maintainsISBN:1590590554two abstract Brush types, which are
assigned to a newAprTextureBrushss © 2003 (1200inpagthes)constructor. Notice that the constructor of the TextureBrush type
requires a type derivedThis comprehensivefrom Image: text starts with a brief overview of the C# language and then quickly moves to key technical and
architectural issues for .NET developers.
public class MainForm : System.Windows.Forms.Form
{
// Note! These *.bmp files must be in the same folder
Table of Contents
// as the application (or specify hard coded paths).
C# and the .NET Platform, Second Edition
// We'll fix this limitation later in this chapter.
Introduction
Part One - Introducing C# and the .NET Platform
// Data for the image brush.
Chapter 1 - The Philosophy of .NET
private Brush texturedTextBrush;
Chapter 2 - Building C# Applications
private Brush texturedBGroundBrush;
Part Two - The C# Programming Language
public MainForm()
Chapter 3 - C# Language Fundamentals
{
Chapter 4 - Object-Oriented Programming with C# |
|
|
... |
Chapter 5 |
- Exceptions and Object Lifetime |
|
// Load image for background brush. |
Chapter 6 |
- Interfaces and Collections |
|
Image bGroundBrushImage = new Bitmap("Clouds.bmp"); |
Chapter 7 |
- Callback Interfaces, Delegates, and Events |
|
texturedBGroundBrush = new TextureBrush(bGroundBrushImage); |
Chapter 8 |
- Advanced C# Type Constructi n Techniques |
|
// Now load image for text brush. |
Part Three - ProgrammingImage textBrushImagewith .NET Assemblies= new Bitmap("Soap Bubbles.bmp");
Chapter 9 - UnderstexturedTextBrushanding .NET Assemblies= new TextureBrush(textBrushImage);
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)
Now that you have two TextureBrush types to render with, the paint handler should be a no-brainer:
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
private void MainForm_Paint(object sender, PaintEventArgs e)
Chapter 16 - The System.IO Namespace
{
Chapter 17 - Data Access with ADO.NET
Graphics g = e.Graphics;
Part Five - Web Applications and XML Web Services
Rectangle r = ClientRectangle;
Chapter 18 - ASP.NET Web Pages and Web Controls
// Paint the clouds on the client area.
Chapter 19 - ASP.NET Web Applications g.FillRectangle(texturedBGroundBrush, r);
Chapter 20 - XML Web Services
// Some big bold text with a textured brush.
Index g.DrawString("Bitmaps as brushes! Way cool...",
List of Figures |
new Font("Arial", 60, |
|
List of Tables |
||
FontStyle.Bold | FontStyle.Italic), |
||
|
||
|
texturedTextBrush, |
|
} |
r); |
|
|
Not bad at all huh? For those of you who have spent time achieving the same effects using the raw Win32 API (or even MFC for that matter), you should be quite pleased with the minimal amount of work required to achieve rather complex results. Now, before moving on to a discussion of image manipulation, there is one final brush typeto consider.
SOURCE The TexturedBrushes application is included under the Chapter 14 subdirectory.
CODE
Working with Gradient Brushes
Last but not least, there is the LinearGradientBrush type, which can be used whenever you want to blend
C# and the .NET Platform, Second Edition
two colors together in a gradient pattern. Working with this type is just as simple as working with the other
by Andrew Troelsen ISBN:1590590554
brush types. The only point of interest is that when building a LinearGradientBrush, you need to specify the
Apress © 2003 (1200 pages)
direction of the blend, using a value from the LinearGradientMode enumeration (Table 14-25).
This comprehensive text starts with a brief overview of the
C# language and then quickly moves to key technical and
Table 14-25: LinearGradientMode Enumeration architectural issues for .NET developers.
|
LinearGradientMode Value |
|
Meaning in Life |
|
|
|
|
|
|
|
|
TableBackwardDiagonalof Contents |
|
Specifies a gradient from upper right to lower left |
|
||
|
|
|
|
|
|
C# and the .NET Platform, Second Edition |
|
Specifies a gradient from upper left to lower right |
|
||
|
ForwardDiagonal |
|
|
||
|
Introduction |
|
|
|
|
|
|
|
|
||
|
|
|
|
||
PartHorizontalOne - Introducing C# and the .NET |
PlatformSpecifies a gradient from left to right |
|
|||
|
|
|
|
|
|
|
Chapter 1 |
- The Philosophy of .NET |
|
Specifies a gradient from top to bottom |
|
|
Vertical |
|
|
|
|
|
Chapter 2 |
- Building C# Applications |
|
|
|
|
|
|
|
Part Two - The C# Programming Language
To test each type, let's make use of the System.Enum class yet again, and draw a series of rectangles
Chapter 3 - C# Language Fundamentals
using a LinearGradientBrush. The output is seen in Figure 14-18.
Chapter 4 - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime Chapter
Chapter
Chapter
Part |
|
Chapter |
|
Chapter |
and Threads |
Chapter |
and Attribute-Based Programming |
Part |
|
Chapter |
Remoting Layer |
Chapter |
(Introducing Windows Forms) |
Chapter |
(GDI+) |
Chapter |
Forms Controls |
Figure 14-18: Gradient brushes at work
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
Now the code, which I assume requires little comment at this point:
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
private void MainForm_Paint(object sender, PaintEventArgs e)
Chapter 19 - ASP.NET Web Applications
{
Chapter 20 - XML Web Services
Index Graphics g = e.Graphics;
Rectangle r = new Rectangle(10, 10, 100, 100);
List of Figures
// A gradient brush.
List of Tables
LinearGradientBrush theBrush = null; int yOffSet = 10;
// Get all members of the LinearGradientMode enum.
Array obj = Enum.GetValues(typeof(LinearGradientMode));
// Draw an oval with a LinearGradientMode member.
for(int x = 0; x < obj.Length; x++)
{
// Configure Brush.
LinearGradientMode temp = (LinearGradientMode)obj.GetValue(x); theBrush = new LinearGradientBrush(r, Color.GreenYellow,
Color.Blue, temp);
// Print name of LinearGradientMode enum.
g.DrawString(temp.ToString(), new Font("Times New Roman", 10), new SolidBrush(Color.Black), 0, yOffSet);
//Fill a rectangle with the correct brush.
g. FillRectangle(theBrush, 150, yOffSet, 200, 50);
yOffSet += 80;
} |
C# and the .NET Platform, Second Edition |
|
|
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 |
||
SOURCE |
architectural issues for .NET developers. |
|
|
The GradientBrush application is included under the Chapter 14 subdirectory. |
CODE
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
Rendering C#Imagesnd the .NET Platform, Second Edition
by Andrew Troelsen |
ISBN:1590590554 |
At this point you have examined how to manipulate three of the four major GDI+ types (fonts, pens, and
Apress © 2003 (1200 pages)
brushes). The final type you examine in this chapter is the Image class, and related subtypes. The abstract
This comprehensive text starts with a brief overview of the
System.Drawing.C#Imagelanguagetype definesand thena numberq ickly movesof methodso keyandtechnicalpropertiesand that hold various bits of information regardingarchitecturalthe underlyingissues forpixel.NETsetdevelopit representsrs. . For example, the Image class supplies the Width, Height, and Size properties to retrieve the dimensions of the image. Other properties allow you to gain access to the underlying palette. The Image class defines the core members shown in Table 14-26.
Table of Contents
C# and the .NET Platform, Second Edition |
|||||||||
|
Table 14-26: Members of the Image Type |
||||||||
|
|
Introduction |
|
|
|
|
|
|
|
|
|
C# andMeaningthe .NET Platformin Life |
|
|
|||||
PartImageOne - IntroducingMember |
|
|
|||||||
|
ChapterName1 |
- The Philosophy |
|
of .NET |
|
|
|||
|
|
|
|
|
|
||||
|
|
Chapter 2 |
- Building C# |
Applications |
|
|
|||
|
|
FromFile() |
|
|
|
This static method creates an Image from the specified file. |
|
|
|
Part Two - The C# Programming |
|
Language |
|
|
|||||
|
|
||||||||
|
ChapterFromHbitmap()3 - C# Language |
|
|
FundamentalsThis static method creates a Bitmap from a Windows handle. |
|
|
|||
|
|
||||||||
|
|
Chapter 4 |
- Object-Oriented |
|
|
Programming with C# |
|
|
|
|
|
FromStream() |
|
|
|
This static method creates an Image from the specified data stream. |
|
|
Chapter 5 - Exceptions and Object Lifetime
Height These properties return information regarding the dimensions of this
Chapter 6 - Interfaces and Collections
Image.
ChapterWidth7 - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques
Size
Part Three - Programming with .NET Assemblies
PhysicalDimensions
Chapter 9 - Understanding .NET Assemblies
HorizontalResolution
Chapter 10 - Processes, AppDomains, Contexts, and Threads
ChapterVerticalResolution11 - Type Reflection, Late Binding, and Attribute-Based Programming
|
|
|
|
|
Part Four - Leveraging the .NET Libraries |
|
|||
|
Palette |
|
This property returns a ColorPalette data type that represents the |
|
Chapter 12 - Object Serialization and the .NET Remoting Layer |
|
|||
|
|
|
underlying palette used for this Image. |
|
|
Chapter 13 - Building a Better |
|
Window (Introducing Windows Forms) |
|
|
|
|
||
|
ChapterGetBounds()14 - A Better Painting |
|
ReturnsFrameworkRectangle(GDI+) that represents the current size of this Image. |
|
|
|
|
|
|
|
Chapter 15 - Programming with Windows Forms Controls |
|
||
|
Save() |
|
Saves the data held in an Image-derived type to file. |
|
|
Chapter 16 - The System.IO |
|
Namespace |
|
Chapter 17 - Data Access with ADO.NET |
PartGivenFivethat- Webthe Applicationsabstract ImageandclassXML WebcannotServicesbe directly created, you typically make a direct instance of the
ChapterBitmap18type- .ASPFor.NETexample,Web Passumeges and youWebhaveContrsomels Form-derived class that renders three bitmaps into the
Chapterclient area19 -. ToASPbegin,.NET WebyouApplicationsmay create three private Image data members, each of which is assigned to a Chaptergiven *.20bmp- XMLfile onWebstartupServices(again, be sure these files are located in the application directory):
Index
Listpublicof F guresclass MainForm : System.Windows.Forms.Form
List{ of Tables
// The images.
private Bitmap bMapImageA; private Bitmap bMapImageB; private Bitmap bMapImageC; public MainForm()
{
...
// Fill the images with bitmaps.
bMapImageA = new Bitmap("imageA.bmp");
bMapImageB = new Bitmap("imageB.bmp");
bMapImageC = new Bitmap("imageC.bmp");
}
...
}
C# and the .NET Platform, Second Edition
Rendering these items from within the context of a paint handler is easy as could be, given that the
by Andrew Troelsen ISBN:1590590554
Graphics class has a member named (appropriately enough) DrawImage(). This method has been
Apress © 2003 (1200 pages)
overloaded numerous times to provide various ways to place the image onto the drawing surface. For
This comprehensive text starts with a brief overview of the
example, you may specify optional ImageAttributes and GraphicsUnit enumerations. For your purposes, all
C# language and then quickly moves to key technical and
you need to do is specify the location at which to render each image (which may be defined using Point, architectural issues for .NET developers.
Rectangles, integers, or floats):
Tableprotectedof Contentsvoid OnPaint (object sender, System.Windows.Forms.PaintEventArgs e)
C#{ and the .NET Platform, Second Edition
IntroductionGraphics g = e.Graphics;
Part One//- IntroducingRender allC# andthreethe .NETimagesPlatform.
g.DrawImage(bMapImageA, 10, 10, 90, 90);
Chapter 1 - The Philosophy of .NET
g.DrawImage(bMapImageB, 10, 110, 90, 90);
Chapter 2 - Building C# Applications
g.DrawImage(bMapImageC, 10, 210, 90, 90);
Part Two - The C# Programming Language
}
Chapter 3 - C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime
The result can be seen in Figure 14-19.
Chapter 6 - Interfaces and Collections
Chapter 7 - Callback Interfaces, Delegates, and Events
Chapter |
Construction Techniques |
Part |
Assemblies |
Chapter |
Assemblies |
Chapter |
Contexts, and Threads |
Chapter |
Binding, and Attribute-Based Programming |
Part |
|
Chapter |
the .NET Remoting Layer |
Chapter |
(Introducing Windows Forms) |
Chapter |
(GDI+) |
Chapter |
Forms Controls |
Chapter |
|
Chapter |
NET |
Part |
Web Services |
Chapter |
Web Controls |
Chapter |
|
Chapter |
|
Index |
|
List of |
|
List of |
|
Figure 14-19: Rendering images
Also be aware that regardless of the name given to the Bitmap type, you are able to load in images stored in any number of file formats. For example:
// The Bitmap type can hold work with any number of file formats!
Bitmap myBMP = new Bitmap("CoffeeCup.bmp");
Bitmap myGIF = new Bitmap("Candy.gif");
Bitmap myJPEG = new Bitmap("Clock.jpg");
Bitmap myPNG = new Bitmap("Speakers.png");
Bitmap myTIF = new Bitmap("FooFighters.tif");
// Now render each onto the Graphics context.
g.DrawImage(myBMP, 10, 10);
g.DrawImage(myGIF, 220, 10);
g.DrawImage(myJPEG, 280, 10);
|
C# and the .NET Platform, Second Edition |
|
g.DrawImage(myPNG, 150, 200); |
ISBN:1590590554 |
|
|
by Andrew Troelsen |
|
g.DrawImage(myTIF, 300, 200); |
|
|
|
Apress © 2003 (1200 pages) |
|
|
This comprehensive text starts with a brief overview of the |
|
|
C# language and then quickly moves to key technical and |
|
SOURCE |
architectural issues for .NET developers. |
|
The Images application is included under the Chapter 14 subdirectory. |
CODE
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
Dragging, HitC# andTesting,the .NET Platform,and theSecondPictureBoxEdition Control
by Andrew Troelsen |
ISBN:1590590554 |
While you are free to render Bitmap images directly onto a Control-derived type (such as a Form), you will
Apress © 2003 (1200 pages)
find that you gain far greater control and functionality if you instead choose to create a PictureBox type to
This comprehensive text starts with a brief overview of the
hold your image onC#yourlanguagebehalfand. Therethen quicklyare numerousoves toreasonskey technicalto do soand. First, because the PictureBox type derives from Control,a chitecturalyou inheritissuesa greatfor .NETdealdevelopersof functionality,. such as the ability to capture a number of events for a particular image, assign a tool tip or context menu, and numerous other details. While you could achieve similar behaviors using a raw Bitmap, you would be required to add a fair amount of
Table of Contents boilerplate code.
C# and the .NET Platform, Second Edition
To illustrate the usefulness of the PictureBox type, let's create an application that illustrates the ability to
Introduction
capture MouseUp, MouseDown, and MouseMove events from a graphical image contained in a
Part One - Introducing C# and the .NET Platform
PictureBox.
Chapter 1 - The Philosophy of .NET
Chapter 2 - Building C# Applications
If users click the mouse somewhere within the bounds of the image, they are in "dragging" mode and can
Part Two - The C# Programming Language
move the image around the Form. To make things more interesting, let's monitor where they release the
Chapter 3 - C# Language Fundamentals
image. If it is within the bounds of a GDI+rendered rectangle, we take some additional course of action
Chapter 4 - Object-Oriented Programming with C#
(seen shortly). As you may know, the process of testing for mouse Click events within the context of a
Chapter 5 - Exceptions and Object Lifetime region of the screen is termed "hit testing."
Chapter 6 - Interfaces and Collections
ChapterWhen it7comes- Callbackto theInterfaces,functionalityDelegates,providedandbyEvthentsPictureBox type, there is little to say, as all of the
necessary functionality comes from the Control base class. Given that you have already explored a
Chapter 8 - Advanced C# Type Construction Techniques
number of the members for these types, you can quickly turn your attention to the process of assigning an
Part Three - Programming with .NET Assemblies
image to the PictureBox member variable:
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapterpublic11class- Type Reflection,MainFormLate: Binding,Systemand.WindowsAttribute.-FormsBased Programming.Form
Part{ Four - Leveraging the .NET Libraries
// This holds an image of a smiley face.
Chapter 12 - Object Serialization and the .NET Remoting Layer
private PictureBox happyBox;
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
// Configure the PictureBox.
Chapter 16 - The System.IO Namespace
happyBox = new PictureBox();
Chapter 17 - Data Access with ADO.NET
happyBox.SizeMode = PictureBoxSizeMode.StretchImage;
Part Five - Web Applications and XML Web Services
happyBox.Location = new System.Drawing.Point(64, 32);
Chapter 18 - ASP.NET Web Pages and Web Controls
happyBox.Size = new System.Drawing.Size(50, 50);
Chapter 19 - ASP.NET Web Applications happyBox.Cursor = Cursors.Hand;
Chapter 20 - XML Web Services
happyBox.Image = new Bitmap("happy.bmp");
Index
// Now add to the Form's Controls collection.
List of Figures Controls.Add(happyBox);
List of Tables
}
...
}
The only point of interest is the SizeMode property, which makes use of the PictureBoxSizeMode enumeration. This type is used to control how the associated image should be rendered within the bounding rectangle of the PictureBox. Here, you assigned StretchImage, indicating that you wish to skew the image over the entire client area. Other possible values appear in Table 14-27.
Table 14-27: The PictureBoxSizeMode Enumeration
|
PictureBoxSizeModeC# and the .NET |
|
|
Platform,Meaning Secondin LifeEdition |
|
|
|
|
Member Nameby Andrew Troelsen |
|
ISBN:1590590554 |
|
|||
|
|
|
|
|
|
|
|
|
AutoSize |
Apress © 2003 (1200 |
|
pages) |
|
|
|
|
This comprehensive |
|
|
The PictureBox is sized equal to the size of the image that it |
|
||
|
|
|
|
text starts with a brief overview of the |
|
||
|
|
|
|
|
contains. |
|
|
|
|
C# language and |
|
|
then quickly moves to key technical and |
|
|
|
|
|
|
||||
|
CenterImage |
architectural issues |
for .NET developers. |
|
|
||
|
|
|
|
The image is displayed in the center if the PictureBox is larger |
|
||
|
|
|
|
|
than the image. If the image is larger than the PictureBox, the |
|
|
Table of Contents |
|
|
|
picture is placed in the center of the PictureBox and the outside |
|
||
|
|
|
edges are clipped. |
|
|
||
|
|
|
|
|
|
|
|
C# and the .NET Platform, Second |
|
Edition |
|
|
The image is located in the upper left corner of the PictureBox. If Part One - Introducing C# and the .NETthePlatformPictureBox is smaller than the image, it will be clipped.
Chapter 1 - The Philosophy of .NET
Now that you have configured the initial look and feel of the PictureBox, you need to hook up some
Chapter 2 - Building C# Applications
handlers for the MouseMove, MouseUp, and MouseDown events. This is simple, as PictureBox "is-a"
Part Two - The C# Programming Language
Control. Thus, you can update your constructor logic as follows:
Chapter 3 - C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C#
Chapter// Add5 handlers- Exceptionsforand ObjthectfollowingLifetime events.
happyBox.MouseDown += new MouseEventHandler(happyBox_MouseDown);
C pter 6 - Interfaces and Collections
happyBox.MouseUp += new MouseEventHandler(happyBox_MouseUp);
Chapter 7 - Callback Interfaces, Delegates, and Events
happyBox.MouseMove += new MouseEventHandler(happyBox_MouseMove);
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
The logic behind MouseDown stores the incoming (x,y) location of the mouse click for later use, and sets
Chapter 10 - Processes, AppDomains, Contexts, and Threads
a Boolean member variable (isDragging) to true, to indicate that a drag operation is in process.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
// Mouse event handler to initiate dragging the pictureBox around.
Chapter 12 - Object Serialization and the .NET Remoting Layer
private void happyBox_MouseDown(object sender, MouseEventArgs e)
Chapter 13 - Building a Better Window (Introducing Windows Forms)
{
Chapter 14 - A Better Painting Framework (GDI+) isDragging = true;
Chapter 15 - Programming with Windows Forms Controls
// Save the (x, y) of the mouse down click,
Chapter 16 - The System.IO Namespace
// because we need it as an offset when dragging the image.
Chapter 17 - Data Access with ADO.NET oldX = e.X;
Part Five - Web Applications and XML Web Services
oldY = e.Y;
Chapter 18 - ASP.NET Web Pages and Web Controls
}
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
The MouseMove handler simply relocates the position of the PictureBox (using the Top and Left
Index
properties) by offsetting the current cursor location with the (x,y) position captured when the mouse went
List of Figures
down.
List of Tables
//If the user clicks the image and moves the mouse,
//redraw the image at the new location.
private void happyBox_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging)
{
//Need to figure new Y value based on where the mouse
//down click happened.
happyBox.Top = happyBox.Top + (e.Y - oldY);
// Same deal for X (use oldX as a base line).
happyBox.Left = happyBox.Left + (e.X - oldX);
}
}
Finally, MouseUp sets the isDragging Boolean to false, to signal the end of the drag operation. Recall
C# and the .NET Platform, Second Edition
however, that this application has one extra point of logic. If the MouseUp event occurs when the
by Andrew Troelsen ISBN:1590590554
PictureBox is contained within a GDI+ Rectangle object, you can assume the user has won the game
Apress © 2003 (1200 pages)
(albeit a rather lame game...). That said, here is the remainder of the Form's logic:
This comprehensive text starts with a brief overview of the
C# language and then quickly moves to key technical and
// When the mouse goes up, they are done dragging. archit ctural iss es for .NET developers.
// See if they dropped the image in the rectangle...
private void happyBox_MouseUp(object sender, MouseEventArgs e)
Table{ of Contents
C# and theisDragging.NET Platform,= Secondfalse;Edition
// Is the mouse within the area of the drop rect?
Introduction
if(dropRect.Contains(happyBox.Bounds))
Part One - Introducing C# and the .NET Platform
MessageBox.Show("You win!", "What an amazing test of skill...");
Chapter 1 - The Philosophy of .NET
}
Chapter 2 - Building C# Applications
Part Two - The C# Programming Language
// Assume we have a private Rectangle configured as follows:
Chapter 3 - C# Language Fundamentals
// Rectangle dropRect = new Rectangle(100, 100, 150, 150);
Chapter 4 - Object-Oriented Programming with C#
private void MainForm_Paint(object sender, PaintEventArgs e)
Chapter 5 - Exceptions and Object Lifetime
{
Chapter 6 - Interfaces and Collections
// Draw the drop box.
Chapter 7 - Callback Interfaces, Delegates, and Events
Graphics g = e.Graphics;
Chapter 8 - Advanced C# Type Construction Techniques g.FillRectangle(Brushes.AntiqueWhite, dropRect);
Part Three - Programming with .NET Assemblies
// Display instructions.
Chapter 9 - Understanding .NET Assemblies
g.DrawString("Drag the happy guy in here...",
Chapter 10 - Processes, AppDomains, Contexts, and Threads
new Font("Times New Roman", 25), Brushes.Red, dropRect);
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
As a reminder, it is worth pointing out that the Rectangle type defines the Contains() method that has been
Chapter 13 - Building a Better Wi dow (Introducing Windows Forms)
overloaded to test for contained Rectangle, Point, or two integer values. This member can be quite helpful
Chapter 14 - A Better Painting Framework (GDI+)
when calculating if a mouse click has occurred within a given rectangular region (as seen in the MouseUp
Chapter 15 - Programming with Windows Forms Controls
event handler). When you run the application, you are presented with what appears in Figure 14-20.
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
Part
Chapter
Chapter
Chapter
Index
List of
List of
Figure 14-20: The amazing happy-dude game
If you have what it takes to win the game, you are rewarded with the kudos shown in Figure 14-21.
Second Edition
|
ISBN:1590590554 |
|
with a brief overview of the |
|
moves to key technical and |
|
developers. |
Figure 14-21: You have nerves of steel... |
|
Table of Contents |
The DraggingImages application is included under the Chapter 14 subdirectory. |
SOURCE |
C# and the .NET Platform, Second Edition
CODE
Introduction
Part One - Introducing C# and the .NET Platform
ChapterMore1 Hit- TheTestingPhilosophyDetailsof .NET
Chapter 2 - Building C# Applications
Validating a hit test against a Control-derived type (such as a PictureBox) is very simple, as each can
Part Two - The C# Programming Language
respond to mouse events directly. However, what if you wish to perform a hit test on a geometric shape
Chapter 3 - C# Language Fundamentals
such as a region rendered on the screen using a raw GDI+ object? To illustrate, let's revisit the previous
Chapter 4 - Object-Oriented Programming with C#
Images application, and add some additional functionality.
Chapter 5 - Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections
The goal is to determine when the user clicks a given image (which as you recall was not rendered within
Chapter 7 - Callback Interfaces, Delegates, and Events
a PictureBox control). Once you discover which image was clicked, adjust the Text property of the Form,
Chapterand highlight8 - Advancedthe imageC#withTypea 5Construction-pixel outlineTechniques.
Part Three - Programming with .NET Assemblies
The first step is to intercept the MouseDown event for the Form itself. When the event occurs, you need to
Chapter 9 - Understanding .NET Assemblies
programmatically figure out if the incoming (x,y) coordinate is somewhere within the bounds of the
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Rectangles used to represent the dimension of each Image. If the user does click a given image, you set a
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
private Boolean member variable (isImageClicked) to true, and indicate which image was selected via
Part Four - Leveraging the .NET Libraries
another member variable (of type integer):
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
public class MainForm : System.Windows.Forms.Form
Chapter 14 - A Better Painting Framework (GDI+)
{
Chapter 15 - Programming with Windows Forms Controls
...
Chapter 16 - The System.IO Namespace
// Did they click an image?
Chapter 17 - Data Access with ADO.NET
private bool isImageClicked = false;
Part Five - Web Applications and XML Web Services
private int imageClicked;
Chapter 18 - ASP.NET Web Pages and Web Controls
protected void OnMouseDown (object sender, MouseEventArgs e)
Chapter 19 - ASP.NET Web Applications
{
Chapter 20 - XML Web Services
// Get (x, y) of mouse click.
Index
List of Figures
List of Tables
Point mousePt = new Point(e.X, e.Y);
// See if the mouse is anywhere in the 3 regions...
if(rectA.Contains(mousePt))
{
isImageClicked = true; imageClicked = 0;
this.Text = "You clicked image A";
}
else if(rectB.Contains(mousePt))
{
isImageClicked = true; imageClicked = 1;
this.Text = "You clicked image B";
}
else if(rectC.Contains(mousePt))
{
isImageClicked = true; imageClicked = 2;
this.Text = "You clicked image C";
} |
C# and the .NET Platform, Second Edition |
|
|
by Andrew Troelsen |
ISBN:1590590554 |
||
else |
// Not in any shape, set defaults. |
||
{ |
Apress © 2003 (1200 pages) |
|
This comprehensive text starts with a brief overview of the isImageClicked = false;
C# language and then quickly moves to key technical and this.Text = "Images";
architectural issues for .NET developers.
}
// Redraw the client area.
Invalidate();
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 conditionalC# Applic tions
Notice that the final check sets the isImageClicked member variable to false, indicating that the PartuserTwodid-notTheclickC# Programmingone of your threeLanguageimages. This is important, as you want to erase the outline of the Chapterpreviously3 -selectedC# LanguageimageFundamentals. Once all items have been checked, invalidate the client area. Here is the
Chapterupdated4 Paint- Objecthandler:-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections
private void MainForm_Paint(object sender, PaintEventArgs e)
Chapter 7 - Callback Interfaces, Delegates, and Events
{
Chapter Graphics8 - Advancedg C#= eType.Graphics;Construction Techniques
Part Three//- ProgrammingRender allwithree.NET imagesAssemblies.
Chapter ...9 - Understanding .NET Assemblies
Chapter //10 -DrawP ocesses,outlineAppDomains,(if clickedContexts,...and)Threads
if(isImageClicked == true)
Chapter 11 - Type Reflect on, Late Binding, and Attribute-Based Programming
{
Part Four - Leveraging the .NET Libraries
Pen outline = new Pen(Color.Red, 5);
Chapter 12 - Object Serialization and the .NET Remoting Layer
switch(imageClicked)
Chapter 13 - Building a Better Window (Introducing Windows Forms)
{
Chapter 14 - A Better Painting Framework (GDI+)
case 0:
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace break;
Chapter 17 - Data Access with ADO.NET case 1:
Part Five - Web Applications and XML Web Services
g.DrawRectangle(outline, rectB);
Chapter 18 - ASP.NET Web Pages and Web Controls break;
Chapter 19 - ASP.NET Web Applications |
||
|
case 2: |
|
Chapter 20 - XML Web Services |
||
Index |
g.DrawRectangle(outline, rectC); |
|
break; |
||
List of Figures |
||
default: |
||
|
||
List of Tables |
break; |
|
|
||
} |
} |
|
|
||
} |
|
Hit Testing Nonrectangular Images
Now, what if you wish to perform a hit test in a nonrectangular region, rather than a simple square? Assume you updated your application to render an oddball geometric shape that will also sport an outline when clicked (Figure 14-22).
Second Edition
ISBN:1590590554
starts with a brief overview of the
moves to key technical and
developers.
Table
C# and
Part
Chapter
Chapter
Figure 14-22: Hit-testing polygons
Part Two - The C# Programming Language
Chapter 3 - C# Language Fundamentals
This geometric image was rendered on the Form using the FillPath() method of the Graphics type. This
Chapter 4 - Object-Oriented Programming with C#
method takes an instance of a GraphicsPath object, which was mentioned earlier during your examination
Chapter 5 - Exceptions and Object Lifetime
of the System.Drawing.Drawing2D namespace. The GraphicsPath object encapsulates a series of
Chapter 6 - Interfaces and Collections
connected lines, curves, and (interestingly enough) strings. Adding new items to a GraphicsPath instance
Chapter 7 - Callback Interfaces, Delegates, and Events |
|||||||
|
is achieved using a number of related "add" methods (Table 14-28). |
||||||
Chapter 8 - Advanced C# Type Construction Techniques |
|||||||
Part Three - Programmi |
g with .NET Assemblies |
||||||
|
Table 14-28: Add-Centric Methods of the GraphicsPath Class |
||||||
|
|
|
|
|
|
|
|
|
|
Chapter 9 - Understanding .NET Assemblies |
|
|
|||
|
|
ChapterGraphicsPath10 - Processes,"Add"AppDomains, Contexts,MeaningandinThreadsLife |
|
|
|||
|
|
ChapterMethod11 - Type Reflection, Late Binding, and Attribute-Based Programming |
|
|
|||
|
|
|
|||||
|
|
|
|
|
|
|
|
Part Four - Leveraging the .NET Libraries |
Appends an elliptical arc to the current figure |
|
|
||||
|
|
AddArc() |
|
|
|
|
|
|
|
||||||
|
|
Chapter 12 - Object Serialization and the .NET Remoting Layer |
|
|
|||
|
|
AddBezier() |
|
|
Adds a cubic Bezier curve (or set of Bezier curves) to the |
|
|
|
Chapter 13 - Building a Better Window (Introducing Windows Forms) |
|
|
||||
|
|
|
|
|
current figure |
|
|
|
ChapterAddBeziers()14 - Better Painting Framework (GDI+) |
|
|
||||
|
|
|
|
|
|||
|
|
Chapter 15 - Programming with Windows |
Forms Controls |
|
|
||
|
|
AddClosedCurve() |
|
|
Adds a closed curve to the current figure |
|
|
|
|
Chapter 16 - The System.IO Namespace |
|
|
|
|
|
|
ChapterAddCurve()17 - Data Access with ADO.NET |
|
Adds a curve to the current figure |
|
|
||
|
|
|
|
|
|||
Part Five - Web Applications and XML |
|
Web Services |
|
|
|||
|
|
AddEllipse() |
|
|
Adds an ellipse to the current figure |
|
|
|
Chapter 18 - ASP.NET Web Pages and |
|
Web Controls |
|
|
||
|
|
|
|
|
|||
|
ChapterAddLine()19 - ASP.NET Web Applications |
|
Appends a line segment to the current figure |
|
|
||
|
Chapter 20 - XML Web Services |
|
|
|
|
||
|
|
AddLines() |
|
|
|
|
|
|
|
|
|
|
|
|
|
Index |
|
|
Appends the specified GraphicsPath to the current figure |
|
|
||
|
|
AddPath() |
|
|
|
|
|
List of Figures |
|
|
|
|
|
||
|
|
|
|
|
|||
|
|
AddPie() |
|
|
Adds the outline of a pie shape to the current figure |
|
|
List of Tables |
|
|
|
|
|
||
|
|
|
|
|
|
|
|
|
|
AddPolygon() |
|
|
Adds a polygon to the current figure |
|
|
|
|
|
|
|
|
||
|
|
AddRectangle() |
|
|
Adds one (or more) rectangle to the current figure |
|
|
|
|
AddRectangles() |
|
|
|
|
|
|
|
|
|
|
|
||
|
|
AddString() |
|
|
Adds a text string to the current figure |
|
|
|
|
|
|
|
|
|
|
Assume that you have added a private GraphicsPath member variable to your current Images application. In the Form's constructor, build the set of items that represent your path as follows:
public MainForm : System.Windows.Forms.Form
{
GraphicsPath myPath = new GraphicsPath();
public MainForm()
{
C# and the .NET Platform, Second Edition |
|
// Create an interesting region. |
ISBN:1590590554 |
by Andrew Troelsen |
|
myPath.StartFigure(); |
|
Apress © 2003 (1200 pages)
myPath.AddLine(new Point(150, 10), new Point(120, 150));
This comprehensive text starts with a brief overview of the myPath.AddArc(200, 200, 100, 100, 0, 90);
C# language and then quickly moves to key technical and
Point point1 = new Point(250, 250); architectural issues for .NET developers.
Point point2 = new Point(350, 275); Point point3 = new Point(350, 325);
Point point4 = new Point(250, 350);
Table of Contents
Point[] points = { point1, point2, point3, point4} ;
C# and the .NET Platform, Second Edition myPath.AddCurve(points);
Introduction
myPath.CloseFigure();
Part One - Introducing C# and the .NET Platform
...
Chapter 1 - The Philosophy of .NET
}
Chapter 2 - Building C# Applications
}
Part Two - The C# Programming Language
Chapter 3 - C# Language Fundamentals
ChapterNotice 4the-callsObjectto-StartFigure()Oriented Programmingand CloseFigure()with C# . When you call StartFigure(), you are able to insert a
Chapternew item5 into- Exceptionsthe currentandpathObjectyouLifetimeare building. A call to CloseFigure() closes the current figure and begins Chaptera new figure6 - Interfaces(if you requireand Cone)ll ctions. If the figure contains a sequence of connected lines and curves (as in the
case of the myPath instance), the loop is closed by connecting a line from the endpoint to the starting
Chapter 7 - Callback Interfaces, Delegate , and Events
point.
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
There are more members for System.Drawing.Drawing2D.GraphicsPath, but let's keep focused on the hit-
Chapter 9 - Understanding .NET Assemblies
testing logic. The next step would be to update your existing MouseDown event handler to test for the
Chapter 10 - Processes, AppDomains, Contexts, and Threads
presence of the cursor's (x,y) position within the bounds of the GraphicsPath. Like a Region type, this can
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming be discovered using the IsVisible() member:
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
protected void OnMouseDown (object sender, MouseEventArgs e)
Chapter 13 - Building a Better Window (Introducing Windows Forms)
{
Chapter 14 - A Better Painting Framework (GDI+)
// Get (x, y) of mouse click.
Chapter 15 - Programming with Windows Forms Controls
Point mousePt = new Point(e.X, e.Y);
Chapter 16 - The System.IO Namespace
...
Chapter 17 - Data Access with ADO.NET
else if(myPath.IsVisible(mousePt))
Part Five{- Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
isImageClicked = true;
Chapter 19 - ASP.NET Web Applications
imageClicked = 3;
Chapter 20 - XMLthisWeb.TextServices= "You clicked the strange shape...";
Index }
List...of Figures
}
List of Tables
Finally, you can update the Paint handler as follows:
private void MainForm_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
...
//Draw the graphics path. g.FillPath(Brushes.AliceBlue, myPath);
//Draw outline (if clicked...) if(isImageClicked == true)
{
Pen outline = new Pen(Color.Red, 5); switch(imageClicked)
{ |
C# and the .NET Platform, Second Edition |
|
|
... |
ISBN:1590590554 |
|
by Andrew Troelsen |
|
|
case 3: |
|
|
Apress © 2003 (1200 pages) |
|
|
g.DrawPath(outline, myPath); |
|
|
This comprehensive text starts with a brief overview of the |
|
|
break; |
|
|
C# language and then quickly moves to key technical and |
|
|
default: |
|
|
architectural issues for .NET developers. |
|
} |
break; |
|
|
|
|
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 |
|
|
SOURCE |
The (updated) Images project is included under the Chapter 14 subdirectory. |
Chapter 2 - Building C# Applications
CODE
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# andthet ..NETNETPlatform,ResourceSecond EditionFormat
by Andrew Troelsen |
ISBN:1590590554 |
Up to this point, each application that made use of external resources (such as bitmaps) assumed that
Apress © 2003 (1200 pages)
they were located in a separate stand-alone file within the application directory. For example, the Images
This comprehensive text starts with a brief overview of the
application renderedC# languagethree bitmapand thenimages,quicklywhichmovesas youto keyrecalltechnicalwere loadedand directly from file:
architectural issues for .NET developers.
// Fill the images with bitmaps.
bMapImageA = new Bitmap("imageA.bmp");
Table of Contents
bMapImageB = new Bitmap("imageB.bmp");
C# and the .NET Platform, Second Edition bMapImageC = new Bitmap("imageC.bmp");
Introduction
Part One - Introducing C# and the .NET Platform
ChapterThis logic1 of- ThecoursePhilosophydemandsof .NETthat the application directory does indeed contain three files named
Chapter"imageA2 .bmp,"- Build"imageBng C# Applicatio.bmp," ands "imageC.bmp" (see Figure 14-23).
Part Two - The C# Programming Language |
|
Chapter 3 - C# Language Fundamentals |
|
Chapter |
C# |
Chapter |
|
Chapter |
|
Chapter |
Events |
Chapter |
Techniques |
Part |
|
Chapter |
|
Chapter |
and Threads |
Chapter |
Attribute-Based Programming |
Part |
|
Chapter |
Remoting Layer |
Chapter |
Windows Forms) |
Chapter |
|
Chapter |
Controls |
Chapter |
|
Chapter
Part FiveFigure- Web14-Applications23: An applicationand XMLwithWebthreeS rvicexternals resources
Chapter 18 - ASP.NET Web Pages and Web Controls
If any of these files are deleted, renamed, or relocated outside the application directory, the program fails
Chapter 19 - ASP.NET Web Applications
to execute (give it a try just for verification's sake). Now, as you recall from Chapter 9, an assembly is a
Chapter 20 - XML Web Services
collection of types and optional resources. The time has now come to learn how to bundle external
Index
resources (such as image files and strings) into the assembly itself. In this way, your .NET binary is truly self-contained. In a nut-shell, bundling external resources into a .NET assembly involves the following steps:
Create an *.resx file that establishes name/value pairs for each resource in your application using XML data representation.
Use the resgen.exe utility to convert your XML-based *.resx file into a binary equivalent (a *.resources file).
Using the /resource: flag of the C# compiler, embed the binary *.resources file into your assembly.
As you might suspect, all these steps are followed automatically when using the Visual Studio .NET IDE. You'll examine how the IDE can assist you in just a bit. For now, let's take the time to work with the .NET resource format in the raw.
System.ResourcesC# and the .NamespaceET Platform, S cond Edition
by Andrew Troelsen |
ISBN:1590590554 |
The key to understanding the .NET resource format is to know the types defined within the System.Resources
Apress © 2003 (1200 pages)
namespace. This set of types provides the programmatic means to manipulate both *.resx (XML-based) and
This comprehensive text starts with a brief overview of the
*.resources (binary)C# fileslanguage. Tableand14then-29 providesquickly movesa rundownto keyoftechnithe coreal andtypes.
architectural issues for .NET developers.
Table 14-29: Members of the System.Resources Namespace
|
|
|
|
|
|
|
|
|
|
|
|
TableSystem.Resourcesof Contents |
|
|
|
Meaning in Life |
|
|
|
||||
C#Typeand the .NET Platform, Second Edition |
|
|
|
||||||||
|
|
|
|
|
|
|
|
|
|||
|
|
|
Introduction |
|
|
|
These interfaces are implemented by types that understand how to read |
|
|
|
|
|
|
|
IResourceReader |
|
|
|
|
|
|
||
Part One - Introducing C# and |
|
|
|
the .NET Platform |
|
|
|
||||
|
|
|
IResourceWriter |
|
|
|
and write .NET resources (in various formats). You do not need to |
|
|
|
|
Chapter 1 |
- The Philosophy of .NET |
|
|
|
|||||||
|
|
|
|
|
|
|
|
implement these interfaces yourself unless you are interested in building |
|
|
|
Chapter 2 |
- Building C# Applications |
|
|
|
|||||||
|
|
|
|
|
|
|
|
a custom resource reader/writer. |
|
|
|
Part Two - The C# Programming |
|
|
|
Language |
|
|
|
||||
|
|
|
|
||||||||
ChapterResourceReader3 - C# Language |
|
|
|
FundamentalsThese classes provide an implementation of the IResourceReader and |
|
|
|
||||
|
|
|
ResourceWriter |
|
|
|
IResourceWriter interfaces. Using the ResourceReader and |
|
|
|
|
|
|
|
|
|
|
Programming with C# |
|
|
|
||
Chapter 4 |
- Obj ct-Oriented |
|
|
|
|
|
|
||||
Chapter 5 |
- Exceptions and |
|
|
|
ResourceWriter types, you are able to read from and write to binary |
|
|
|
|||
|
|
|
Object Lifetime |
|
|
|
|||||
|
|
|
|
|
|
|
|
*.resources files. |
|
|
|
|
|
Chapter 6 |
- Interfaces and |
|
|
|
Collections |
|
|
|
|
|
|
|
|
||||||||
|
|
|
Chapter 7 |
- Callback Interfaces, |
|
Del gates, and Events |
|
|
|
||
|
|
|
ResXResourceReader |
|
|
|
These classes also provide an implementation of the IResourceReader |
|
|
|
|
|
|
|
ResXResourceWriter |
|
|
|
and IResourceWriter interfaces. Using the ResXResourceReader and |
|
|
|
|
|
|
Chapter 8 |
- Advanced C# Type Construction Techniques |
|
|
|
|||||
|
|
|
|
|
|
|
|
ResXResourceWriter types, you are able to read from, and write to, XML |
|
|
|
Part Three - Programming with .NET Assembli |
|
|
|
||||||||
Chapter 9 |
- Understanding .NET*.resxA sembliesfiles. This file may be turned into a binary equivalent (the |
|
|
|
|||||||
Chapter 10 |
- Processes, AppDomains,*.resourcesContexts,file) usingand Threadsthe resgen.exe utility. |
|
|
|
|||||||
|
|
|
|
|
|
|
|||||
|
|
|
Chapter 11 |
- Type Reflection, |
|
|
|
Late Binding, and Attribute-Based Programming |
|
|
|
|
|
|
ResourceManager |
|
|
|
Provides easy access to culture-specific resources (BLOBs and string |
|
|
|
|
Part Four - Leveraging the .NET Libraries |
|
|
|
||||||||
|
|
|
|
|
|
|
|
resources) at runtime. |
|
|
|
|
|
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+) |
|||||||||
|
ChapterProgrammatically15 - Programming withCreatingWindows FormsanControls*.resx File |
||||||||||
Chapter 16 |
- The System.IO Namespace |
||||||||||
|
As mentioned, an *.resx file is a block of XML data that assigns name/value pairs for each resource in your |
||||||||||
Chapter 17 |
- Data Access with ADO.NET |
application. The ResXResourceWriter class provides a set of members that allow you to create the *.resx file,
Part Five - Web Applications and XML Web Services
add binary and string-based resources, and commit them to storage. To illustrate, assume you have a simple
Chapter 18 - ASP.NET Web Pages and Web Controls
application you have built a la notepad and csc.exe, whose job in life is to build an *.resx file containing an
Chapter 19 - ASP.NET Web Applications
entry for the happy.bmp image seen earlier in this chapter, and a single string resource. The GUI is as simple
Chapter 20 - XML Web Services
as possible (Figure 14-24).
Index
List of Figures
List of
Figure 14-24: The ResX application
The Click event handler for the "Add resources" button does the grunt work of adding the happy.bmp and string resource to the *.resx file. Here is the code:
protected void btnMakeResxFile_Click (object sender, System.EventArgs e)
C# and the .NET Platform, Second Edition
{
by Andrew Troelsen ISBN:1590590554
// Make an resx writer & specify the file to write to.
Apress © 2003 (1200 pages)
ResXResourceWriter w =
ThisResXResourceWriter("ResXFormcomprehensive text starts with a brief overview of the new .resx");
C# language and then quickly moves to key technical and
// Add happy dude & string. architectural issues for .NET developers.
Image i = new Bitmap("happy.bmp");
w.AddResource("happyDude", i);
w.AddResource("welcomeString", "Hello new resource format!");
Table of Contents
// Commit it.
C# and the .NET Platform, Second Edition w.Generate();
Introduction w.Close();
Part One - Introducing C# and the .NET Platform
}
Chapter 1 - The Philosophy of .NET
Chapter 2 - Building C# Applications
PartTheTwomember- The C#of interestProgrammingis ResXResourceWriterLanguage .AddResource(). This method has been overloaded a few Chaptertimes to3allow- C#youLanguageto insertFundbinarymentalsdata (as you did with the happy.bmp image), as well as textual data (as you
Chavepterdone4 -forObjectyour-Orientedtest string)Programming. Notice thatwitheachC#version takes two parameters: the name of a given resource in
Chapterthe *.resx5 file- Exceptionsand the datand itselfObject. TheLifetimeGenerate() method commits the information to file.
Chapter 6 - Interfaces and Collections
Understand that you are not the one in charge of writing the raw XML that describes your resources. Rather,
Chapter 7 - Callback Interfaces, Delegates, and Events
the logic within the ResXResourceWriter class is responsible for building the XML description of the inserted
Chapter 8 - Advanced C# Type Construction Techniques
items. To prove the point, compile and run your application, load the new *.resx file using VS .NET, and peek
Part Three - Programming with .NET Assemblies
inside the contents (Figure 14-25).
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter |
Programming |
Part |
|
Chapter |
|
Chapter |
Forms) |
Chapter |
|
Chapter |
|
Chapter |
|
ChapterFigure17 - 14Data-25:AccessViewingwiththeADO.NET*.resx file a la VS .NET |
|
Part Five - Web Applications and XML Web Services |
|
Chapter 18 - ASP.NET Web Pages and Web Controls
If you switch to the XML view, you should be able to identify happyDude and welcomeString by name. The
Chapter 19 - ASP.NET Web Applications
XML syntax that is used to represent your name/value pairs follows [note the (partial) binary representation of
Chapter 20 - XML Web Services the happy dude bitmap...]:
Index
List of Figures
< data name="happyDude" mimetype="text/microsoft-urt/binary-serialized/base64" >
List of Tables
<value>
AAEAAAD/////AQAAAAAAAAAMAgAAA
...
AAAAAAAAAAAAAAAAAAAA=
</value>
</data>
<data name="welcomeString">
<value>Hello new resource format!</value>
</data>
Programmatically Reading an *.resx File
To illustrate how you can load and investigate an *.resx file programmatically let's examine the code behind the "Read *resx" button. This time, make use of a ResXResourceReader type. Once the correct file has been opened, ask the reader for a reference to its IDictionaryEnumerator interface, and loop over each name/value
pair:
C# and the .NET Platform, Second Edition
by Andrew Troelsen |
ISBN:1590590554 |
protected void btnReadResxFile_Click (object sender, System.EventArgs e)
Apress © 2003 (1200 pages)
{
This comprehensive text starts with a brief overview of the
// Make an resx reader.
C# language and then quickly moves to key technical and
ResXResourceReader r = new ResXResourceReader("ResXForm.resx"); architectural issues for .NET developers.
// Grab the IDictionaryEnumerator interface and show everything.
IDictionaryEnumerator en = r.GetEnumerator();
Table of whileContents(en.MoveNext())
{
C# and the .NET Platform, Second Edition
Introduction MessageBox.Show("Value:" + en.Value.ToString(),
"Key: " + en.Key.ToString());
Part One - Introducing C# and the .NET Platform
}
Chapter 1 - The Philosophy of .NET
r.Close();
Chapter 2 - Building C# Applications
}
Part Two - The C# Programming Language
Chapter 3 - C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C#
When you click the button, you see a pair of message boxes pop up, as the ResXResourceReader type loops
Chapter 5 - Exceptions and Object Lifetime through the XML file for each named value.
Chapter 6 - Interfaces and Collections
Chapter 7 - Callback Interfaces, Delegates, and Events
Building the *.resources File
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Now that you understand how to build and manipulate an *.resx file, you can make use of the resgen.exe utility
Chapter 9 - Understanding .NET Assemblies
to produce the binary equivalent. Again, VS .NET will do so automatically, but just for the love of learning, here
Chapter 10 - Processes, AppDomains, Contexts, and Threads is the raw command:
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
resgen resxform.resx resxform.resources
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+)
ChapterOf course,15 -youProgrammingmust openwitha commandWindows Forprompts Conin therolsdirectory containing the *.resx file before running Chaptresgenr .16exe-.TheOnceSystemyou do,.IO however,Namespaceyou are able to open the new *.resources file and check out the binary
format (Figure 14-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 14-26: The binary *.resources file
Binding the *.resources File into a .NET Assembly
Cool! At this point you are able to add this *.resources file as a command-line argument to the C# compiler. Recall that doing so also requires you to reference each external assembly (e.g., System.Drawing.dll):
csc/resource:resxform.resources *.cs
If you were to now open your new assembly using ildasm.exe, you would find the entry shown in Figure 14-27
C# and the .NET Platform, Second Edition in the assembly's metadata.
by Andrew Troelsen |
ISBN:1590590554 |
Apress © 2003 (1200 pages)
with a brief overview of the
moves to key technical and
developers.
Table
C# and the .NET Platform, Second Edition
Figure 14-27: The embedded resources
Introduction
PartAs youOnecan- Introducingsee, the manifestC# and thase .NETrecordedPlatformthe name of the binary resources that are now contained in the Chapterowning1assembly- The Philosophy. In just a ofbit.youNET will see how to programmatically read this information from an assembly to
Chaptmakeruse2 -ofBuildingit yourC#applicationA plications.
Part Two - The C# Programming Language
SOURCE The ResXWriterReader.cs file is included under the Chapter 14 subdirectory.
Chapter 3 - C# Language Fundamentals
CODE
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
Working withC# andResourceWritersthe .NET Platform, Second Edition
by Andrew Troelsen |
ISBN:1590590554 |
The previous example made use of the ResXResourceReader and ResXResourceWriter types to
Apress © 2003 (1200 pages)
generate an XML file that contains name/value pairs for each application resource. The resulting *.resx file
This comprehensive text starts with a brief overview of the
was then run throughC# languagethe resgenand.exeth nutilityquickly. Finallymovestheto*.kresourcesy technicalfileandwas bound into the owning assembly using thearchitect/resourceal issuesflag. Thefor .truthNET developersof the matter. is that you do not need to build an *.resx file (although having an XML representation of your resources can come in handy, and is readable).
TableIf youofdoContentsnot require an *.resx file, you can make use of the ResourceWriter type to directly create a binary C#*.resourcesand the .NETfile.Platform,To illustrate,SecondassumeEditionyou have created a new application named ResourceTest (again
using Notepad and csc.exe). The Main() method of the ResourceGenerator class uses the ResourceWrite
Introduction
type to directly generate the myResources.resources file:
Part One - Introducing C# and the .NET Platform
Chapter 1 |
- The Philosophy of .NET |
|
|
|
Chapterclass2ResourceGenerator- Building C# Applications |
|
|
||
Part{ Two - The C# Programming Language |
args) |
|
||
Chapter static3 - C# Languagevoid Main(string[]Fu damentals |
|
|||
Chapter {4 |
- Object-Oriented Programming with C# |
|
||
Chapter 5 |
- Exceptions// Makeanda Objectnew *Lifetime.resources file. |
|
||
Chapter 6 |
- InterfacesResourceWriterand Collectionsrw; |
|
|
|
Chapter 7 |
- Callbackrw = Interfaces,new ResourceWriter("myResources.resources");Delegates, and Events |
|||
Chapter 8 |
- Advanced// AddC#1 TypeimageConstructionand 1 string.Techniques |
|
||
Part Three - |
rw.AddResource("happyDude", new Bitmap("happy.bmp")); |
|||
|
|
Programming with .NET Assemblies |
"Welcome to .NET resources."); |
|
Chapter 9 |
- Understandingrw.AddResource("welcomeString",.NET Assemblies |
|||
Chapter 10 |
|
rw.Generate(); |
|
|
- Processes, AppDomains, Contexts, and Threads |
|
|||
} |
- Type Reflection, Late Binding, and Attribute-Based Programming |
|||
Chapter 11 |
||||
} |
|
|
|
|
Part Four - Leveraging the .NET Libraries |
|
|
||
Chapter 12 |
- Object Serialization and the .NET Remoting Layer |
|||
Chapter 13 |
- Building a Better Window (Introducing Windows Forms) |
|||
At this point, compile and run the application togenerate the *.resource file. Now, we can bind the |
||||
contained binary data to the owning assembly as before: |
|
|||
Chap er 14 |
- A Better Painting Framework (GDI+) |
|
||
Chapter 15 |
- Programming with Windows Forms Controls |
|
||
Chapter 16 |
- The System.IO Namespace |
|
|
|
csc /resource:myresources.resources *.cs |
|
|||
Chapter 17 |
- Data Access with ADO.NET |
|
|
Part Five - Web Applications and XML Web Services
If you wish to read the raw name/value data from the binary *.resources file, you are free to make use of
Chapter 18 - ASP.NET Web Pages and Web Controls
the ResourceReader class. This is almost identical to working with the ResXResourceWriter type.
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Index
List of Figures
List of Tables
Working withC# andResourceManagersthe .NET Platform, S cond Edition
by Andrew Troelsen |
ISBN:1590590554 |
Rather than working with the ResourceReader class directly, you will most likely use the
Apress © 2003 (1200 pages)
ResourceManager type. The reason is simple: It is easier to work with! Using the ResourceManager, you
This comprehensive text starts with a brief overview of the
are able to extractC#binarylanguandge textualand thendataquicklyfrommovesan assemblyto key technicalfor use inandyour application.
architectural issues for .NET developers.
To illustrate, assume you have added a new class to the current project named MyResourceReader. This type uses a ResourceManager type to pull the happyDude and welcomeString resources from the
Tableassemblyof Contentsand dump them into a PictureBox and Label object using the GetObject() and GetString() C#membersand the..BeNETveryPlatform,awareSecondhowever,Editionthat the double quoted strings you send into these methods are case
sensitive. Here is the code:
Introduction
Part One - Introducing C# and the .NET Platform
Chapterclass1MyResourceReader- The Philosophy of .NET
Chapter{ 2 - Building C# Applications
Part Twopublic- The C#staticProgrammingvoidLanguageReadMyResources()
Chapter {3 - C# Language Fundamentals
// Open the resources file.
Chapter 4 - Object-Oriented Programming with C#
ResourceManager rm = new ResourceManager("myResources",
Chapter 5 - Exceptions and Object Lifetime
Assembly.GetExecutingAssembly());
Chapter 6 - Interfaces and Collections
// Load image resource.
Chapter 7 - Callback Interfaces, Delegates, and Events
PictureBox p = new PictureBox();
Chapter 8 - Advanced C# Type Construction Techniques
Bitmap b = (Bitmap)rm.GetObject("happyDude");
Part Three - Programming with .NET Assemblies
p.Image = (Image)b;
Chapter 9 - Understanding .NET Assemblies p.Height = b.Height;
Chapter 10 - Processes, AppDomains, Contexts, and Threads p.Width = b.Width;
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming p.Location = new Point(10, 10);
Part Four - Leveraging the .NET Libraries
// Load string resource.
Chapter 12 - Object Serialization and the .NET Remoting Layer |
|
|
Label label1 = new Label(); |
Chapter 13 - Building a Better Window (Introducing Windows Forms) |
|
|
label1.Location = new Point(50, 10); |
Chapter 14 - A Better Painting Framework (GDI+) |
|
|
label1.Font = new Font(label1.Font.FontFamily, 12, FontStyle.Bold); |
Chapter 15 - Programming with Windows Forms Controls |
|
|
label1.AutoSize = true; |
Chapter 16 - The System.IO Namespace |
|
|
label1.Text = rm.GetString("welcomeString"); |
Chapter 17 - Data Access with ADO.NET |
|
|
// Build a Form to show the resources. |
Part Five - Web Applications and XML Web Services |
|
|
Form f = new Form(); |
Chapter 18 - ASPf.NETHeightWeb Pages= 100;and Web Controls |
|
Chapter 19 - ASPf.NETWidthWeb=Applications370; |
|
Chapter 20 - XMLf.TextWeb Services= "These resources are embedded in the assembly!"; |
|
Index |
// Add controls and show Form. |
List of Figures |
f.Controls.Add(p); |
List of Tables |
f.Controls.Add(label1); |
f.ShowDialog();
}
}
Before you run the application, be sure to update Main() to call the ReadMyResources() method:
static void Main(string[] args)
{
...
MyResourceReader.ReadMyResources();
}
When you run this application, you should find what appears in Figure 14-28.
Second Edition
ISBN:1590590554
This comprehensive text starts with a brief overview of the
Figure 14-28: Reading (and using) embedded resources
C# language and then quickly moves to key technical and
architectural issues for .NET developers.
SOURCE The ResourceTest project is included under the Chapter 14 subdirectory.
CODE
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
Automatic ResourceC# and the .NETConfigurationPlat orm, Second Editiona la Visual Studio .NET
by Andrew Troelsen |
ISBN:1590590554 |
To wrap things up, let's look at how the Visual Studio .NET IDE gets you up and running with the correct
Apress © 2003 (1200 pages)
resource file configuration automatically. When you create a new Windows Forms project workspace using
This comprehensive text starts with a brief overview of the
Visual Studio .NET,C#thelanguageIDE automaticallyand then quicklydefinesmovesanto*.resxkey filetechnicalfor eachandForm in your application. Furthermore, whenarchitecturalyou insertissuesnew resourcesfor .NET developersto a given. Form, the name/value pairs contained in the *.resx file are updated on your behalf. You can view a Form's *.resx file by selecting the "Show all files" option from the Solution Explorer window (Figure 14-29).
Table of Contents
C# and the .NET Platform, Second Edition
Part
Chapter
Chapter
Part
Chapter
Chapter
Chapter
Chapter
Chapter
Chapter
Part
Chapter
Chapter Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Figure 14-29: The underlying *.resx file for MainForm.cs
Part Four - Leveraging the .NET Libraries
ChaptOnceryou12 -selectObjectthisSerializationfile, checkandouttthe.PropertiesNET RemotingwindowLayer. You will see that the build action for this file has
Chapterbeen configured13 - Buildingas "Embeddeda Bett r WindowResource"(IntroducingFigureWindows14-30)Forms).
Chapter 14 - A Better Painting Framework (GDI+)
Chapter
Chapter
Chapter
Part
Chapter
Chapter
Chapter
Index
List of
List of
Figure 14-30: Under VS .NET, *.resx files are automatically embedded into your assembly.
This option compiles the *.resx file to produce the corresponding *.resources file, which is then embedded into your assembly. To illustrate updating *.resx files using VS .NET, create a new C# Windows Application workspace named ResLoader. The Form contains two PictureHolder types, one of which has its Image property set to the happy.bmp file, the other of which is empty. In addition, a single button type will be used to dynamically read this happy dude from file, and place it into the empty PictureHolder. The GUI is shown inFigure 14-31.
Edition
ISBN:1590590554
brief overview of the
to key technical and
.
Table
C# and
Part
Chapter
Chapter
Figure 14-31: GUI of the ResLoader application
Part Two - The C# Programming Language
Chapter 3 - C# Language Fundamentals
As you insert resources (such as a bitmap) into the project, the IDE responds by creating an instance of the
Chapter 4 - Object-Oriented Programming with C#
ResourceManager type within the scope of your InitializeComponent() method:
Chapter 5 - Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections
private void InitializeComponent()
Chapter 7 - Callback Interfaces, Delegates, and Events
{
Chapter 8 - Advanced C# Type Construction Techniques
// Note you need to specify the name of the Form that
Part Three - Programming with .NET Assemblies
// maintains the embedded resources.
Chapter 9 - Understanding .NET Assemblies
System.Resources.ResourceManager resources =
Chapter 10 - Processes, AppDomains, Contexts, and Threads
new System.Resources.ResourceManager (typeof(MainForm));
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
...
Part FourpictureBox1- Leve aging the.Image.NET Libraries=
Chapter 12 - Object(SystemSerialization.Drawingd.theImage).NET RemotingresourcesLayer.GetObject ("pictureBox1.Image");
Chapter} 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Needless to say, you are free to add a private ResourceManager member variable (or local variables) for
Chapter 16 - The System.IO Namespace
use throughout your application. To illustrate, here is the code behind the button's Click event:
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
// Be sure to specify 'using System.Resources'
Chapter 18 - ASP.NET Web Pages and Web Controls
private void btnLoadRes_Click(object sender, System.EventArgs e)
Chapter 19 - ASP.NET Web Applications
{
Chapter 20 - XML Web Services
// Make a ResourceManager
Index
ResourceManager resources = new ResourceManager (typeof(MainForm));
List of Figures
// Read happy dude from assembly and place it
List of Tables
// into the second PictureBox object.
this.pictureBox2.Image =
((System.Drawing.Bitmap)(resources.GetObject("pictureBox1.Image")));
// All done!
resources.ReleaseAllResources();
}
If you were to run the application and click the button, you would find that the image has been extracted from the assembly and placed into the second PictureBox (Figure 14-32).
Second Edition
ISBN:1590590554
with a brief overview of the moves to key technical and
developers.
Table
C# and the .NET Platform, Second Edition
Figure 14-32: Loading resources with the ResourceManager type
Introduction
Part One - Introducing C# and the .NET Platform
SOURCE The ResLoader project is included under the Chapter 14 subdirectory.
Chapter 1 - The Philosophy of .NET
CODE
Chapter 2 - Building C# Applications
Part Two - The C# Programming Language
That wraps up our look at GDI+. As you can guess, this .NET technology allows you to perform numerous
Chapter 3 - C# Language Fundamentals
other graphical manipulations. At this point you should have a solid understanding of the technology. You
Chapter 4 - Object-Oriented Programming with C#
revisit GDI+ later in this text when you examine ASP.NET (as odd as that may seem). Until then, the next
Chapter 5 - Exceptions and Object Lifetime
chapter addresses the use of Windows Forms widgets.
Chapter 6 - Interfaces and Collections
ChapterNote7 If- youCallbackare interestedInterfaces,inDexploringlegates, andGDI+Eventsfurther (including printing support), be sure to check out
GDI+ Programming in C# and VB .NET (Symmonds, Apress 2002).
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