Question

I am developing a winforms application in .net 2.0.

I am wondering how to display a logo in a contextmenustrip attached to a notification icon.

It's not the kind of icon that displays next to text. It is the kind that spans the whole row and is usually used to display a company logo. Apologies that I can't post a image yet.

EDIT:

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

But, this only gives me an icon with some texts next to it in a single row and when cursor hovers over it, it will be highlighted.

What I want to achieve is to display an image across the single row without any text and it cannot be highlighted when cursor hovers over or clickable.

Was it helpful?

Solution

The solution is very simple. You have to use a custom ToolStripRenderer and override the OnRenderImageMargin method. You will also need to prepare a logo image with a suitable size.

Here is the code:

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);
   }
}

Note: Your image should already be rotated 90 degrees. Otherwise you will have to rotate it using code before drawing.

Here is the screenshot of the above code, using the Stack Overflow logo:

enter image description here

After your edit, it looks like that you want something different. You may want to show the logo stretching the whole region of an item. I suppose that's the last item. You have to add an item with Text = string.Empty. Here is the code:

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);
   }
}

Screen shot:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top