Print Dialog Constructor

You must initialize one (but not both) of the following properties PrintDialog Properties (selection) You must initialize one (but not both) of the following properties PrintDialog Properties (selection) Setting the Document property is preferred the PrintDialog object then uses the PrinterSettings property from that PrintDocument object to set its own PrinterSettings property. The bulk of the additional options available with PrintDialog involve letting the user print an entire document, a...

The Rendering Origin

There's something you should know about the hatch brush, and it's something that affects more sophisticated brushes as well. In fact, it's part of the model under which the Windows Forms graphics system was developed. To illustrate what I'm talking about, consider the following program. OverlappingHatehBrushes.es 2001 by Charles Petzold class OverlappingHatchBrushes PrintableForm Application.Run(new OverlappingHatchBrushes() Text Overlapping Hatch Brushes protected override void DoPage(Graphics...

The Open File Dialog

Both OpenFileDialog and SaveFileDialog inherit from the abstract class FileDialog, which implements a number of properties common to both classes. Both OpenFileDialog and SaveFileDialog are sealed, meaning that you can't inherit from them. Both OpenFileDialog and SaveFileDialog are primarily responsible for returning to your program a fully qualified filename that the user specifies either by selecting from a list box or by manually typing. Considering that this is file I O we're speaking of...

Linear Gradient Brushes

The remaining two brush classes are LinearGradientBrush and PathGradientBrush the word gradient here refers to a transition between colors. LinearGradientBrush involves a transition between two colors, sometimes called a fountain. At first, it may seem complicated to define a way in which one color merges with another, and that's probably why there are a couple different ways of specifying such a brush. A gradient between two colors can be defined by a pair of parallel lines. Each line is a...

Image Static Methods selection

Image Image.FromFile(string strFilename) Image Image.FromFile(string strFilename, bool bUselmageColorManagement) Image Image.FromStream(Stream stream) Image Image.FromStream(Stream stream, bool bUseImageColorManagement) Bitmap Image.FromHbitmap(IntPtr hBitmap) Bitmap Image.FromHbitmap(IntPtr hBitmap, IntPtr hPalette) You probably won't use the last two methods in this table unless you're interfacing with Win32 code. The first two methods, however, are quite powerful and very simple, as you can...

The Path More Formally

Let's begin a more formal look at paths with a few definitions and a quick overview A path is a collection of device-independent coordinate points that describe straight lines and curves. These lines and curves might or might not be connected to each other. Any set of connected lines and curves within the path is known as a figure or a subpath. (Both terms are used in the Windows Forms interface. The terms are synonymous.) Thus, a path is composed of zero or more subpaths. Each subpath is a...

Graphics Static Methods selection

Graphics Graphics.FromImage(Image image) For example, here's a statement that obtains a Graphics object named grfxlmage based on an lmage object named image Graphics grfxImage Graphics.FromImage(image) When you're finished with this Graphics object, call the Dispose method to get rid of it. The Graphics.Fromlmage method won't work with every image format. The method will not work and will throw an exception if the PixelFormat property of the image is one of the following PixelFormat members...

Metafile Constructors selection

Metafile(string strFileName, IntPtr ipHdc, Rectangle rect) Metafile(string strFileName, IntPtr ipHdc, RectangleF rectf) Metafile(string strFileName, IntPtr ipHdc, Rectangle rect, MetafileFrameUnit mfu) Metafile(string strFileName, IntPtr ipHdc, RectangleF rectf, MetafileFrameUnit mfu) MetafileFrameUnit is an enumeration defined in the System.Drawing.lmaging namespace. The enumeration indicates the units of the boundary rectangle specified in the constructor. MetafileFrameUnit plays no other...

The Keys Enumeration

Three of the properties of KeyEventArgs are of type Keys. Keys is a large enumeration the second largest enumeration in the entire .NET Framework. It includes keys that certainly aren't on my keyboard and probably aren't on yours either. (Veteran Windows programmers might notice that these enumeration values are the same as the virtual key codes defined in the Windows header files.) Let's tackle the Keys enumeration in logical groups. First, Keys has 26 members that identify the letter keys...

Printer Settings Constructor

PrinterSettings prnset new PrinterSettings() creates a new instance of PrinterSettings that refers to the default printer. The following three properties indicate some basic information about the printer The following three properties indicate some basic information about the printer PrinterSettings Properties (selection) PrinterName is a string that usually indicates the make and model of the printer. It's the same string you'll see in the Printers dialog box. Here are some examples HP...

List ViewltemList ViewSubltem Collection Methods selection

ListViewSubItem Add(string strText, Color clrFore, Color clrBack, Font font) ListViewSubItem Add(ListViewItem.ListViewSubItem lvsi) void AddRange(string astrText) void AddRange(string astrText, Color clrFore, Color clrBack, Font font) void AddRange(ListViewItem.ListViewSubItem alvsi) The ListViewltem.ListViewSubltem constructors have similar arguments ListViewltem.ListViewSubltem Constructors lviOwner, string strText) lviOwner, string strText, Color clrFore, Color clrText, Font font) L...

