2

I found that while trying to find the owning toolstrip of an item, it wasn't a easy as just looking at the owner of the item. Below is some pseudo code that I think should work. Can anyone see any problems with this or should it work in all cases?

(1) Is type of Item.Owner a ToolStrip?

(2) Yes, Return Item.Owner

(3) No, Item = Item.OwnerItem. Go to (1).

ETA:

I'd like to make the test a general test. So instead of testing for ToolStrip, I should be testing for ToolStrip, MenuStrip, StatusStrip or ContextMenuStrip.

What makes the 4 mentioned above different to other ToolStrip derived controls such as ToolStripDropDown, ToolStripDropDownMenu and ToolStripOverflow?

ETA2: Ignore, absolute carp!

As far a I can tell, it's something to do with Control.TopLevelControl. The 3 controls above that can't be added to a form return a TopLevelControl of themselves. The 4 valid controls return nothing for TopLevelControl, before being added to a form, and then the form itself, after being added.

Jules
  • 4,319
  • 3
  • 44
  • 72
  • Is this a ToolStripItem? The Owner property of the ToolStripItem returns a ToolStrip. Is that not working? – Jacob G Feb 12 '10 at 21:59
  • It's a ToolStripMenuItem that belongs to a ToolStripDropDownButton. However, when you add certain items, like the DropDownButton, it seems to create an invisible ToolStripDropDownMenu item that derives from ToolStrip. This is what is returned when you look at owner. The owner of the ToolStripDropDownMenu is nothing. – Jules Feb 12 '10 at 22:07

3 Answers3

5

This worked:

        ToolStrip owner = testToolStripMenuItem.Owner;
        while (owner is ToolStripDropDownMenu)
            owner = (owner as ToolStripDropDownMenu).OwnerItem.Owner;
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Hi, thanks for that. Can you have a look at my eta and see how this could work for any valid toolstrip derived control. Cheers. – Jules Feb 12 '10 at 22:29
  • 1
    If You are using a `ContextMenuStrip` then the above need modification to `while (owner is ToolStripDropDownMenu && !owner is ContextMenuStrip)` since `ContextMenuStrip` inherit from `ToolStripDropDownMenu` – NiKiZe Mar 29 '17 at 10:51
1

If you are handling a click event for a drop down menu item as follows:

 private void testItemToolStripMenuItem_Click(object sender, EventArgs e)
 {
    ToolStripDropDownItem item = sender as ToolStripDropDownItem;
    ToolStripDropDown menu = item.DropDown;
    ToolStripItem ownerItem = item.OwnerItem;
    ToolStrip toolStrip = item.Owner;
 }
Michael
  • 3,821
  • 2
  • 19
  • 18
  • Hi, that won't work. You can nest sideways and have multiple ToolStripDropDown menus. You need to do a loop like my pseudo code or nobugz example. – Jules Feb 12 '10 at 22:45
  • Ah, I see what you're saying for nested DropDown menu items. – Michael Feb 12 '10 at 23:14
0

Try item.Parent instead of item.Owner.

Steve Danner
  • 21,818
  • 7
  • 41
  • 51