Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

winforms - contextMenuStrip - close on clicking away

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.

like image 939
Tamim Sadikali Avatar asked Dec 30 '25 19:12

Tamim Sadikali


1 Answers

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.

like image 131
dotjoe Avatar answered Jan 02 '26 16:01

dotjoe