C# 如何在菜单项中放置图标
有没有办法在菜单项中的文本旁边放置图标 当用户右键单击用户控件时,我使用以下代码显示弹出菜单:C# 如何在菜单项中放置图标,c#,.net,winforms,.net-2.0,C#,.net,Winforms,.net 2.0,有没有办法在菜单项中的文本旁边放置图标 当用户右键单击用户控件时,我使用以下代码显示弹出菜单: ContextMenu menu = new ContextMenu(); MenuItem item = new MenuItem("test", OnClick); menu.MenuItems.Add(item); menu.Show(this, this.PointToClient(MousePosition)); 我想在弹出菜单中“test”字符串的左侧放置一个图标,以便用户更容易
ContextMenu menu = new ContextMenu();
MenuItem item = new MenuItem("test", OnClick);
menu.MenuItems.Add(item);
menu.Show(this, this.PointToClient(MousePosition));
我想在弹出菜单中“test”字符串的左侧放置一个图标,以便用户更容易识别它。除了将OwnerDraw属性设置为true(因此需要我自己完全绘制菜单项,就像在本例中所做的那样:)之外,还有其他方法可以做到这一点吗
感谢您的帮助 使用ContextMenuStrip控件,因为您可以在设计器中通过单击项目并选择“设置图像…”或通过编程方式更改ToolStripMenuItem的图像属性来执行此操作 尝试使用ContextMenuStrip并向其添加ToolStripMenuItems
如果必须使用MenuItem,则必须通过DrawItem事件执行,OwnerDraw属性设置为true。这是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));
如果您被绑定到
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,
});
希望这能有所帮助。@Bolu-查看此链接-System.Windows.Forms.MenuItem没有这样的属性,至少在.Net 2中没有。0@BaGi-看看这个链接-@Bibhu,你的链接是针对WPF中通常使用的
System.Windows.Controls.MenuItem
。。那上面的投票从哪里来?@Bibhu:你提到的链接是指.Net 4.0,而我使用的是2.0。你能用ContextMenuStrip
代替ToolStripMenuItem
吗?在这种情况下,可以设置ToolStripMenuItem.Image
。ContextMenuStrip当然能胜任这项工作。我不知道它的存在。非常感谢!这对我不起作用——主要是我必须实现MeasureItem
事件。。。还必须绘制文本和选择矩形。