[英]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
. 该资源名为
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: 在我使用设计器时Visual Studio自动生成的代码中,它看起来像这样:
((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).
通过设计器添加它不是一个选项(此按钮是以编程方式创建的,因此在设计器中不存在)。
You can use the Icon.ToBitmap
method for this purpose. 您可以使用
Icon.ToBitmap
方法来实现此目的。 Note that a Bitmap
is an Image
. 请注意,
Bitmap
是Image
。
CancelButton.Image = Properties.Resources.CancelButtonIcon.ToBitmap();
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. 不知道为什么,但是当我尝试使用接受的答案的方法时,
.ToBitmap()
调用给了我数组索引超出范围的异常。 I solved this by doing it this way instead: 我通过这样做来解决这个问题:
System.Drawing.Icon.FromHandle(Properties.Resources.CancelButtonIcon.Handle).ToBitmap();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.