主题:哪位大虾知道菜单栏中选项前面如何添加图标?
mikechen2003
[专家分:0] 发布于 2005-08-01 11:23:00
急!
回复列表 (共1个回复)
沙发
ryowu [专家分:6470] 发布于 2005-08-01 12:35:00
给你个例子
使用例子:
给menu2添加如下两个事件代码
private void menuItem2_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
DrawColorMenuItem(e,"新建(&N)","29.ico");
}
private void menuItem2_MeasureItem(object sender, System.Windows.Forms.MeasureItemEventArgs e)
{
e.ItemWidth = 140;
e.ItemHeight = 22;
}
属性ownerDraw改为True
以下是两个重要的实现函数,其他的相信大家都会自己添加使用吧。
/// <summary>
/// 获取资源文件
/// </summary>
/// <param name="strname"></param>
/// <returns></returns>
private System.IO.Stream GetEmbeddedResource(string strname)
{
return System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(strname);
}
/// <summary>
/// 绘制多彩菜单
/// </summary>
/// <param name="e"></param>
/// <param name="text">要显示的文本</param>
/// <param name="resName">资源里面的文件名</param>
private void DrawColorMenuItem(System.Windows.Forms.DrawItemEventArgs e,string text,string resName)
{
Graphics g = e.Graphics;
Rectangle aRect = new Rectangle(); //绘制图标的矩形区域
aRect.X = e.Bounds.X+3 ;
aRect.Y = e.Bounds.Y+4;
aRect.Height = 16;
aRect.Width = 16;
if((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{//判断菜单项是否被选中,填充不同颜色
g.FillRectangle(new SolidBrush(Color.FromArgb(182,189,210)),e.Bounds.X,e.Bounds.Y,e.Bounds.Width,e.Bounds.Height);
//g.FillRectangle(new System.Drawing.Drawing2D.LinearGradientBrush(e.Bounds, Color.MidnightBlue, Color.LightBlue, .0),e.Bounds);
g.DrawRectangle(new Pen(Color.FromArgb(10,36,106),1),e.Bounds.X,e.Bounds.Y,e.Bounds.Width-1,e.Bounds.Height-1);
}
else
{
g.FillRectangle(new SolidBrush(Color.LightGray),e.Bounds.X,e.Bounds.Y,22,22);
g.FillRectangle(new SolidBrush(Color.White),e.Bounds.X+22,e.Bounds.Y,e.Bounds.Width-22,e.Bounds.Height);
}
Icon anIcon; //各菜单项实用的图标
anIcon = new Icon(GetEmbeddedResource("iconMenuTest." + resName));
g.DrawIcon(anIcon,aRect); //绘制图标,然后写菜单文本
Font m_Font = new Font("宋体", 9);
StringFormat sf = new StringFormat();
sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.Show;
sf.SetTabStops(60, new float [0]);
SolidBrush br = new SolidBrush(Color.Black);
e.Graphics.DrawString(text,m_Font,br,e.Bounds.X + 30,e.Bounds.Y + 6,sf);
}
我来回复