How to put an icon in a MenuItem

强颜欢笑 提交于 2019-12-13 06:41:25

问题


Is there a way to put an icon next to the text in a MenuItem?

I use the following code to display a popup menu when the user right clicks in a user control:

 ContextMenu menu = new ContextMenu();
 MenuItem item = new MenuItem("test", OnClick);
 menu.MenuItems.Add(item);
 menu.Show(this, this.PointToClient(MousePosition));

I would like to put a icon to the left of the "test" string in the popup menu so that the user more easily recognizes it. Is there a way to do this other than by setting the OwnerDraw property to true (thus requiring me to completely draw the menu item myself, like it is done in this example: http://www.codeproject.com/KB/menus/cs_menus.aspx)?

Any help is appreciated.


回答1:


Try using ContextMenuStrip and add ToolStripMenuItems to it.

If you have to use MenuItem, you will have to do it through the DrawItem event with the OwnerDraw property set to true.




回答2:


This was fixed 6 years ago with the .NET 2.0 release. It acquired the ToolStrip classes. The code is very similar:

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



回答3:


If you are tied to MenuItem, then I've found the solution to be like this one:

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

Hope this helps.




回答4:


Use ContextMenuStrip control, in that you can do that either it in the designer, by clicking on the item and selecting "Set image...", or programmatically by changing the Image property of the ToolStripMenuItem.



来源:https://stackoverflow.com/questions/15393448/how-can-i-place-an-image-on-a-system-windows-forms-menuitem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!