.net - 如何向 System.Windows.Forms.MenuItem 添加图标?

标签 .net winforms menu contextmenu

我尝试将图标添加到我的上下文菜单项之一,但我无法做到。有谁能够帮助我?

这是我写的代码:

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

最佳答案

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!

关于.net - 如何向 System.Windows.Forms.MenuItem 添加图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10671585/

相关文章:

.net - 为什么在 Dispose() 方法中隐式提交工作单元不好?

c# - 如何在 RichTextBox 中获取点击的单词编号( Index )

c# - 开始使用 MVC 创建大型 C# 应用程序的最佳方法是什么?

c# - 如何在SendKeys中发送 "{}"

javascript - LastIndexOf 的作用是什么?

javascript - 菜单仅在一页上

.net - 可以通过名称实例化和调用委托(delegate)吗?

c# - 如何根据该页面上的链接从网页下载图片?

c# - 来自类库的引用不会复制到正在运行的项目 bin 文件夹

html - 菜单下拉显示在列中,CSS