Tweaking ContextMenu's for List Items

A little System.Windows.Forms diversion. One thing that's ill-documented, imho, is the CheckedListBox. And if you then want to add a context menu that's context sensitive to the Item in the list you are over, then good luck finding any useful info. Therefore, I figured i put this snippet in here before I forget again how do deal with this.

The best example I found for handling ContextMenu in the context of a list item recommended completely ignoring the ContextMenu property on the listbox and handling it all in the MouseDown event--creating the context menu on the fly and all.

That seemed a little overkill to me since all i wanted to to do was disable the one item Edit on the context menu. So, instead i capture the Popup event and tweak my menu there. First the setup of the context menu (in my constructor):

ContextMenu contextMenu = new ContextMenu();
MenuItem edit = new MenuItem("Edit");
contextMenu .MenuItems.Add(edit);
edit.Click += new EventHandler(edit_Click);
contextMenu .Popup +=new EventHandler(contextMenu _Popup);
checkedListBox.ContextMenu = contextMenu;

And here's the popup handler:

private void contextMenu_Popup(object sender, EventArgs e)
{
    //don't forget to translate the mouse coordinates to the control local coordinates
    int index = checkedListBox.IndexFromPoint(checkedListBox.PointToClient(MousePosition));
    if( index == -1 || !checkedListBox.GetItemChecked(index) )
    {
        ((ContextMenu)sender).MenuItems[0].Enabled = false;
    }
    else
    {
        ((ContextMenu)sender).MenuItems[0].Enabled = true;
        //storing the index in a class field so that i don't have to
        //do the math again and in case the mouse moved
        contextSelection = index;
    }
}

So there you have it.