GraphicsPath Methods selection 1

void AddRectangle void AddRectangles void AddPolygon void AddEllipse void AddPie void AddClosedCurve path.AddRectangle new Rectangle 50, 50, 100, 100 path.AddLine 200, 0, 0, 0 You can also add one path to another path GraphicsPath AddPath Method void AddPath GraphicsPath path, bool bConnect The second argument indicates whether the path that is added should be connected to the current subpath. The AddString methods add a text string to the path. The syntax of these methods is quite different...

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

IButtonControl Methods

void NotifyDefault bool bDefault void PerformClick When a control implementing IButtonControl gets a call to NotifyDefault with an argument of true, it is responsible for visually indicating that it is the default control and hence will respond to the Enter key . A button indicates that it's the default control with a bold outline. The PerformClick method simulates a button click. That's the method of the default Button control that the form calls when the Enter key is pressed. Generally, the...

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

String CompareOrdinal Static Method

int CompareOrdinal string str1, string str2 int CompareOrdinal string str1, int iStartIndex1, string str2, int iStartIndex2, int iCount The static Compare methods perform a lexical comparison String Compare Static Method int Compare string str1, string str2 int Compare string strl, string str2, bool blgnoreCase int Compare string strl, string str2, bool blgnoreCase, Culturelnfo ei int Compare string strl, int iStartlndexl, string str2, int iStartIndex2, int iCount int Compare string strl, int...

Graphics SetClip 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...

TextWriter Methods selection

void Write void WriteLine void Flush void Close TextWriter supports and StreamWriter inherits 17 versions of Write and 18 versions of WriteLine that let you specify any object as an argument to the method. The object you specify is converted to a string by the use of its ToString method. The WriteLine method follows the string with an end-of-line marker. A version of WriteLine with no arguments writes just an end-of-line marker. The Write and WriteLine methods also include versions with...

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

TreeNodeCollection 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...

PageSetupDialog 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 AutoScale

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

The Menu Item Collection

If you look back at the FirstMainMenu program, you'll see that the menu was built from the inside out. It began by creating Menultem objects for the innermost items such as Open, Save, and so on . These were assembled into arrays to create top-level items File, Edit, and so forth . Then the toplevel menu items were gathered together into a MainMenu object. A program might be more coherent and maintainable if the menu were created from the top down, beginning by creating a MainMenu object,...

A 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...

Print Preview

Once your application supports printing, it's fairly easy to implement a print preview feature. Basically, your normal PrintPage event handler is used to display printer output on the surfaces of bitmaps rather than to the printer. These bitmaps are then presented to the user. But before I show you how easy it is, let's examine what goes on behind the scenes. You may want to know these details if you prefer to take a different approach to handling the print preview bitmaps. The key to print...

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 Box

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

Graphics TranslateClip Methods

void TranslateClip int cx, int cy void TranslateClip float cx, float cy The KeyholeClipCentered program overrides the KeyholeClip program and centers both the clipping region and the path in the client area. KeyholeClipCentered.cs 2001 by Charles Petzold class KeyholeClipCentered KeyholeClip Application.Run new KeyholeClipCentered protected override void DoPage Graphics grfx, Color clr, int cx, int RectangleF rectf path.GetBounds int xOffset int cx - rectf.Width 2 - rectf.X int yOffset int cy -...

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 1

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

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

LinearGradientBrush 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...

The Print Controller

Earlier, when discussing the PrintDocument class, I skipped over the PrintController property. By default, you can set that property to an instance of a class descended from the abstract PrintController class. Here's the class hierarchy StanfarclPrintControlter J PrititCoMrollerWithSmiiisOitfvgl j PrevtowPruilCortfreller j The PrintController class defines four methods PrintController Methods void OnStartPrint PrintDocument prndoc, PrintEventArgs pea Graphics OnStartPage PrintDocument prndoc,...

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

StreamWriter 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...

Measuring the String

Another approach to centering text a much more generalized approach to text positioning doesn't require the StringFormat class but instead involves a method of the Graphics class, named MeasureString. MeasureString comes in seven versions, the simplest of which you call something like this SizeF sizefText grfx.MeasureString str, font MeasureString returns a SizeF structure that indicates the width and height of the string in units of pixels or, as you'll discover in Chapter 7, whatever units...

Handling PrintDocument 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...

GraphicsPath GetBounds Methods

RectangleF GetBounds Matrix matrix, Pen pen Neither argument has any effect on the coordinates stored in the path. You should be aware that the calculated rectangle reflects the minimum and maximum x and coordinates of all the points in the path. If the path contains Bezier splines, the rectangle reflects the coordinates of the control points, not the actual curve. To get a more accurate measurement of the figure, call Flatten before GetBounds. In Chapter 7, I spoke of the matrix transform as...

Everything Is an Object

In a program like SysInfoColumns, the code that displays the lines of text should probably be in a for loop. The actual information should probably be stored in an array of some sort, and perhaps isolated from the actual text-output code so that it could be used in other programs. In a C or C program, for example, you might put the information in an array of structures in a header file. However, there are no header files in C . Instead, remember the magic rule for C Everything is an object or...

PreviewPrintController 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...

Mouse Movement

Let's next look at the MouseMove event. This program is called MouseWeb but it has nothing to do with the World Wide Web instead, it overrides the OnMouseMove method to draw a web that connects the current mouse position with the corners and sides of the client area. MouseWeb.cs 2001 by Charles Petzold Text Mouse Web BackColor SystemColors.Window ForeColor SystemColors.WindowText ResizeRedraw true protected override void OnMouseMove MouseEventArgs mea DrawWeb grfx, BackColor, ptMouse ptMouse...

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 DrawImage Methods selection 1

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 AutoScale

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

InJz

Just offhand, it appears as if the most recently created control takes priority for actually touching the edge. In reality, the positioning is based on the z-order, a concept I'll explain shortly. Then there's DockStyle.Fill. I used DockStyle.Fill in the AnalogClock program in Chapter 10 to make the clock control fill up the form's entire client area. Only one control should have its Dock property set to DockStyle.Fill. The control fills up the client area but won't overlap any other controls...

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