Use a bitmap for an icon in C#

You can't set a form's Icon property equal to a bitmap. Fortunately it's easy enough to create an icon from a bitmap.

This example uses the following code to make a form's icon display the image in a bitmap.

// Convert the bitmap resource to an icon and use it.
private void Form1_Load(object sender, EventArgs e)
{
    // Get the bitmap.
    Bitmap bm = new Bitmap(Properties.Resources.Spiral);

    // Convert to an icon and use for the form's icon.
    this.Icon = Icon.FromHandle(bm.GetHicon());
}

The program gets the bitmap stored in its Spiral resource. It then uses the bitmap's GetHicon method to get a handle to an icon holding the same image. It passes the handle to the Icon class's FromHandle method to create an Icon object and sets the form's Icon property equal to the result.

Note that the GetHicon method creates an icon in unmanaged memory. If the form stops using the icon, its memory is not freed. If you only create a few icons in this way, that's no big deal, but if the program makes hundreds of icons at run time, this may result in a memory leak. If you need to create and destroy many icons at run time, use the DestroyIcon API function to free the icon handle's memory.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.