RE: the comment posted to my previous answer
The invalid cast exception is because the
Items
collection of the
ContextMenuStrip
holds
ToolStripItem
s, not
ToolStripMenuItem
s. In this bit of code:
foreach (ToolStripMenuItem TSI in CollectionTSI)
there's an implicit cast happening without you seeing it, each object of the
Items
collection is being cast to a
ToolStripMenuItem
and casting the separator object obviously fails.
One way around this is to do the cast yourself using the
as
operator to check for invalid casts:
void contextMenuStrip_Click(object sender, EventArgs e)
{
ContextMenuStrip menu = sender as ContextMenuStrip;
if (menu == null)
{
return;
}
foreach (ToolStripItem item in menu.Items)
{
ToolStripMenuItem menuItem = item as ToolStripMenuItem;
if (menuItem == null)
{
continue;
}
}
}
In this
foreach
loop no casting is done when enumerating over the elements in
Items
, but the first thing the body of the loop does is do a safe cast to see if each
ToolStripItem
is really a
MenuItem
.