Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to stop a Menu from closing when you click on it?

Tags:

c#

.net

winforms

We have a form in our program that allows a user to determine what a user can see when setting privileges, by using a menu bar. When a user clicks on an item, that item then is "selected" (gets a tick next to it). However, this also closes the menu.

enter image description here

Is there a way to stop this menu from closing (without affecting any other menu's in the program) when a user clicks on it? So far I have not found anything in the settings, and any _click methods are not affecting it either.

like image 497
Ben Avatar asked Dec 02 '15 03:12

Ben


2 Answers

Listen the ToolStripDropDownClosingEventHandler present in ToolStripDropDown. To do this just access the ToolStripMenuItem.DropDown Property, and so, add a listener that will handle the Closing event. We just need to check if the mouse pointer it's inside of toolStrip rectangle and this can be done with this piece of code:

private void ListenToolStripMenuItems(IEnumerable<ToolStripMenuItem> menuItems)
{
    // listen all menuItems
    foreach (ToolStrip menuItem in menuItems)
        menuItem.DropDown.Closing += OnToolStripDropDownClosing;
}

private void OnToolStripDropDownClosing(object sender, ToolStripDropDownClosingEventArgs e)
{
        var tsdd = (ToolStripDropDown)sender;

        // checking if mouse cursor is inside
        Point p = tsdd.PointToClient(Control.MousePosition);  
        if (tsdd.DisplayRectangle.Contains(p))
            e.Cancel = true;  // cancel closing
}

This way the AutoClose still working and the toolStrip will close properly.

like image 169
Henrique Avatar answered Oct 13 '22 21:10

Henrique


I'm a hack, but I would do this for each item you can click:

 sampleNameToolStripMenuItem.ShowDropDown();

That way whenever you click something, it will also drop the menu down again right after.

like image 36
user3263609 Avatar answered Oct 13 '22 22:10

user3263609