Working with Icons

The Icon class represents a Windows icon, which is a small transparent bitmap. Just like the Bitmap class, this class is inherited from the Image class.

An application can create an Icon object from a stream, string, icon, icon file, or type by using the Icon class constructors with the size of the icon as an optional parameter. The Icon class provides four read-only propertiesHandle, Height, Size, and Widthwhich return a window handle to the icon, height, size, and width of an icon, respectively.

Listing 7.21 creates an Icon object from an icon file and sets the icon of a form using the Form class's Icon property.

Listing 7.21 Creating an icon and setting a form's Icon property

private void Form1_Load(object sender,
 System.EventArgs e)
{
 // Create an icon
 Icon curIcon = new Icon("mouse.ico");
 // Set form's icon
 this.Icon = curIcon;
 // Get icon properties
 float h = curIcon.Height;
 float w = curIcon.Height;
 Size sz = curIcon.Size;
}

The FromHandle method of the Icon class creates an Icon object from a window handle to an icon (HICON). The Save method saves an Icon object to a stream, and the ToBitmap method converts an Icon object to a Bitmap object. Listing 7.22 creates a Bitmap object from an Icon object using ToBitmap and draws the bitmap using DrawImage.

Listing 7.22 Creating a bitmap from an icon and displaying it

private void Form1_Paint(object sender,
 System.Windows.Forms.PaintEventArgs e)
{
 // Create an icon
 Icon curIcon = new Icon("mouse.ico");
 // Create a bitmap from an icon
 Bitmap bmp = curIcon.ToBitmap();
 // Draw bitmap
 Graphics g = e.Graphics;
 g.Clear(this.BackColor);
 g.DrawImage(bmp, 10, 10);
 g.Dispose();
}

Figure 7.35 shows the output from Listings 7.21 and 7.22.

Figure 7.35. Viewing icons

graphics/07fig35.jpg

Sometimes you will need to convert a Bitmap object into an Icon object. The following code snippet shows how to do this:


 
Icon curIcon;
curIcon = Icon.FromHandle(bmp.GetHicon());

 

GDI+: The Next-Generation Graphics Interface

Your First GDI+ Application

The Graphics Class

Working with Brushes and Pens

Colors, Fonts, and Text

Rectangles and Regions

Working with Images

Advanced Imaging

Advanced 2D Graphics

Transformation

Printing

Developing GDI+ Web Applications

GDI+ Best Practices and Performance Techniques

GDI Interoperability

Miscellaneous GDI+ Examples

Appendix A. Exception Handling in .NET



GDI+ Programming with C#
GDI+ Programming with C#
ISBN: 073561265X
EAN: N/A
Year: 2003
Pages: 145

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net