Title: 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.
Note also that the system may need to display the form's icon in many sizes. For example, it may display different sizes in the form's upper left corner, in the Alt-Tab task switcher, and the task bar. Because an icon created from a bitmap only has one size, it will be scaled as needed and the results may not look very good. To get better results, build a real icon file and include all of the sizes that the system might need.
Download the example to experiment with it and to see additional details.
|