ContextMenuStrip右键菜单原生样式只能显示一个图标配一个对应菜单文字,现在有一个需求是菜单项已经做成对应的图片,只需要显示对应图片而不需要显示文字,直接设置属性是无法实现的,下面说明实现方法
1.自定义一个继承ToolStripMenuItem控件的子控件MainToolStripMenuItem
using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace WinFormDemo.ToolStripMenu { public class MainToolStripMenuItem : ToolStripMenuItem { #region /// <summary>悬浮时</summary> [Category("MouseImageEnter"), Description("悬浮时背景")] public Image ImageMouseBack { get; set; } /// <summary>点击时</summary> [Category("MouseImageDown"), Description("点击时背景")] public Image ImageDownBack { get; set; } private Image normlback; /// <summary>初始时</summary> [Category("MouseImageNorml"), Description("初始时背景")] public Image ImageNormlBack { get { return normlback; } set { if (normlback != value) { normlback = value; this.Image = normlback; this.Invalidate(); } } } #endregion public MainToolStripMenuItem() { this.DisplayStyle = ToolStripItemDisplayStyle.Image; this.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.ShowShortcutKeys = false; } } }
2.自定义一个继承ToolStripProfessionalRenderer的子类StackRenderer
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Text; using System.Windows.Forms; namespace WinFormDemo.ToolStripMenu { internal class StackRenderer : ToolStripProfessionalRenderer { protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) {//实现鼠标按下/鼠标移动/无鼠标情况下显示不同图片 MainToolStripMenuItem toolItem = e.Item as MainToolStripMenuItem; if (toolItem == null) { base.OnRenderMenuItemBackground(e); } else { Graphics g = e.Graphics; ToolStrip toolStrip = e.ToolStrip; if (toolStrip is ContextMenuStrip) { if (e.Item.Pressed) { g.DrawImage(toolItem.ImageDownBack, new Point(-10, 0)); } else if (e.Item.Selected) { g.DrawImage(toolItem.ImageMouseBack, new Point(-10, 0)); } else { g.DrawImage(toolItem.ImageNormlBack, new Point(-10, 0)); } } } } protected override void OnRenderItemImage(ToolStripItemImageRenderEventArgs e) {//去掉前景图 //base.OnRenderItemImage(e); } protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) {//去掉边框 //base.OnRenderToolStripBorder(e); } } }
3.在需要右键菜单的控件上创建ContextMenuStrip对象contextMenuStrip1,添加第1步创建MainToolStripMenuItem类型的菜单项,并设置三个不同状态时要显示的图片,第一次无法添加MainToolStripMenuItem类型的菜单项将程序生成一下就可以添加了
4.设置要显示右键菜单控件的ContextMenuStrip属性为contextMenuStrip1
5.在要显示右键菜单控件的构造函数中增加
this.contextMenuStrip1.Renderer = new StackRenderer(); foreach (ToolStripMenuItem tsmi in this.contextMenuStrip1.Items) { tsmi.AutoSize = false; tsmi.Height = 32; tsmi.Click += (sender, e) => { MainToolStripMenuItem _item = sender as MainToolStripMenuItem; if (_item == null || !_item.Enabled) { return; } MessageBox.Show(_item.Tag.ToString(),"提示"); }; }
6.效果
7.完整代码下载
文章评论