2012-05-20 46 views
4

我試圖給我的一個上下文菜單項添加一個圖標,但我做不到。有誰能夠幫助我?如何將圖標添加到System.Windows.Forms.MenuItem?

下面是我寫的代碼:

private System.Windows.Forms.ContextMenu notifyContextMenu; 
private void foo() { 
      if (notifyIcon == null) { 
       notifyIcon = new System.Windows.Forms.NotifyIcon(); 
      } 

      if (notifyContextMenu == null) { 
       notifyContextMenu = new System.Windows.Forms.ContextMenu(); 
       notifyContextMenu.MenuItems.Add("Exit"); 
       // How do I add an icon to this context menu item? 
      } 
      notifyIcon.ContextMenu = notifyContextMenu; 
      } 
    } 

回答

5

的MainMenu /文本菜單已經過時,您應該使用菜單條代替類。

變化

notifyContextMenu = new System.Windows.Forms.ContextMenu(); 
notifyContextMenu.MenuItems.Add("Exit"); 

notifyContextMenu = new System.Windows.Forms.ContextMenuStrip(); 
var exitMenuItem = notifyContextMenu.Items.Add("Exit"); 
exitMenuItem.Image = ...; 

http://msdn.microsoft.com/en-us/library/system.windows.forms.toolstripitem.image.aspx

最後附上上下文菜單條通知圖標,

notifyIcon.ContextMenuStrip = notifyContextMenu; 
+1

嗯,這不是真的。是的,「Strip」類更新,但它們會生成菜單,*在Windows Vista及更高版本上看起來*完全可惡。而不是要求Windows繪製菜單,它們都是用.NET代碼自定義繪製的。它們在Windows XP中看起來不錯,並且它們與Office XP中使用的自定義繪製菜單相匹配,但從那以後,技術發生了很大的變化。使用這些醜陋的菜單試圖避免過時看起來像對我來說是一個相當愚蠢的決定。你的應用程序永遠不會在現代版本的Windows上看起來不錯。 –

+0

儘管本機包裝在Windows Vista及更高版本上看起來效果更好,但通過自定義渲染器可以在條帶類中實現同樣的效果,http://code.google.com/p/szotar/source/browse/trunk/Client/ Szotar.WindowsForms/Base/NativeToolStripRenderer.cs –

+0

甚至沒有接近...(我已經嘗試過了,重新編寫了它,調整了它,嘗試了更多,不一樣,更糟糕的是,不管你做了多少它看起來像原生菜單,它不會像原生菜單那樣行爲。)但的確,更好的... –

9

Lex Li's answer涵蓋了最簡單的方法:從MainMenu控件切換到MenuStrip控件,該控件提供內置的開箱即用支持,用於爲每個菜單項添加圖標。不幸的是,正如我在a comment中對他的回答所討論的那樣,這個解決方案有一些醜陋的後果。

特別是,如果您使用MenuStrip控件,您的菜單在新版本的Windows上將永遠看起來很難看,因爲它們是由可能永遠不會更新的.NET代碼自定義繪製的。當然,他們在Windows XP上看起來很光滑,但這已經是至少5年的老消息了。從Windows Vista開始,菜單看起來完全不同,這也是您的用戶對您的應用程序的期望。世界上最酷的圖標不會幫助你看起來更現代。比較:

                              MenuStrip (and its little brother, ContextMenuStrip) look downright ugly on Windows Vista and later, compared to the platform native menus, as implemented with MainMenu (and its little brother, ContextMenu)

所以稍微複雜的解決方案是堅持與MainMenu控制,這實際上使用了Windows本身繪製的菜單,但編寫一些處理添加圖標的代碼。

幸運的是,Wyatt O'Day已經寫了一個很棒的自定義控件,可以爲你做到這一點。你所要做的就是下載它,放到你的項目中,編譯並開始使用它。它是開源的,在BSD許可下獲得許可,並且它生成的菜單在所有版本的Windows上生成的平臺本機版本。下載它here from his website,或從his introduction and 100% accurate rant開始。

的結果是真棒

                              Comparing the appearance of Wyatt's VistaMenu control on 4 different operating systems: Windows 7, Vista, XP, and 2000. On all 4, it looks just like the platform native menus, except with icons!

+0

重新使用VistaMenu之類的東西是一個更好的選擇。我同意。 –

+0

@Cody Gray,實際上我不想僅爲上下文菜單使用一些第三方庫。我想自己解決這個問題。但是如何?如果我的上下文菜單看起來像Vista菜單並且帶有圖像的menuItem,那將會很棒。我該怎麼辦? – Alexandre

+0

@Alex:我鏈接的庫是開源的,這意味着您可以查看代碼,查看它的功能,並將其用作編寫自己的代碼的示例。 –