我的方法是重写MenuItem类,在写的过程中发现用GDI+实际测量出来的文本的大小不是很准确,还有文本也不能很好对齐,固在代码里可以时常看到很多多加上去的数字.我想原理就不用我讲了吧,下面的代码注释的很
清楚了:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace OfficeMenu
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
public class OfficeMenuItem:MenuItem
{
public OfficeMenuItem(bool IsApplyOfficeMenu,string ItemText)
{
if(IsApplyOfficeMenu)
{
this.Text=ItemText;
this.OwnerDraw=true;
font=new Font("宋体",9f,GraphicsUnit.Point);
}
else
{
this.Text=ItemText;
this.OwnerDraw=false;
}
}
private Font font;
private StringFormat strFormat=new StringFormat();
private string ItemText="";
private string iconPath="";
//定义绘制的时候的各种笔刷
private LinearGradientBrush TopMenuHostLightBrush;
private SolidBrush TopMenuDefaultBrush;
private SolidBrush FontDefaultBrush;
private LinearGradientBrush TopMenuSelectedBrush;
private SolidBrush MenuDefaultBrush;
private SolidBrush MenuDefaultSelectedBrush;
private SolidBrush MenuCheckBrush;
private LinearGradientBrush MenuSideBarBrush;
private SolidBrush MenuDefaultGrayedBrush;
//定义绘制的时候所需的各种线条
private Pen TopMenuPen;
private Pen MenuDefaultPen;
//定义需要的矩形结构
private Rectangle SideBarRect;
private Rectangle CheckedRect;
private Rectangle TopMenuRect;
private Rectangle ShortcutRect;
//定义图标
public string IconPath
{
get
{
return iconPath;
}
set
{
iconPath=value;
}
}
//判断菜单是否是顶级菜单
private bool CheckIsTop()
{
if(typeof(MainMenu)==this.Parent.GetType())
{
return true;
}
else
{
return false;
}
}
//获取菜单的快捷键
private string GetShortCut()
{
string shortcut="";
try
{
if(this.ShowShortcut==true && (!this.IsParent) && (!(this.Shortcut==Shortcut.None)))
{
shortcut=this.Shortcut.ToString();
shortcut=shortcut.Replace("Ctrl","Ctrl+");
shortcut=shortcut.Replace("Alt","Alt+");
shortcut=shortcut.Replace("Shift","Shift+");
}
}
catch
{
return "";
}
return shortcut;
}
//重写测量函数
protected override void OnMeasureItem(MeasureItemEventArgs e)
{
base.OnMeasureItem (e);
try
{
ItemText=this.Text;
SizeF SizeMenuText;
if(this.ItemText=="-") //设置分割线的高度
{
e.ItemHeight=5;
return;
}
string getedShortcut=this.GetShortCut();
if(!this.CheckIsTop()) //如果不是顶级菜单
{
SizeMenuText=e.Graphics.MeasureString(ItemText+"".PadRight(4,' ')+getedShortcut,this.font);
e.ItemWidth=Convert.ToInt32(SizeMenuText.Width)+26;
}
else
{
SizeMenuText=e.Graphics.MeasureString(ItemText,this.font);
e.ItemWidth=Convert.ToInt32(SizeMenuText.Width)-4;
}
if(this.Visible)
{
e.ItemHeight=Convert.ToInt32(SizeMenuText.Height)+6;
}
else
{
e.ItemHeight=0;
}
}
catch
{
e.ItemHeight=20;
e.ItemWidth=80;
}
}
//重写绘图函数
protected override void OnDrawItem(DrawItemEventArgs e)
{
if(this.Visible)
{
base.OnDrawItem (e);
Rectangle MenuRect=e.Bounds;
ItemText=this.Text;
Graphics g=e.Graphics;
//绘制边框时需要的特殊矩形
SideBarRect=new Rectangle(MenuRect.X,MenuRect.Y,25,MenuRect.Height);