Main menu:

Site search

Categories

Archive

Convert Images To Icons In C# (C Sharp)

This entry (below) gets more hits than any other entry on my old blog. In an effort to help other programmers I am have reposted this entry on my new blog (here).

I have an image list object with my icons in it on my form. I need those icons, which are now “bitmaps” to go into an Icon property of a task tray icon object. Seems like it should be easy but there’s a trick. You need to convert the icons, which are bitmaps in the image list, back to icons. Anyway, here’s a quick function I made to do just that. Hopefully it’s helpful to someone else

private Icon GetIconFromImageList(ImageList imgList, int position)
{
return Icon.FromHandle(((Bitmap)imgList.Images[position]).GetHicon());
}

Just pass the function GetIconFromImageList() the image list object and then the position of the image you want to be returned as an Icon type. I used it like this:

taskTrayIcon.Icon = GetIconFromImageList(imgTrayIcons, 1);

Comments

Comment from Andy Swain
Time: November 10, 2005, 8:32 am

I had a similar problem but found the code above would leak gdi-objects causing the system to fall over when I used it as part of a fast animation.
I now use something like the following.

[System.Runtime.InteropServices.DllImport(”user32″)]
private static extern bool DestroyIcon(IntPtr hIcon);

IntPtr hIcon = bitmap.GetHicon();
Icon icon = Icon.FromHandle(hIcon);
statusMode.Icon = (Icon)icon.Clone();
icon.Dispose();
DestroyIcon(hIcon);

Write a comment