Reputation: 27693
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....
Upvotes: 3
Views: 4589
Reputation: 7674
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:
Upvotes: 5