Search code examples
c#.netwinformstoolstriptoolstripdropdown

Get the (ToolStrip) parent of a ToolStripDropDownMenu


I am writing a custom ToolStripProfessionalRenderer

Take for example, the following override:

protected override void OnRenderImageMargin(ToolStripRenderEventArgs e)
{
    if(e.ToolStrip is MenuStrip)
    {
        // It never is. It's always ToolStripDropDownMenu
    }
}

I guess that OnRenderImageMargin is called by the drop down menu since this is what will be rendered, however I want to get the parent ToolStrip/MenuStrip/StatusStrip that caused the OnRenderImageMargin call.

Is this possible?


Solution

  • I thought the e.ToolStrip.Parent property would be the key, but it's always null.

    One option is to create a constructor in your ToolStripProfessionalRenderer, and pass in a reference to the control.

    class CustomRenderer : ToolStripProfessionalRenderer
    {
        // All those controls derive from ToolStrip so we can use the base class here
        private ToolStrip ts;
    
        public CustomRenderer(ToolStrip ts)
        {
            this.ts = ts;
        }
    
        protected override void OnRenderImageMargin(ToolStripRenderEventArgs e)
        {
            if (ts is MenuStrip)  
            {
            }
            else if (ts is StatusStrip)
            {
            }
            else  // ts is ToolStrip
            {
            }
        }
    

    Then pass a reference in when you instantiate it:

    toolStrip1.Renderer = new CustomRenderer(toolStrip1);
    
    statusStrip1.Renderer = new CustomRenderer(statusStrip1);
    

    An alternative option, modified from this answer.

    Forget the ctor and test the Owner repeatedly until you get the correct parent control:

    protected override void OnRenderImageMargin(ToolStripRenderEventArgs e)
    {
        ToolStrip owner = e.ToolStrip;
        while (owner is ToolStripDropDownMenu)
            owner = (owner as ToolStripDropDownMenu).OwnerItem.Owner;
    
        if (ts is MenuStrip)  
        {
        }
        else if (ts is StatusStrip)
        {
        }
        else  // ts is ToolStrip
        {
        }      
    }