How to put an icon in a MenuItem
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 C开发者_如何学编程ontextMenu();
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.
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.
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));
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.
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.
精彩评论