如何将图像添加到ToolStripMenuItem

时间:2013-04-24 01:40:51

标签: c# winforms

我有一个使用ContextMenuStrip的C#winForm项目。我根据使用交互动态地将ToolStripMenuItems添加到ContextMenuStrip。当我添加一个新的ToolStripMenuItem时,我设置了它的Text属性和Image属性。我不知道如何设置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中添加图标时,我都点击了硬盘驱动器

1 个答案:

答案 0 :(得分:7)

您可以将图标保存在资源文件中,或将图像另存为嵌入资源。

使用资源文件。

将图像添加为嵌入资源

您的代码将如下所示。

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;
}

注意:

  1. 如果您在资源文件中添加了图标。您必须使用 .ToBitmap()将其转换为图像。
  2. 图像现在可以在智能感知中使用,而不是使用路径字符串。
  3. 我已将contextMenuStrip添加到上例中的表单。
  4. 除了提供的有关如何在上面的链接中添加资源的信息之外,您还可以按如下方式添加它们

    enter image description here

相关问题