Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 487
Ricardo Altamirano Avatar asked Jun 22 '12 19:06

Ricardo Altamirano


People also ask

How do I add an image to a resource in Winforms?

Open the Visual Designer of the form containing the control to change. Select the control. In the Properties pane, select the Image or BackgroundImage property of the control. Select the ellipsis ( ) to display the Select Resource dialog box and then select the image you want to display.


2 Answers

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

CancelButton.Image = Properties.Resources.CancelButtonIcon.ToBitmap();
like image 113
Ani Avatar answered Sep 27 '22 22:09

Ani


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();
like image 35
HotN Avatar answered Sep 27 '22 22:09

HotN