簡體   English   中英

如何將圖像添加到ToolStripMenuItem

[英]How to add image to ToolStripMenuItem

我有一個使用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上添加一個圖標時,我都點擊硬盤驅動器似乎不對

您可以將圖標保存在資源文件中,也可以將圖像另存為嵌入式資源。

使用資源文件。

將圖像添加為嵌入式資源

您的代碼將如下所示。

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. 圖像現在可以在intellisense中使用,而不是使用路徑字符串。
  3. 我已將contextMenuStrip添加到上面示例中的表單中。

除了提供的有關如何在上面的鏈接中添加資源的信息之外,您還可以按如下方式添加它們

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM