6
votes

I'm looking to convert a transparent PNG image as an ImageSource into a System.Drawing.Icon that respects the transparency of the PNG.

WPF can somehow do this internally if you set the icon for a window to a PNG ImageSource, but is there any way I can do this manually? Specifically I need this to set the system tray notify icon and I really want to avoid using clumsy .ico format resources.

2
As a side note, windows vista+ supports .ico files which are actually in PNG format. Does this work for you? blogs.msdn.com/b/oldnewthing/archive/2010/10/22/10079192.aspxMerickOWA
Not unless there's some utility/function in .NET that I can use to build a .ico from a PNG on the fly... Good to know, tho.devios1
@chaiguy have you looked at using hardcodet.net/projects/wpf-notifyicon for doing WPF system tray stuff?MerickOWA
@MerickOWA That's actually the library I'm using--the problem with it is it expects the icon resource to be a System.Drawing.Icon and will throw an exception if it is not, hence my trouble.devios1
@chaiguy Isn't the TaskBarIcon.IconSource property declared be an ImageSource?MerickOWA

2 Answers

6
votes

You can write

Icon.FromHandle(image.GetHIcon())

You'll need to explicitly destroy the icon when you're done with it:

[DllImport("user32.dll", CharSet = CharSet.Auto)]
extern static bool DestroyIcon(IntPtr handle);

DestroyIcon(newIcon.Handle);
1
votes

I'm looking for this~ Here is one, but not very good!

        Icon icon;
        Image source = Image.FromFile(picturefile, true);

        Bitmap target = new Bitmap(iconsize, iconsize,
            System.Drawing.Imaging.PixelFormat.Format32bppArgb);

        Graphics g = Graphics.FromImage(target);
        g.DrawImage(source, 0, 0, iconsize, iconsize);

        //target.Save("c:\\temp\\forest.bmp");

        icon = Icon.FromHandle(target.GetHicon());

        FileStream fs = File.Create(iconfile);
        icon.Save(fs);
        fs.Close();

        icon.Dispose();
        target.Dispose();
        source.Dispose();