如果您使用的是MainMenu
. 你应该使用 aMenuStrip
代替。
如果您绝对必须使用MainMenu
,则必须设置 to 的属性OwnerDraw
并覆盖/实现and事件,以便您可以手动绘制它。MenuItem
true
DrawItem
MeasureItem
这是一个非常基本的自定义菜单项类;它绝不是完整的或功能齐全的,但它应该让你开始:
using System.Windows.Forms;
using System.Drawing;
class CustomMenuItem : MenuItem
{
private Font _font;
public Font Font
{
get
{
return _font;
}
set
{
_font = value;
}
}
public CustomMenuItem()
{
this.OwnerDraw = true;
this.Font = SystemFonts.DefaultFont;
}
public CustomMenuItem(string text)
: this()
{
this.Text = text;
}
// ... Add other constructor overrides as needed
protected override void OnMeasureItem(MeasureItemEventArgs e)
{
// I would've used a Graphics.FromHwnd(this.Handle) here instead,
// but for some reason I always get an OutOfMemoryException,
// so I've fallen back to TextRenderer
var size = TextRenderer.MeasureText(this.Text, this.Font);
e.ItemWidth = (int)size.Width;
e.ItemHeight = (int)size.Height;
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
e.DrawBackground();
e.Graphics.DrawString(this.Text, this.Font, Brushes.Blue, e.Bounds);
}
}
这是一个 3-deep 测试用法:
MainMenu mainMenu = new MainMenu();
MenuItem menuFile = new CustomMenuItem("File");
MenuItem menuOpen = new CustomMenuItem("Open");
MenuItem menuNew = new CustomMenuItem("New");
public MenuTestForm()
{
InitializeComponent();
this.Menu = mainMenu;
mainMenu.MenuItems.Add(menuFile);
menuFile.MenuItems.Add(menuOpen);
menuOpen.MenuItems.Add(menuNew);
}
和输出: