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
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());
Категории