简体   繁体   中英

Changing the font for menu in the Windows Forms application, .net3.5

I have a menu on my form that is defined as follows:

private System.Windows.Forms.MainMenu mainMenu1;

//Then

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

I set the font for the entire form, but the Menu items still ignore it. How do I make the font bigger for the Menu items? I can't find Font property for the Menu or MenuItem....

You can't do it directly if you're using a MainMenu . You should be using a MenuStrip instead.

If you absolutely must use MainMenu , you have to set the OwnerDraw property of the MenuItem to true and override/implement the DrawItem and MeasureItem events so that you can manually paint it.


Here's a very basic custom menu item class; it's by no means complete or fully functional, but it should get you started:

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

Here's a 3-deep test usage:

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

And the output:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM