2012-05-20 48 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:我链接的库是开源的,这意味着您可以查看代码,查看它的功能,并将其用作编写自己的代码的示例。 –