String Format Constructors

StringFormat(StringFormat strfmt) StringFormat(StringFormatFlags sff) StringFormat(StringFormatFlags sff, int iLanguage) The second version essentially clones an existing StringFormat object the third and fourth versions create a StringFormat object based on a combination of StringFormatFlags enumeration values. The StringFormatFlags enumeration is also used in setting the FormatFlags property of StringFormat StringFormat Properties (selection) The second version essentially clones an existing...

Using the Windows Registry

The Windows registry is a general-purpose mechanism that applications (and Windows itself) use to store program information that must be retained when an application terminates. The information is stored in a hierarchical format. You can use the Registry Editor program (Regedit.exe) that comes with Windows to examine (and, if you're very brave, even modify) the contents of the registry on your machine. The information in the registry is organized by keys, which are often written in the syntax...

Single Line Text Boxes

The simplest text box control is named TextBox. which is derived from the abstract TextBoxBase class. as shown in the class hierarchy on the top of the following page. Also deriving from TextBoxBase is RichTextBox. The RichTextBox control provides additional functionality over TextBox in the same way that the Microsoft WordPad program provides additional features over Notepad. In TextBox (as in Notepad). you can define a font. but the font applies to the entire document. In RichTextBox (as in...

Bitmap File Formats

A bitmap is a rectangular array of bits that correspond to the pixels of a graphics output device. A bitmap has a particular height and width measured in pixels. A bitmap also has a particular color depth, which is the number of bits per pixel (commonly abbreviated bpp). Each pixel in the bitmap has the same number of bits, which determines how many unique colors are in the image Number of colors 2 Number of bits per pixel The number of bits per pixel can generally range from 1 to 32 (and even...

List View Events

When experimenting with the SysInfoListView program, you'll find that you can select an item in the first column using the mouse or the up and down arrow keys. With the Shift key pressed, you can extend the selection to multiple items. You can also select and deselect individual items (without affecting other selected items) by clicking with the mouse while holding down the Ctrl key. (To turn off the default multiselection feature in a ListView object, set the MultiSelect property to false.) A...

The Mouse Cursor

The mouse cursor is the little bitmap image you see on the screen that indicates the location of the mouse. As you know, the cursor can change appearance depending on its location. Often it's an arrow, but if you pass it over a sizing border of a form, it changes into a double-headed arrow. In a text-entry field, the cursor becomes a vertical I-beam. The mouse cursor is an object of type Cursor, a class defined in the System. Windows.Forms namespace. I'll describe the Cursor class in more...

Printer Resolution Properties

PrinterResolutionKind is another enumeration PrinterResolutionKind is another enumeration Every printer has at least five items in the PrinterResolutions collection. Four of these items have PrinterResolutionKind values of Draft, Low, Medium, and High, with X and Y properties set equal to -1. These four enumeration values are not necessarily associated with unique printer resolutions. If the printer is capable of only one resolution, all these options result in the same resolution. The...

Metafile Header Methods

Bool IsWmf() bool IsWmfPlaceable() bool IsEmf() bool IsEmfPlus() bool IsEmfPlusOnlyO bool IsEmfPlusDual() bool IsEmfOrEmfPlus() bool IsDisplay() For MetafileType.Emf metafiles, the isEmf and isEmfOrEmfPlus methods return true. For MetafileType.EmfPlusOnly metafiles, isEmfPlus, isEmfPlusOnly, and isEmfOrEmfPlus return true. For MetafileType.EmfPlusDual metafiles, isEmfPlus, isEmfPlusDual, and isEmfOrEmfPlus return true. As we'll see, a metafile is always created based on a particular graphics...

The Paint Event Is Special

Watch out what you put in the Paint event handler. The method can be called quite frequently and sometimes unexpectedly, and it works best when it can repaint the client area quickly without interruption. Earlier in this chapter, I suggested that you use message boxes for simple debugging. But don't put a call to MessageBox.Show in the Paint event handler The message box could cover up part of the client area and result in another Paint event. And another and another and another Also, don't put...

Data Object Methods selection

Bool GetDataPresent(string strFormat) bool GetDataPresent(string strFormat, bool bAllowConversions) object GetData(string strFormat) object GetData(string strFormat, bool bAllowConversions)_ string str (string) data.GetData(typeof(string)) is equivalent to string str (string) That's pretty obvious. But those two calls are also equivalent to this one string str (string) The GetData method always converts the clipboard data into a .NET Framework data type, so in this case GetData returns a string...

Clip and a Trim

When you use the RectangleF version of DrawString, you're defining not only a right margin that governs text wrapping but also a bottom margin that limits the total amount of text that can be displayed. What happens if the text is too long to fit in the rectangle Let's look at the default case first when you don't include a StringFormat object as the last argument to DrawString. If the height of the rectangle is an integral multiple of the line-spacing height, an integral number of lines of...

Clipboard Viewers

A clipboard viewer is a program that displays the current contents of the clipboard. Here's a clipboard viewer that contains 21 radio buttons corresponding to the 21 fields of the DataFormats class. The program sets a 1-second timer and checks the clipboard contents during the Tick event. The Win32 messages that inform an application when the clipboard contents have changed are not directly available to a Windows Forms program. The radio buttons are enabled according to what formats are...

Metrical Dimensions

The dimensions of a form's client area are available from the ClientSize property. These dimensions are always in units of pixels. If you set a new page transform, you probably want the dimensions of the client area not in units of pixels but in units corresponding to what you're now using in the drawing methods. There are at least two ways to get the client size in metrical dimensions. Probably the most convenient way is the VisibleClipBounds property of the Graphics object. This property...

Text and Paths

Graphicspath Warp

The GraphicsPath class includes a method named AddString that lets you add a text string to a path. The straight lines and curves that make up the character outlines become part of the path. As usual, however, text is a little different from other graphics objects, and adding text to a path requires some special considerations. The first problem involves the AddString method itself. As you'll recall from Chapter 15, most of the Add methods in GraphicsPath are very similar to the corresponding...

List Box Text Box Combo

In its classical form, the combo box looks like a text box with an arrow at the right. Click the arrow and a list box drops down. But this traditional usage is not the only way in which you can use combo boxes. The critical property is DropDownStyle ComboBox Properties selection The DropDownStyle property is set to a member of the ComboBoxStyle enumeration The DropDownStyle property is set to a member of the ComboBoxStyle enumeration Editable field, list drops down default What I referred to as...

Clipboard Data Formats

At first, it seems so simple you put an object of type String, Bitmap, Metafile, or even Button on the clipboard, and you extract an object of type String, Bitmap, Metafile, or Button from the clipboard. But not every application running under Windows is a Windows Forms program Some Windows programs place objects on the clipboard that don't directly correspond to Windows Forms types. The problem goes both ways Windows applications that make use of the Win32 API or MFC are not prepared to deal...

Graphics Drawlmage Methods selection

Void DrawImage Image image, int x, int y, int cx, int cy void DrawImage Image image, float x, float y, float cx, float cy void DrawImage Image image, Rectangle rect void DrawImage Image image, RectangleF rectf These methods scale the image to the size of the rectangle, either stretching or compressing it to fit. One common use of these methods is to display an image in its pixel size rather than its metrical size. If page units are pixels, simply call grfx.DrawImage image, x, y, image.Width,...

Caps and Joins

Adjustablearrowcap Net

As the PenDashStyle program indicates, when lines start to get wide, they assume a graphical form of their own. You may like the square and rectangular appearance of the dots and dashes in styled lines, but you may prefer a more rounded appearance instead. This is the realm of line caps also known as ends and joins. The cap governs the appearance of the lines at their beginning and end, or the appearance of the dots and dashes. The join governs what happens at the meeting of two connected...

Graphics Set Clip Methods selection

Void SetClip GraphiesPath path, CombineMode em Suppose the path contains an ellipse. When you call the first version of SetClip, all subsequent drawing is restricted to that ellipse. I'll talk about the second version of SetClip shortly. But first, let's jump right into a demonstration program. The Clover program defines a path containing four overlapping ellipses and uses that for the clipping region. Clover.es 2001 by Charles Petzold protected override void DoPage Graphics grfx, Color clr,...

Horizontal and Vertical Alignment

Stringformat Alignment Property

Our first encounter with the StringFormat class was back in Chapter 3, where we used it to center text in a form's client area. The two StringFormat properties that affect the alignment of text are shown here Both these properties are of type StringAlignment, which is an enumeration consisting of just three members The alignment values work a little differently depending on whether you specify a PointF object or a RectangleF object in the DrawString call. Let's take a look at the RectangleF...

Programming Microsoft Windows with C

Copyright 2002 by Charles Petzold All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any means without the written permission of the publisher. Library of Congress Cataloging-in-Publication Data Petzold, Charles, 1953- Programming Microsoft Windows with C Charles Petzold. p. cm. Includes index. ISBN 0-7356-1370-2 1. C Computer program language 2. Microsoft Windows Computer file I. Title. QA76.73.C154 P48 2001 005.26'8--dc21 Distributed...

SSSSmSmSmSmSmSmm

Square Shingle Hatch Pattern

The HatchBrush class is defined in the System.Drawing.Drawing2D namespace. There are only two constructors HatchBrush HatchStyle hs, Color clrForeground HatchBrush HatchStyle hs, Color clrForeground, Color clrBackground Although the bitmaps used for hatch brushes are monochrome, the O's and 1's of the bitmap can be mapped to any two colors you want. In the simpler hatch brushes with line patterns, the foreground color is the color of the lines themselves the background color is the color...

The Track Bar Alternative

Very similar in functionality to scroll bars are track bars. From the programmer's perspective, one difference between scroll bars and track bars is that the horizontal or vertical orientation of a track bar is a property The Orientation enumeration is short and simple The Orientation enumeration is short and simple As you know from experimenting with the ColorScroll program, you can change the thickness of scroll bars. By default, you can't change the thickness of track bars, and the track bar...

Tree NodeCollection Methods selection

TreeNodeCollection also contains familiar methods named insert, Remove, Clear, and others. All the nodes in the same TreeNodeCollection object are sometimes referred to collectively as siblings. The TreeNode object to which the collection belongs is the parent. I haven't yet said anything about TreeView. Basically, TreeView is a collection of top-level or root TreeNode objects. Like TreeNode, TreeView contains a Nodes property This Nodes property is a collection of all the root TreeNode...

Page SetupDialog Constructor

You then set one and only one of the following properties PageSetupDialog Properties selection You then set one and only one of the following properties PageSetupDialog Properties selection PageSetupDialog Properties selection Setting the Document property is recommended. PageSetupDialog then sets the PrinterSettings and PageSettings properties from that PrintDocument object. To make everything work right. you must use the same PrintDocument object with both PageSetupDialog and PrintDialog....

Inside Auto Scale

After the code in your form's constructor is executed, the form and all children in the form are scaled based on the form's Font and AutoScaleBaseSize properties. The actual scaling is performed by a protected method of the Control class named ScaleCore, which is called first for the form and then for all the controls that are children of the form. You can accomplish the same scaling as auto-scale by calling one of the Scale methods for the form For example, if you set the AutoScale property to...

Problem and Its Solution

Let's begin our exploration of graphics paths with a graphics programming problem. Suppose you want to draw a figure that's composed of a line, a semicircle, and another line, all connected to each other, and you want to use a pen that is considerably thicker than 1 pixel. Here's a possible first stab at drawing such a figure. LineArcCombo.cs 2001 by Charles Petzold Application.Run new LineArcCombo Text Line Arc Combo protected override void DoPage Graphics grfx, Color clr, int cx, int...

Status Bar Panels

In the examples shown so far, the status bar is barely more functional than a label control that's docked to the bottom of the form. If you hide the sizing grip, you'd be hard pressed to tell them apart. The status bar becomes more versatile when you make use of StatusBarPanel objects. A status bar can contain zero or more status bar panels. StatusBar has two properties that involve the StatusBarPanel objects The status bar becomes more versatile when you make use of StatusBarPanel objects. A...

Buttons with Bitmaps

Although you can set custom fonts and colors in your buttons, you may want to go to greater extremes in presenting a unique visual interface to your users. You can put a graphical image on your buttons in two ways. The first involves four properties of the ButtonBase class These properties let you specify a bitmap image to be displayed in the background of the button. Either you set the Image property to a specific Image or Bitmap object, or you set ImageList to an ImageList object and...

Your First Modal Dialog

Dialog boxes differ from application forms mostly in the way in which they are invoked and just as important terminated. This SimpleDialog program demonstrates both of these jobs. SimpleDialog.cs 2001 by Charles Petzold Text Simple Dialog Menu new MainMenuO new EventHandler MenuOnCliek void MenuOnCliek objeet obj, EventArgs ea SimpleDialogBox dlg new SimpleDialogBox dlg.ShowDialog strDisplay Dialog box terminated with dlg.DialogResult proteeted override void OnPaint PaintEventArgs pea...

The Missing Caret

Controls or forms that accept keyboard input generally display something special when they have input focus. A button control, for example, displays a dotted outline around its text. Controls or forms that allow you to type text usually display a little underline, a vertical bar, or a box that shows you where the next character you type will appear on the screen. You may know this indicator as a cursor, but in Windows it's more properly known as a caret. The word cursor is reserved for the...

Font Constructors selection

Font string strFamily, float fSize, GraphicsUnit gu Font string strFamily, float fSize, FontStyle fs, GraphicsUnit gu You can use all but one of the GraphicsUnit enumeration values that you learned about in connection with the PageUnit property in Chapter 7 You can use all but one of the GraphicsUnit enumeration values that you learned about in connection with the PageUnit property in Chapter 7 new Font strFamily, float fSize is identical to new Font strFamily, float fSize, GraphicsUnit.Point...

Texture Brushes

If you've gone through the list of hatch brushes and not discovered one you like, or if you need more than two colors in your brush, or if you want a brush that's subject to transforms, you'll want to explore the TextureBrush class. A texture brush is based on an object of type Image or a rectangular subset of an Image object that repeats horizontally and vertically. The WrapMode enumeration is defined in the System.Drawing.Drawing2D namespace The WrapMode enumeration is defined in the...

An Analog Clock

Code Clock Analog Vb8

Digital clocks were popular when they were new, but the pendulum has swung back so to speak to analog clocks. An analog clock needn't concern itself with different date and time formats, but the complexity of the graphics more than outweighs that convenience. Users have come to expect analog clocks to dynamically change size with the size of the window. For greatest versatility, I decided to write the clock display logic as a child window control like the CheckerChild class in the...

Linear GradientBrush Methods selection

Void SetBlendTriangularShape float fFocus void SetBlendTriangularShape float fFocus, float fScale void SetSigmaBellShape float fFocus void SetSigmaBellShape float fFocus, float fScale Normally, the gradient is from the first color to the second color. These two methods change the gradient so that it goes from the first color to the second color and then back to the first. Both arguments which I'll describe shortly can range from 0 to 1. Let's take a look. Here's the unaltered...

Page Units and Page Scale

So that you can avoid writing methods such as MMConv, GDI includes a facility that performs automatic scaling to dimensions of your choosing. Basically, the coordinates you pass to the Graphics drawing functions are scaled by constants, just as in the MMConv method. But you don't set these scaling factors directly. Instead, you set them indirectly using two properties of the Graphics class named PageUnit and PageScale You set the PageUnit property to a value in the GraphicsUnit enumeration You...

Splitsville

You've probably seen splitters in other applications besides Windows Explorer. In Microsoft Word, for example, you can choose Split from the Window menu and divide your document into two regions with a horizontal splitter. This feature allows you to work on one section of a document while keeping another section in view. Again, the splitter adjusts the relative sizes of the two views. By default, Microsoft Visual Studio .NET uses splitters to separate its client area into four areas. Splitters...

Scrolling a Panel Control

The .NET Framework has lots of interesting controls, ranging from buttons, list boxes, and text boxes to calendars, tree views, and data grids. The panel control, however, is not one of these interesting controls. It has no visual appearance to speak of and not much of a user interface. Panels are generally used for architectural purposes to group other controls against a background. Panels are also useful when you need a control but don't want it to do very much. What I've done in the...

The Shadow Bitmap

Occasionally, implementing an OnPaint method can be costly in terms of processing time or memory. The client area could contain a complex image that has been assembled over a long period of time, for example. For such applications, implementing a shadow bitmap is usually an excellent solution. A shadow bitmap is a bitmap that your program draws on whenever it also draws on its client area outside the OnPaint method. Then the OnPaint method reduces to a simple call to Drawlmage. In Chapter 8,...

Choosing Fonts and Colors

Let's take a look at both FontDialog and ColorDialog in a single program that lets you set the BackColor, ForeColor, and Font properties of a form. FontAndColorDialogs.cs 2001 by Charles Petzold Applieation.Run new FontAndColorDialogs Text Font and Color Dialogs ResizeRedraw true Menu new MainMenu Color , void MenuFontOnCliek objeet obj, EventArgs ea FontDialog fontdlg new FontDialog fontdlg.Font Font fontdlg.Color ForeColor fontdlg.ShowColor true if fontdlg.ShowDialog DialogResult.OK Font...

Stream Writer Constructors selection

StreamWriter Stream stream StreamWriter Stream stream, Encoding enc StreamWriter Stream stream, Encoding enc, int iBufferSize If you use a constructor without an Encoding argument, the resultant StreamWriter object will not store strings to the file in a Unicode format with 2 bytes per character. Nor will it convert your strings to ASCII. Instead, the StreamWriter object will store strings in a format known as UTF-8, which is something I'll go over shortly. If you use one of the StreamWriter...

Handling Print Document Events

The following class hierarchy shows the descendents of EventArgs that are involved with the PrintDocument event handlers CancelEventArgs is defined in the System.ComponentModel namespace. The PrintEventArgs object associated with the BeginPrint and EndPrint events has a single property that it inherits from The BeginPrint event handler can set Cancel to true to abort the print job for example, when the print job needs more memory than is available . The QueryPageSettingsEventArgs class adds...

Radio Buttons and Group Boxes

Ellips Radio Button

Someday, no one will know why they're called radio buttons. You see, car radios once came equipped with a row of tall buttons that could be set to favorite radio stations. To select a station, you pushed in a button, which caused the previously pushed-in button to pop out. Because only one button could be pressed at a time, a group of radio button controls always reflects a group of mutually exclusive options. What makes radio buttons different from other controls is that they always exist in a...

Nonlinear Transforms

The matrix transform is widely available throughout the Windows Forms graphics system. You can apply it to a Graphics object, to a path, and to brushes and pens. But the matrix transform is always a linear transform. Parallel lines are always mapped to other parallel lines, and after awhile, you might begin to see those consistently parallel lines as bars on a jail cell. The GraphicsPath class has one nonlinear transform available through a method named Warp. Here's a program that stores some...

Pen Widths

Pen Widths

What's a proper pen width for the printer You might take a cue from PostScript the well-known and highly respected page composition language many upscale printers use and think of a normal default pen width as 1 point, otherwise expressible as 1 72 inch, or about 1 3 millimeter. I personally find a 1-point pen width to be a bit on the chunky side, but it's an easy rule to remember. Here's a program that displays a bunch of pen widths in units of points. PenWidths.cs 2001 by Charles Petzold new...

Arbitrary Coordinates

Some of the graphics programs shown so far in this book have scaled their output to the size of the client area or the printable area of the printer page. Programs in this chapter have drawn in specific sizes in units of millimeters or inches. Then there are times when you want to hard-code a bunch of coordinates and would prefer that you could skip any explicit scaling of them. For example, you may want to code some graphics output using a coordinate system of say 1000 units horizontally and...

Canonical Curve Derivation

Like the Bezier spline, the canonical spline is a cubic, so it has the general parametric formulas x t a b cxt d, y0t a byf c t d for t ranging from 0 to 1. The first derivatives are x t 3a 2bxt cx t 3a t2 2b t c Let's look at four points, labeled po, p1, p2, and p3. I'm going to develop the formulas for the segment between p1 and p2. That curve is based on those two points as well as the two adjoining points, po and p3. The first assumptions are that the curve begins at p1 and ends at p2 From...

Preview PrintController Method

PreviewPageInfo GetPreviewPagelnfo The PreviewPagelnfo class has two properties PreviewPagelnfo Properties The PreviewPagelnfo class has two properties PreviewPagelnfo Properties The pixel size of the Image property is the pixel size of your printer page. The PhysicalSize property indicates the dimensions in hundredths of an inch. Now you have a collection of bitmaps, each of which corresponds to a page of the printed document. You can display these bitmaps however you want. Is there an even...

Arrays of Font Families

FontFamily has one more static property and just one static method, and they are very similar and very important. Both of them return an array of FontFamily objects corresponding to the installed TrueType and OpenType fonts on the system. Here's the static property FontFamily Static Property selection FontFamily aff FontFamily.Families FontFamily aff FontFamily.Families each element of the aff array will be a FontFamily object. If you've ever done font enumeration under Windows using the Win32...

Graphics Draw Image Methods selection

Void Drawlmage lmage image, int xDst, int yDst, Rectangle rectSrc, GraphicsUnit gu void Drawlmage lmage image, float xDst, float yDst, RectangleF rectfSrc, GraphicsUnit gu The concept here is simpler than the bizarre definitions of these methods would seem to imply. First, you always specify the source rectangle in units of pixels. Thus, the version of DrawImage defined with a RectangleF structure rather than a Rectangle structure makes no sense. Second, the GraphicsUnit argument must be...

How the Windows Forms Designer Uses Auto Scale

I mentioned that you'll someday have to look at the code that the Visual C .NET Windows Forms Designer generates, and you may need to understand certain aspects of it. Well, auto-scale is a primary example. Let me assume that your display settings are set to Small Fonts. When you use the Windows Forms Designer to design a form, it generates code that contains the pixel dimensions you've used. For example, a Button control might have its Size property set like so this.button1.Size new...

Times New Roman Metrics

You can use information derived from the design metrics to position text on a baseline. Let's suppose we want the baseline to be the horizontal line in the center of the client area and we want a 144-point Times New Roman font to be positioned on that line. Here's the code to do it. TextOnBaseline.es 2001 by Charles Petzold elass TextOnBaseline PrintableForm Application.Run new TextOnBaseline Text Text on Baseline proteeted override void DoPage Graphies grfx, Color elr, int ex, int Draw the...

Binary Resources

If your application needs to display a particular bitmap, I've demonstrated numerous times in this chapter how you can load the bitmap from a file. But as you know, storing bitmaps in separate files isn't always a good solution for an application that is distributed to other users. What happens if the program file and the bitmap file are separated An overzealous user might be cleaning up the hard drive by erasing unnecessary files and suddenly, Bam No more bitmap. For this reason, it's often...

Graphics Path Warp Methods

Graphicspath Warp

You can optionally also supply a Matrix object and a flatness value. The source points are transformed to the destination points like this aptfDst 0 is the destination of the upper left corner of the rectangle. aptfDst 1 is the destination of the upper right corner of the rectangle. aptfDst 2 is the destination of the lower left corner of the rectangle. aptfDst 3 is the destination of the lower right corner of the rectangle. An optional argument determines how intermediary points are calculated...

The Canonical Spline

Net Fillclosedcurve

The Graphics class includes a second type of spline called the canonical spline, meaning a standard or normal spline. You draw a canonical spline by using one of the DrawCurve methods. DrawCurve comes in seven different versions, but you'll probably use the following four methods most frequently Graphics DrawCurve Methods selection Graphics DrawCurve Methods selection At least two points are required. If the array contains only two points, the DrawCurve method draws a straight line from the...

Collinear Beziers

Bezier Infinity Sign

Although connected Bezier curves share end points, it's possible that the point at which one curve ends and the other begins won't be smooth. Mathematically speaking, the composite curve is considered to be smooth only if the first derivative of the curve is continuous that is, it doesn't make any sudden changes. When you draw multiple Bezier curves, you may want the resultant composite curve to be smooth where one curve ends and the next one begins. Then again, you may not. The hands of the...

Handling Input from Foreign Keyboards

It's always helpful to test your programs on any type of keyboard that's not like the one on your machine, and in particular, foreign language keyboards.11' And running your program with Russian is much easier than a trip to Moscow. You can install foreign-language keyboard layouts, which are small files that let you use your existing keyboard to generate character codes from other languages. The following instructions for installing foreign-language keyboard layouts pertain to the English...

Data Object Set Data Method

Void SetData Type typeFormat, object objData void SetData string strFormat, object objData void SetData string strFormat, bool bConvert, object objData You create an object of type DataObject, use calls to SetData to store multiple formats of a single item, and then pass the DataObject object to Clipboard.SetDataObject. By default, items are converted to compatible formats unless you use the last overload in the table and set the bConvert argument to false. For example, suppose strText is a...

Other Stream Classes

Net Streams Hierarchy

The FileStream class is one of several classes descended from the abstract class Stream. For a class that can't be instantiated, Stream plays a very important role in the .NET Framework. This hierarchy diagram shows six classes descended from Stream The stream classes with an asterisk are defined in namespaces other than System.IO. In addition, a number of methods in other classes scattered throughout the .NET Framework return objects of type Stream. For example, as I'll demonstrate later in...

UpDown Controls

The Windows Forms up-down control is more traditionally known as a spin control. There are two types of up-down controls, as shown in the following class hierarchy The controls consist of an edit field with a pair of arrow buttons at the right. The NumericUpDown control lets the user select from a range of numbers while the DomainUpDown control lets the user select from a collection of objects that are identified by strings. I'll be focusing on the NumericUpDown control in this section. You...

String Format Methods selection

Void SetTabStops float fFirstTab, float afTabs float GetTabStops out float fFirstTab _ Tab stops are in world coordinates. You'll notice that the tab stops are specified by both a float value and an array of float values, which would seem to indicate that the value not in the array is treated differently. What the method syntax doesn't imply is that the last value of the array is also treated differently. Let me give you a few simple examples first before I show you how the SetTabStops method...

Adventures in Tracking

Generally, it's fairly easy to write some mouse-tracking code that works 99.5 percent of the time. This program is quite similar in structure to MouseConnect but it does something much more conventional, which is letting you drag the mouse to draw a rectangle. BlockOut.cs 2001 by Charles Petzold Text Blockout Rectangle with Mouse BackColor SystemColors.Window ForeColor SystemColors.WindowText protected override void OnMouseDown MouseEventArgs mea if mea.Button MouseButtons.Left ptBeg ptEnd new...

Pierre Bezier

Bezier Art

Many people including Pierre Bezier151 himself have used Bezier splines to create interesting designs and patterns. These are generally lumped under the category of Bezier art. There are no rules here except that a for loop is generally involved. Here's an example. BezierArt.cs 2001 by Charles Petzold protected override void DoPage Graphics grfx, Color clr, int cx, int double dAngle 2 i Math.PI iNum aptf 0 .X cx 2 cx 2 float aptf 0 .Y 5 cy 8 cy 16 float Math.Sin dAngle aptf 1 new PointF cx 2,...

Toolbar Styles

So far. the toolbar buttons we've created have functioned much like push buttons. You can also make a toolbar button function like a check box that can be toggled on or off. Or. a toolbar button can invoke a menu. These options are available through the following properties So far. the toolbar buttons we've created have functioned much like push buttons. You can also make a toolbar button function like a check box that can be toggled on or off. Or. a toolbar button can invoke a menu. These...

Font StyleButtonsbmp

This program creates a Panel control that fills the client area at least before the toolbar is created and displays any output that would normally go in the client area. The PanelOnPaint event handler displays a string of centered text. Because it's displaying centered text, the panel must be repainted whenever it's resized. However, the handy ResizeRedraw property is protected. One possibility is to subclass Panel another which is what this program does is to install an event handler for the...

Page Transforms

What you're effectively setting when you set the PageScale and PageUnit properties is known as the page transform. This transform can be represented by a pair of simple formulas. Assume that the coordinates you pass to the Graphics drawing methods are page coordinates. This assumption isn't quite true, as you'll see later in this chapter, but it is true if you're setting only the PageScale and PageUnit properties. You can represent a point in page units as xpage, page . Pixel coordinates...

The Auto Scale Option

The programs shown in this chapter have used the Font.Height property of the form to scale the sizes of controls that display text. For horizontal sizing, I've used one-half the font height as a generous approximation of the average character width of lowercase letters. It's even generous for the Courier font. Because controls inherit their parent's font, this is a perfectly acceptable method of scaling controls. If you ever want to set a different font for the form and hence its controls , do...

Filelnfo Methods selection

Filelnfo CopyTo string strFileName, bool bOverwrite void MoveTo string strFileName void Delete void Refresh The copy, move, and delete facilities are duplicated in the File class File Static Methods selection void Copy string strFileNameSrc, string strFileNameDst void Copy string strFileNameSrc, string strFileNameDst, bool bOverwrite void Move string strFileNameSrc, string strFileNameDst void Delete string strFileName And finally, the File and Filelnfo classes have several methods to open files...

Little Puzzle Called Jeu de Taquin

Well, more like a puzzle. This particular puzzle was invented in the 1870s, probably by the famous American puzzle-maker Sam Loyd 1841-1911 . For a while, this puzzle was all the rage, particularly in Europe, and was known under various names, including the 15-puzzle, the 14-15 puzzle, and in France Jeu de Taquin, the teasing game. In its classic form, the puzzle consists of 15 square blocks numbered 1 through 15. The squares are arranged in a 4-by-4 grid,...

Polygons and the Filling Mode

Finally at least for this chapter , we have the FillPotygon method. What makes the polygon different from other filled areas is that the lines that define the polygon can cross and overlap. This adds a layer of complexity because the interiors of the polygon can be filled in two distinct ways. There are four FillPotygon methods void FillPolygon Brush brush, Point apt void FillPolygon Brush brush, PointF apt void FillPolygon Brush brush, Point apt, FillMode fm void FillPolygon Brush brush,...

Variations on Draw String

We've already encountered the six variations of the DrawString method The versions using a PointF structure are identical to the versions using the two float values. It's just two different ways of specifying the same starting point for the string. All four of the DrawString overloads that use a PointF or two float values generally display a single line of text. However, if the text contains line feed characters ' n' or ' x000A' , the text that follows is displayed one line lower. The two...

Listing the System Information

I created the SysInfoStrings.cs file in a project named SysInfoList, which also includes the SysInfoList.cs file shown here. This program displays the system information items provided by the SyslnfoStrings class. SysInfoList.cs 2001 by Charles Petzold readonly float cxCol readonly int cySpace Text System Information List BackColor SystemColors.Window ForeColor SystemColors.WindowText SizeF sizef grfx.MeasureString , Font cxCol sizef.Width SysInfoStrings.MaxLabelWidth grfx, Font grfx.Dispose...

Anti Aliasing

Besides those four properties of the Graphics class that affect output very profoundly, other properties affect the output in more subtle ways. Two of these properties are SmoothingMode and PixelOffsetMode. Besides those four properties of the Graphics class that affect output very profoundly, other properties affect the output in more subtle ways. Two of these properties are SmoothingMode and PixelOffsetMode. These properties enable a graphics rendering technique known as anti-aliasing. The...

Grid Fitting and Text Fitting

The text-handling portion of GDI is designed to be device independent. In practical terms, MeasureString returns a text dimension that is independent of the output device. If you set the same page transform on both the screen and the printer, MeasureString returns identical values for any particular text string and font. This consistency makes it comparatively easy to format text on the screen that will look the same when printed on the printer. However desirable the goal of WYSIWYG may be,...

Filling Rectangles Ellipses and Pies

Several of the Graphics methods discussed so far have defined enclosed areas, even though these methods have only drawn the outline of the area with the specified pen and not filled the interior of the area. For those methods prefixed with Draw that define enclosed areas, there are also methods beginning with Fill that fill the interiors. The first argument to these methods is the Brush used to fill the area. Here are the four versions of the FillRectangle method Graphics FillRectangle Methods...

Graphics Path Flatten Methods

Void Flatten Matrix matrix, float fFlatness You can optionally apply a Matrix to transform the points before flattening them. The number of line segments decreases as the fFlatness argument gets higher. The default fFlatness argument is equivalent to an argument of 0.25. The method is not defined for values of 0. The Widen method has a much more profound effect on the path than the Flatten method does. The first argument is always a Pen object The method ignores the color of the pen and uses...

Metafile Sizes and Rendering

As you'll recall from Chapter 11, the Image class has several properties that describe the image. Because Metafile is descended from Image, these properties also apply to metafiles. In particular, you'll find the following properties useful when working with metafiles For Bitmap objects, the Size, Width, and Height properties indicate the pixel dimension of the bitmap the number of rows and columns of bits. The HorizontalResolution and VerticalResolution properties report information that's...

Graphics Enumerate Metafile Methods selection

Void EnumerateMetafile Metafile mf, Point pt, It may seem odd that EnumerateMetafile is a method of our old friend the Graphics class. But you'll see shortly that the method not only enumerates a metafile but also provides a way to render it on a record-by-record basis. As your method gets access to every record of the metafile, it can decide to let the record be rendered, skip the record, or if you're particularly brave modify the record and render it. And that's also why there are so many...

Creative Auto ScaleBase Size Settings

Traditionally, Windows programmers coding in C and C using the Win32 API or the Microsoft Foundation Class MFC Library define their dialog boxes in a text format known as a dialog box template using a special device-independent coordinate system known as dialog box coordinates. All x coordinates are 1 4 of the average character width y coordinates are expressed in units of 1 8 of the character height. If a control's location is specified as 40, 32 , for example, the control is positioned 10...