Search code examples
c#.netuser-interfacecontextmenustrip

Do not close ContextMenuStrip on selection of certain items


Is it possible to leave a ContextMenuStrip open after a selection/check of certain items?

I plan on using a simple ContextMenuStrip to set a filter (this way i could use the same filter either in a menu or as a right-click option).

The menu lists a number of items, and i would like the user to be able to make a selection of the items using the basic Check functionality. Once the selection is done the user can click an Activate filter option or can click outside the menu to either activate or cancel the filter.

On a selection/click event the menu normally closes. Is it possible to keep the menu open on a click event?


Solution

  • To prevent the contextmenu from closing when an item is clicked, do the following.

    On mousedown event of ContextMenuItems set flag to false then set it back to true at the closing event of the contextmenu.

    Example:

    Private blnClose As Boolean = True
    
    Private Sub MoveUpToolStripMenuItem_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MoveUpToolStripMenuItem.MouseDown
    
         blnClose = False
    
    End Sub
    
    Private Sub ContextMenuStrip1_Closing(ByVal sender As Object, ByVal e As System.Windows.Forms.ToolStripDropDownClosingEventArgs) Handles ContextMenuStrip1.Closing
    
         e.Cancel = Not blnClose
         blnClose = True
    
    End Sub