3

我的表单上有一个菜单,定义如下:

private System.Windows.Forms.MainMenu mainMenu1;

//Then

private void InitializeComponent()
{
 this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components);
 this.Menu = this.mainMenu1;
}

我为整个表单设置了字体,但菜单项仍然忽略它。如何使菜单项的字体更大?我找不到 Menu 或 MenuItem 的 Font 属性......

4

1 回答 1

5

如果您使用的是MainMenu. 你应该使用 aMenuStrip代替。

如果您绝对必须使用MainMenu,则必须设置 to 的属性OwnerDraw并覆盖/实现and事件,以便您可以手动绘制它。MenuItemtrueDrawItemMeasureItem


这是一个非常基本的自定义菜单项类;它绝不是完整的或功能齐全的,但它应该让你开始:

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

和输出:

在此处输入图像描述

于 2012-10-01T22:14:18.970 回答