2

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.

DavidRR
  • 18,291
  • 25
  • 109
  • 191
Tamim Sadikali
  • 203
  • 4
  • 11

3 Answers3

9

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.

DavidRR
  • 18,291
  • 25
  • 109
  • 191
dotjoe
  • 26,242
  • 5
  • 63
  • 77
  • Good idea & tried it - except the event doesn't fire!! When I click away & even e.g. select a cell in the parent DGV, LostFocus() on the ContextMenuStrip just does not get triggered. Any ideas on rectifying this..? – Tamim Sadikali Oct 08 '09 at 17:34
  • @TamimSadikali ` private void _cntxtMnu_Closing(object sender, ToolStripDropDownClosingEventArgs e) { if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked) { e.Cancel = true; } }` – Ahmed Suror Sep 19 '22 at 01:30
0

You could follow what these guys have done in this SO question. I'm not sure if this would cause a flicker in the ui, but it might allow you to do what you want to.

Community
  • 1
  • 1
mlsteeves
  • 1,251
  • 2
  • 16
  • 20
  • Thanks for the reply but the suggestion herein - i.e. to call Show() within OnClick() and thus effectively 'recuscitate' the control - feels overly complex to me. Plus if there were sub-menu items open at the time, you would have to re-open them to preserve the effect, and that's way too much hard work! – Tamim Sadikali Oct 08 '09 at 17:19
0

Generally speaking, I discourage non-standard behaviour of standard controls... so this is really borderline. I'd probably look for a way to refactor the UI to make it more intuitive for the user, who will expect a context menu to close itself after selecting one of the menu items.

In this situation, if you're modifying the properties of a row in the grid, for example, you could use a Properties (modal) dialog box that gets opened from the context menu; or, implement something like the Visual Studio Properties window, where it updates itself depending on the selection context. Both of these solutions are more flexible and will provide better feedback to the user than a simple context menu.

Jon Seigel
  • 12,251
  • 8
  • 58
  • 92