您可以使用函数 SetMenuItemInfo 将图标添加到菜单项。
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
class Program
{
static void Main()
{
var menu = new ContextMenu();
menu.Popup += MenuItem_Popup;
SetMenuInfo(menu.Handle, new MENUINFO());
var item = menu.MenuItems.Add("Exit", (sender, e) => Application.Exit());
SetImage(item, Properties.Resources.Image1);
var notifyIcon = new NotifyIcon
{
Icon = Properties.Resources.Icon1,
ContextMenu = menu
};
notifyIcon.Visible = true;
Application.Run();
notifyIcon.Visible = false;
}
static Dictionary<MenuItem, IntPtr> MenuBitmaps = new Dictionary<MenuItem, IntPtr>();
static void SetImage(MenuItem item, Image img)
{
using (var bmp = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppPArgb))
{
using (var g = Graphics.FromImage(bmp)) g.DrawImage(img, 0, 0);
MenuBitmaps[item] = bmp.GetHbitmap(Color.FromArgb(0));
}
}
static void MenuItem_Popup(object sender, EventArgs e)
{
var info = new MENUITEMINFO();
int i = 0;
foreach (MenuItem item in ((Menu)sender).MenuItems)
if (item.Visible)
{
if (MenuBitmaps.TryGetValue(item, out info.hbmpItem))
SetMenuItemInfo(((Menu)sender).Handle, i, true, info);
i++;
}
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern bool SetMenuInfo(IntPtr hMenu, MENUINFO lpcmi);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern bool SetMenuItemInfo(IntPtr hMenu, int uItem, bool fByPosition, MENUITEMINFO lpmii);
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class MENUINFO
{
public int cbSize = Marshal.SizeOf(typeof(MENUINFO));
public int fMask = 0x10; //MIM_STYLE
public int dwStyle = 0x4000000; //MNS_CHECKORBMP
public uint cyMax;
public IntPtr hbrBack;
public int dwContextHelpID;
public IntPtr dwMenuData;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class MENUITEMINFO
{
public int cbSize = Marshal.SizeOf(typeof(MENUITEMINFO));
public int fMask = 0x80; //MIIM_BITMAP
public int fType;
public int fState;
public int wID;
public IntPtr hSubMenu;
public IntPtr hbmpChecked;
public IntPtr hbmpUnchecked;
public IntPtr dwItemData;
public IntPtr dwTypeData;
public int cch;
public IntPtr hbmpItem;
}
}