【问题标题】:Display a logo in a contextmenustrip在上下文菜单条中显示徽标
【发布时间】:2013-08-15 20:19:59
【问题描述】:

我正在 .net 2.0 中开发一个 winforms 应用程序。

我想知道如何在附加到通知图标的上下文菜单中显示徽标。

它不是显示在文本旁边的那种图标。它是跨越整行的那种,通常用于显示公司徽标。抱歉,我还不能发布图片。

编辑:

ContextMenuStrip1.Items.Add(new ToolStripMenuItem(String, Image) )

但是,这只会给我一个图标,旁边有一些文本在一行中,当光标悬停在它上面时,它将被突出显示。

我想要实现的是在没有任何文本的单行中显示图像,并且当光标悬停或可点击时无法突出显示。

【问题讨论】:

    标签: c# winforms contextmenustrip


    【解决方案1】:

    解决方案非常简单。您必须使用自定义ToolStripRenderer 并覆盖OnRenderImageMargin method。您还需要准备一个大小合适的徽标图片。

    代码如下:

    public class Form1 : Form {
       public Form1(){
          InitializeComponent();
          // This contextMenuStrip is used for your Notify Icon
          // Just show it as you do
          contextMenuStrip1.Renderer = new CustomRenderer();
       }
    }
    public class CustomRenderer : ToolStripProfessionalRenderer
    {            
       protected override void OnRenderImageMargin(ToolStripRenderEventArgs e)
       {
          e.Graphics.DrawImage(yourImage, e.AffectedBounds);
       }
    }
    

    注意:您的图像应该已经旋转了 90 度。否则你将不得不在绘制之前使用代码旋转它。

    这是上面代码的截图,使用了 Stack Overflow 标志:

    编辑后,您似乎想要一些不同的东西。您可能希望显示拉伸项目整个区域的徽标。我想这是最后一项。您必须使用Text = string.Empty 添加一个项目。代码如下:

    public class Form1 : Form {
       public Form1(){
          InitializeComponent();
          // This contextMenuStrip is used for your Notify Icon
          // Just show it as you do
          contextMenuStrip1.Renderer = new CustomRenderer(){RootToolStrip = contextMenuStrip1};
          //Add your last item first
          int lastItemIndex = contextMenuStrip1.Items.Count - 1;
          contextMenuStrip1.Items[lastItemIndex].AutoSize = false;
          contextMenuStrip1.Items[lastItemIndex].Text = "";
          contextMenuStrip1.Items[lastItemIndex].Height = 40;
       }
    }
    public class CustomRenderer : ToolStripProfessionalRenderer
    {    
       public ToolStrip RootToolStrip;        
       protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e)
       {
            int i = e.ToolStrip.Items.Count - 1;
            if (e.ToolStrip.Items.IndexOf(e.Item) == i&&e.ToolStrip == RootToolStrip)
            {
               e.Graphics.DrawImage(yourImage, new Rectangle(0,0,e.Item.Width, e.Item.Height));
            } else base.OnRenderMenuItemBackground(e);
       }
    }
    

    屏幕截图:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      • 2019-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多