xopzew
Last Updated: February 25, 2016
·
22.87K
· keboo

Dynamic context menu not showing on first click

I was faced with a very interesting problem. Given a user control the context menu was not being shown the first time the user right clicked. There was nothing special about the user control nor the context menu except that the menu items were dynamically generated during the context menu’s opening event.

Consider the follow code snippet:

bool _showItem1;
bool _showItem2;

private void ctxMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
    _ctxMenuStrip.Items.Clear();

    if (_showItem1)
    {
        _ctxMenuStrip.Items.Add("Item 1", null, item1_clickHandler);
    }

    if (_showItem2)
    {
        _ctxMenuStrip.Items.Add("Item 2", null, item2_clickHandler);
    }
}

private void item1_clickHandler(object sender, EventArgs e)
{  }

private void item2_clickHandler(object sender, EventArgs e)
{  }

The above code does have the issue I described above where the context menu is not show the first time the user right clicks on the user control.

As it turns out when the context menu is building up the CancelEventArgs to pass to the Opening event, it does the following.

CancelEventArgs e = new CancelEventArgs(this.DisplayedItems.Count == 0);
this.OnOpening(e);

So the first time the context menu is shown the Cancel property on the CancelEventArgs is set to true because no items have been added. While all subsequent times the context menu is properly displayed.

A more appropriate fix would be something along the lines of

private void ctxMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
    _ctxMenuStrip.Items.Clear();

    if (_showItem1)
    {
        _ctxMenuStrip.Items.Add("Item 1", null, item1_clickHandler);
    }

    if (_showItem2)
    {
        _ctxMenuStrip.Items.Add("Item 2", null, item2_clickHandler);
    }

    e.Cancel = _ctxMenuStrip.Items.Count > 0;
}

MSDN Reference: http://msdn.microsoft.com/en-us/library/ms229625.aspx

Source: http://dotnetgeek.tumblr.com/post/2620348172/dynamic-context-menu-not-showing-on-first-click

Say Thanks
Respond