c# - 更改 Windows 窗体应用程序中菜单的字体,.net3.5

标签 c# winforms .net-3.5 fonts

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

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 属性....

最佳答案

如果您使用的是 MainMenu,则不能直接执行此操作。你应该使用 MenuStrip相反。

如果你绝对必须使用MainMenu,你必须设置OwnerDraw MenuItem 的属性设置为 true 并覆盖/实现 DrawItemMeasureItem事件,以便您可以手动绘制它。


这是一个非常基本的自定义菜单项类;它绝不是完整的或功能齐全的,但它应该可以帮助您入门:

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

输出:

enter image description here

关于c# - 更改 Windows 窗体应用程序中菜单的字体,.net3.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12681806/

相关文章:

c# - 使用 XDocument 加载编码为 UTF 16 的 xml

C# WinForms 以其他形式更改数据库名称

c# - explain x => x.ToString()//简化这么多调用

.net - Windows 服务已启动但不执行任何操作 - .NET

.net - .NET 3.5 是媒体中心插件的合理先决条件吗?

c# - 预期为 "{"但发现为 ")"。在 Asp.Net MVC 5 中, block 语句必须包含在 "{"和 "}"中

c# - 异步 TPL 死锁与第三方 lib aka wild goose chase

c# - C# 中的帮助文件

c# - ASP.NET Core 中的 PostAsJsonAsync 方法在哪里?

c# - 以锯齿形顺序显示Excel数据?