我尝试将图标添加到我的上下文菜单项之一,但我无法做到。有谁能够帮助我?
这是我写的代码:
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 开始,菜单看起来完全不同,这也是您的用户对您的应用程序的期望。世界上最酷的图标不会让你看起来更现代。相比:
因此,更复杂的解决方案是坚持使用 MainMenu
控件,它实际上使用 Windows 本身绘制的菜单,但编写了一些处理添加图标的代码。
幸运的是,Wyatt O'Day 已经编写了一个很棒的自定义控件,可以为您执行此操作。您所要做的就是下载它,将其放入您的项目中,编译并开始使用它。它是开源的,在 BSD 许可下获得许可,它生成的菜单在所有版本的 Windows 上看起来都是平台原生的。下载 here from his website ,或以 his introduction and 100% accurate rant 开头.
结果是真棒 :
关于.net - 如何向 System.Windows.Forms.MenuItem 添加图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10671585/