3

I have a ToolStripDropDownButton where the subitems have CheckOnClick enabled.

I want to give the user the ability to pick more than one item before closing the drop down, but I can't find a way of doing that without setting AutoClose to false and doing so presents another problem, which is how to close it when the user clicks anywhere outside the control (which is when it should close it).

I've seen the similar question How do I close a toolstripmenuitem that is set to autoclose = false? but the suggestion of putting a handler for the Click event on every component is not exactly what I'm after. It should be when it loses focus, regardless of whether it's through mouse or keyboard control.

I looked at the Leave but while ToolStrips themselves have that event, apparently the ToolStripDropDownButton doesn't.

What would the best way to do this be?

Community
  • 1
  • 1
JohnUbuntu
  • 699
  • 6
  • 19

1 Answers1

9

Turns out there's a really simple way of doing this which I hadn't realized yet. The Closing event states why the ToolStripDropDownButton is being closed and one of the reasons available is that an item was clicked.

ToolStripDropDownButton directly doesn't have a Closing event, but since it is just a wrapper for a ToolStripDropDown it does expose that via ToolStripDropDownButton.DropDown.Closing

So I just did the following:

toolStripDropDownButton1.DropDown.Closing += toolStripDropDownButton1_Closing;

private void toolStripDropDownButton1_Closing(object sender, ToolStripDropDownClosingEventArgs e)
{
    if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked)
    {
        e.Cancel = true;
    }
}

This way I'm only preventing it from being closed if an item is clicked, but not preventing it from closing if, say, a user clicks outside of the ToolStripDropDownButton or if it loses focus.

JohnUbuntu
  • 699
  • 6
  • 19