如何在菜单项中添加图标

20
有没有办法在菜单项中的文本旁边放置一个图标?我使用以下代码在用户控件中右键单击时显示弹出菜单:
 ContextMenu menu = new ContextMenu();
 MenuItem item = new MenuItem("test", OnClick);
 menu.MenuItems.Add(item);
 menu.Show(this, this.PointToClient(MousePosition));

我想在弹出菜单中的“test”字符串左侧放置一个图标,以便用户更容易识别它。除了将OwnerDraw属性设置为true(从而要求完全自己绘制菜单项,就像在此示例中所做的那样:http://www.codeproject.com/KB/menus/cs_menus.aspx),还有其他方法吗?

感谢任何帮助。


2
你可以使用 ContextMenuStripToolStripMenuItem 吗?在这种情况下,您可以设置 ToolStripMenuItem.Image。http://msdn.microsoft.com/en-us/library/system.windows.forms.contextmenustrip.aspx - Bolu
4个回答

19

尝试使用ContextMenuStrip并向其添加ToolStripMenuItems。

如果必须使用MenuItem,则必须通过设置OwnerDraw属性为true的DrawItem事件来完成。


ContextMenuStrip确实能胜任这项工作。我之前不知道它的存在。非常感谢! - Bart Gijssens

11

这个问题在6年前的.NET 2.0版本中被解决了。它引入了ToolStrip类。代码非常相似:

        var menu = new ContextMenuStrip();
        var item = new ToolStripMenuItem("test");
        item.Image = Properties.Resources.Example;
        item.Click += OnClick;
        menu.Items.Add(item);
        menu.Show(this, this.PointToClient(MousePosition));

4

如果您正在使用 MenuItem,那么我发现解决方案应该像这样:

var dropDownButton = new ToolBarButton();
dropDownButton.ImageIndex = 0;
dropDownButton.Style = ToolBarButtonStyle.DropDownButton;

var mniZero = new MenuItem( "Zero", (o, e) => DoZero() );
mniZero.OwnerDraw = true;
mniZero.DrawItem += delegate(object sender, DrawItemEventArgs e) {
    double factor = (double) e.Bounds.Height / zeroIconBmp.Height;
    var rect = new Rectangle( e.Bounds.X, e.Bounds.Y,
                         (int) ( zeroIconBmp.Width * factor ),
                         (int) ( zeroIconBmp.Height * factor ) );
    e.Graphics.DrawImage( zeroIconBmp, rect );
};

var mniOne = new MenuItem( "One", (o, e) => DoOne() );
mniOne.OwnerDraw = true;
mniOne.DrawItem += delegate(object sender, DrawItemEventArgs e) {
    double factor = (double) e.Bounds.Height / oneIconBmp.Height;
    var rect = new Rectangle( e.Bounds.X, e.Bounds.Y,
                     (int) ( oneIconBmp.Width * factor ),
                     (int) ( oneIconBmp.Height * factor ) );
    e.Graphics.DrawImage( oneIconBmp, rect );
};

dropDownButton.DropDownMenu = new ContextMenu( new MenuItem[]{
    mniZero, mniOne,
});

希望这能帮到您。

这对我没有用 - 主要是因为我不得不实现 MeasureItem 事件... 还必须绘制文本和选择矩形。 - Andy

1
使用ContextMenuStrip控件,在其中可以通过在设计器中点击项目并选择“设置图像…”或编程方式更改ToolStripMenuItem的Image属性来执行此操作。

@Bolu - 请查看此链接- http://msdn.microsoft.com/zh-cn/library/system.windows.controls.menuitem.icon.aspx - Bibhu
System.Windows.Forms.MenuItem在.Net 2.0中没有这样的属性,至少目前还没有。 - Bart Gijssens
@BaGi - 看一下这个链接 - http://msdn.microsoft.com/zh-cn/library/system.windows.controls.menuitem.icon.aspx - Bibhu
@Bibhu,你提供的链接是关于System.Windows.Controls.MenuItem的,通常在WPF中使用。至于“Upvote”是从哪里来的? - Bolu
@Bibhu:你提到的链接是关于 .Net 4.0 的,而我正在使用 2.0 版本。 - Bart Gijssens

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接