tags:

views:

43

answers:

3

Hi,

I have an Icon which has a few different sizes (16px, 32px, 64px). I am calling the toBitMap() object but it is always returning the 32px image. How do I retrieve the 64?

A: 

There is no built-in method in the .Net framework that does this.

Instead, you can use this library.

SLaks
A: 

The size is determined when you first create the Icon instance, so you need to specify which size you want to use when you create it, using one of the Icon constructors that take a Size parameter.

Thomas Levesque
Hi thanks. This would make sense, but my icon is inside a resource file. How do I modify the constructor?
whydna
+1  A: 

This is a fairly painful limitation in the ResourceManager class. It's GetObject() method has no way to make the returned icon selected by size. A workaround is to add the icon to the project instead. Use Project + Add Existing Item, select your .ico file. Select the added icon and change the Build Action property to "Embedded Resource".

You can now retrieve the desired icon with code like this:

    public static Icon GetIconFromEmbeddedResource(string name, Size size) {
        var asm = System.Reflection.Assembly.GetExecutingAssembly();
        var rnames = asm.GetManifestResourceNames();
        var tofind = "." + name + ".ICO";
        foreach (string rname in rnames) {
            if (rname.EndsWith(tofind, StringComparison.CurrentCultureIgnoreCase)) {
                using (var stream = asm.GetManifestResourceStream(rname)) {
                    return new Icon(stream, size);
                }
            }
        }
        throw new ArgumentException("Icon not found");
    }

Sample usage:

        var icon1 = GetIconFromEmbeddedResource("ARW04LT", new Size(16, 16));
        var icon2 = GetIconFromEmbeddedResource("ARW04LT", new Size(32, 32));

Beware one possible failure mode: this code assumes that the icon was added to the same assembly that contains the method.

Hans Passant