How do I cast an icon from a resource file to an image for use on a button?

11,006

Solution 1

You can use the Icon.ToBitmap method for this purpose. Note that a Bitmap is an Image.

CancelButton.Image = Properties.Resources.CancelButtonIcon.ToBitmap();

Solution 2

Not sure why, but any time I tried using the accepted answer's approach, the .ToBitmap() call was giving me array index out of bounds exceptions. I solved this by doing it this way instead:

System.Drawing.Icon.FromHandle(Properties.Resources.CancelButtonIcon.Handle).ToBitmap();
Share:
11,006
Ricardo Altamirano
Author by

Ricardo Altamirano

Originally from Nicaragua, educated in Edinburgh and the USA, and now living primarily in London. Useful questions and answers Stack Overflow Debugging CREATE TABLE statements Logging in Python Simple string formatting in Python Reference types in C# String compression in C# using Gzip Meta Stack Overflow Book recommendation questions Answering old questions with a solution in the comments IT Security Cryptographically secure random strings in PHP LaTeX Fitting a table on a page through rotation StackExchange Flair

Updated on June 04, 2022

Comments

  • Ricardo Altamirano
    Ricardo Altamirano almost 2 years

    I'm trying to use an icon that I've added as a resource as the image on a button. I know it's possible because I can do it in other projects through the designer. However, I'm trying to do this with code. I added the icon as a resource to my project by following the steps in the accepted answer to this question. The resource is named CancelButtonIcon.

    Now, I'm trying to add that icon as the image on a standard button with this code:

    this.CancelButton.Image = (System.Drawing.Image)Properties.Resources.CancelButtonIcon;
    

    However, I get an error message:

    Cannot convert type 'System.Drawing.Icon' to 'System.Drawing.Image'
    

    In the code that Visual Studio automatically generates when I use the designer, it looks like this:

    ((System.Drawing.Image)(resources.GetObject("SaveButton.Image")));
    

    which results from manually adding a resource through the Properties window. How can I convert this icon resource to an image so it can be used on the button? Adding it through the designer is not an option (this button is created programmatically and thus isn't present in the designer).