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

c#, icons, resources, winforms

Solution

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

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

Problem

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).

Original source

Related problems