[英]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;
}
注意:
除了提供的有關如何在上面的鏈接中添加資源的信息之外,您還可以按如下方式添加它們
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.