I tried to add an icon to one of my context menu items, but I couldn't do it. Can anybody help me?
Here's the code I've written:
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;
}
}
You can easily add icons to your menu items if you wish. Open your menu item, click Select for the "Icon" field, an icon panel will open where you can select your icon.
You can add menus to Windows Forms at design time by adding the MainMenu component and then appending menu items to it using the Menu Designer. After drag the Menustrip on your form you can directly create the menu items by type a value into the "Type Here" box on the menubar part of your form.
Lex Li's answer covers the simplest way to do this: switch from the MainMenu
control to the MenuStrip
control, which provides built-in, out-of-the-box support for adding icons to each menu item. Unfortunately, as I discussed in a comment to his answer, this solution has some ugly consequences.
In particular, if you use the MenuStrip
control, your menus will forever look ugly and out of place on newer versions of Windows because they're custom drawn by .NET code that will probably never be updated. Sure, they look slick on Windows XP, but that's been old news for at least 5 years. Menus look totally different starting with Windows Vista, and that's what your user will expect from your app, too. The coolest icons in the world just won't help you look any more modern. Compare:
So the somewhat more involved solution is to stick with the MainMenu
control, which actually uses menus drawn by Windows itself, but write some code that handles adding an icon.
And fortunately, Wyatt O'Day has already written a great custom control that does this for you. All you have to do is download it, drop it into your project, compile, and start using it. It's open-source, licensed under the BSD license, and it produces menus that look platform native on all versions of Windows. Download it here from his website, or start with his introduction and 100% accurate rant.
The results are awesome:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With