http://www.codeproject.com/csharp/vsnetmenu.asp

解决方案 »

  1.   

    感谢您使用微软产品。在C#中,您可以通过自己绘制菜单项的方式来定制菜单。
    首先,需设置该菜单项,如menuItemExit菜单项的OwnerDraw属性为true;
    然后,需要处理menuItemExit菜单项的MeasureItem事件的响应方法menuItemExit_MeasureItem(object sender, System.Windows.Forms.MeasureItemEventArgs e)和该菜单项的DrawItem事件的响应方法private void menuItemExit_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)。
    其中:
    MeasureItem:用于设置菜单项的高度和宽度;
    DrawItem:用来绘制实际的菜单项,包括图标,文本等等。
    下面提供一段示例代码,用来实现加图标exit.bmp的菜单项menuItemExit,可供您参考:
    private void menuItemExit_MeasureItem(object sender, System.Windows.Forms.MeasureItemEventArgs e)
    {
    e.ItemHeight = 25;
    e.ItemWidth = 75;
    }private void menuItemExit_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
    {
    Rectangle rc = new Rectangle(e.Bounds.X,e.Bounds.Y,e.Bounds.Width,e.Bounds.Height);
    e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),rc);
    MenuItem s = (MenuItem)sender;
    string strItem = s.Text;
    StringFormat sf = new StringFormat();
    sf.Alignment = StringAlignment.Far;
    sf.LineAlignment = StringAlignment.Center;
    e.Graphics.DrawString(strItem,new Font("Veranda",10), new SolidBrush(Color.Blue),rc,sf);
    e.Graphics.DrawRectangle(new Pen(new SolidBrush(Color.LightGray)),rc);
    if(e.State ==(DrawItemState.NoAccelerator | DrawItemState.Selected))
    {
    e.Graphics.FillRectangle(new SolidBrush(Color.CornflowerBlue),rc);
    e.Graphics.DrawString(strItem,new Font("Veranda",10,FontStyle.Bold|FontStyle.Underline),new SolidBrush(Color.Yellow),rc,sf);
    e.Graphics.DrawRectangle(new Pen(new SolidBrush(Color.Black)),rc);
    //Draws a focus rectangle within the bounds specified in the DrawItemEventArgs constructor.
    e.DrawFocusRectangle();
    } Image imgExit = new Bitmap("exit.bmp");
    SizeF sz = imgExit.PhysicalDimension ;
    e.Graphics.DrawImage(imgExit,e.Bounds.X + 5,(e.Bounds.Bottom + e.Bounds.Top)/2 - sz.Height/2);
    }
     — 微软全球技术中心 VB支持中心本贴子以“现状”提供且没有任何担保,同时也没有授予任何权利。具体事项可参见使用条款(http://support.microsoft.com/directory/worldwide/zh-cn/community/terms_chs.asp)。
    为了为您创建更好的讨论环境,请参加我们的用户满意度调查(http://support.microsoft.com/directory/worldwide/zh-cn/community/survey.asp?key=(S,49854782))。