winforms - contextMenuStrip - close on clicking away

contextmenustrip, events, winforms

Solution

Just close it in the `LostFocus` event on the ContextMenuStrip.

Set the AutoClose property back to true and handle the `Closing` event. Cancel the close only if the CloseReason property of ToolStripDropDownClosedEventArgs is equal to ItemClicked.

Problem

I have a DataGridView with a ContextMenuStrip. The ContextMenuStrip's default behaviour is to auto-close - i.e. to close immediately on the user interacting with it. I've turned this off to allow multiple user interactions (which is what I want), however beyond that what I really need is for the context menu to subsequently close on the user clicking anywhere outside of itself. The space in which the user clicks away might be on the form directly, or on a child control (or a child of the child etc). And yet regardless, I am looking to neatly capture the 'click away' event, and thus close the ContextMenuStrip. Any ideas would be very gratefully received. Tamim.

Original source

Related problems