ToolStripButton:以编程方式分配图像有什么问题

有一个带有ToolStrip的表单。 此ToolStrip包含ToolStripButton。 我想为此按钮指定图像:

this.btnSaveFile.Image = Bitmap.FromFile("C:\\Work\\Icons\\png\\save.png"); 

仅当指定路径上有save.png时才有效。 否则,我得到一个FileNotFoundexception。

如果我通过表单设计器创建了一个表单,Visual Studio将创建如下代码:

 this.toolStripButton9.Image = ((System.Drawing.Image) (resources.GetObject("toolStripButton9.Image"))); 

toolStripButton9.Image这里不是真名。 Visual Studio将我的文件save.png删除并将其转换为toolStripButton9.Image。

但我以编程方式创建了一个表单,没有Designer。 我的问题是如何以编程方式将图像分配给ToolStripBotton?

我试图将图像添加到项目中,但它没有多大帮助。 我不知道如何让Visual Studio抓住它并嵌入到我的可执行文件中,以便我不需要在指定位置使用此文件。

在MSDN中,我只看到这样的解决方案:

 this.toolStripButton1.Image = Bitmap.FromFile("c:\\NewItem.bmp"); 

但它并没有像我上面所说的那样起作用。 我知道有一个简单的解决方案,但没有看到它。 你能给我一个提示吗?

在Visual Studio中,在解决方案资源管理器中打开“属性”文件夹,然后打开Resources.resx文件并将现有图像文件添加为资源。 然后,您可以通过Resource静态类以编程方式使用它:

 Image x = Resources.MyResourceImage; 

我建议的代码的完整示例:

 using System.Windows.Forms; using Testapplication.Properties; namespace Testapplication { public class Class1 { public Class1() { Form MyForm = new Form(); ToolStrip MyToolStrip = new ToolStrip(); MyForm.Controls.Add(MyToolStrip); ToolStripButton MyButton = new ToolStripButton(); MyToolStrip.Items.Add(MyButton); MyButton.Image = Resources.MyResourceImage; MyForm.Show(); } } } 

不要忘记在YourApps的Properties命名空间中添加一个使用。 您的Resources.resx(.cs)文件驻留在该命名空间中,用于提供类似图像的强类型对象引用。 在您的情况下,将“MyResourceImage”替换为“save”(省略引号)。

PS。 浏览一下我的Resources.designer.cs文件中最重要的部分:

 internal static System.Drawing.Bitmap MyResourceImage { get { object obj = ResourceManager.GetObject("MyResourceImage", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } 

所以你的意思是从嵌入式资源设置图像?

 string res = "MyAssembly.Resources.toolStripButton9.Image"; Stream s = this.GetType().Assembly.GetManifestResourceStream( res ); Icon icon = Icon.FromStream( s ); 

使用Webleeuws答案,如果它有效,比这更容易:P