David Rutten
David Rutten

Reputation: 4806

Combobox inside ContextMenuStrip problem

Given the following insane setup (a ComboBox inside a UserControl inside a ToolStripControlHost inside a ContextMenuStrip):

enter image description here

there's something odd going on with clicking on different items in the ComboBox popup. If the item is inside the menu bounds (i.e. Amsterdam, Brussel or Luxemburg) the item is selected. If the item is outside the menu bounds (i.e. Berlijn and further) the menu is closed immediately.

Ignoring any spiffy remarks regarding the sheer crazy, anyone know what's going on and how to stop the menu from closing if a distant combobox item is selected?

Upvotes: 0

Views: 920

Answers (1)

John Arlen
John Arlen

Reputation: 6698

The problem is due to a check deep in the ToolStripManager determining the mouse event is not on a child.

Basically you need to reject the ContextMenuStrip.OnClosing event if the ComboBox is displaying. There's inevitably a cleaner solution but I didn't see one.

public bool IsDropDownShowing { get; private set; }
private void InitializeContextMenu()
{
    var userControl = new ComboMenuUserControl();
    var toolStripHost = new ToolStripControlHost(userControl);
    contextMenuStrip1.Items.Add(toolStripHost);

    userControl.comboBox1.DropDown += (o, args) => IsDropDownShowing = true;
    userControl.comboBox1.DropDownClosed += (o, args) => IsDropDownShowing = false;

    contextMenuStrip1.Closing += (o, args) =>
                                    {
                                        if (IsDropDownShowing == true)
                                            args.Cancel = true;
                                    };
}

Upvotes: 3

Related Questions