我有一个使用 ContextMenuStrip 的 C# winForm 项目。我根据使用交互动态地将 ToolStripMenuItems 添加到 ContextMenuStrip。当我添加一个新的 ToolStripMenuItem 时,我设置了它的 Text 属性和 Image 属性。我不知道如何在不从图像所在位置获取图像的情况下设置图像属性。如何将想象添加到我的项目中?这是我的代码正在做什么的示例
ContextMenuStrip cxtMnuStrp = new ContextMenuStrip; private void Button_Click(object sender, EventArgs e) { // some filtering and logic // to determine weather to // create and add a ToolStripMenuItem // blah, blah, blah... ToolStripMenuItem item = new ToolStripMenuItem("uniqueName"); item.Image = Image.FromFile(@"C:\MyFolder\MyIcon.ico"); if (cxtMnuStrp.Items.ContainsKey(item) == false) cxtMnuStrp.Items.Add(item); }
使用 "item.Image = Image.FromFile(@"C:\MyFolder\MyIcon.ico")"当我分发时我的每台机器都必须有 "C:\MyFoler"目录并且还有 "MyIcon .ico"在他们计算机上的“C:\MyFoler”目录中。
另外,每次我想向我的 ToolStripMenuItem 添加图标时,我都碰到了硬盘驱动器,这似乎不对
最佳答案
您可以将图标保存在资源文件中或将图像保存为嵌入资源。
使用资源文件。
将图像添加为嵌入资源
您的代码将如下所示。
private void BuildContextMenuStrip_Click(object sender, EventArgs e)
{
ContextMenuStrip cxtMnuStrp = new ContextMenuStrip();
ToolStripMenuItem item = new ToolStripMenuItem("uniqueName") { Image = WindowsFormsApplication2.Properties.Resources.Search.ToBitmap() };
if (cxtMnuStrp.Items.Contains(item) == false)
cxtMnuStrp.Items.Add(item);
this.ContextMenuStrip = cxtMnuStrp;
}
注意:
- 如果您在资源文件中添加了一个图标。您必须使用 .ToBitmap() 将其转换为图像。
- 图像现在可以在智能感知中使用,而不是使用路径字符串。
- 我已将 contextMenuStrip 添加到上面示例中的表单。
除了在上面的链接中提供的有关如何添加资源的信息外,您还可以按以下方式添加它们
关于c# - 如何将图像添加到 ToolStripMenuItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16181980/