问题
I´m have been dealing with this issue all day. I have a menustrip with several menu items. Each item, also have many items. Now, if I click the parent menu item, a container(similar to contextmenu) stays opened until I click somewhere else.
In the image example, "Clientes" will be the parent item, and there its the "container" with their child menu items.
What I wanted to do, is to close that "container" when the mouse leaves the parent item or the container area. I dont want to have to click in any other part of the form to close it. When I say that, its because I´m actually using WPF buttons and I need to do it this way.
I need help here, hope somebody can give me some advice.
I tried to use the MouseLeave event of the parents items ("Clientes", etc.) and there did:
private void clientesToolStripMenuItem_MouseLeave(object sender, EventArgs e)
{
clientesToolStripMenuItem.DropDown.Close();
}
This works, but obviously, it closes the parent and also the container, when the mouse leaves menuitem "Clientes". I need a way to know if the mouse is over the parent menuitem or over one of their childs so as to close it if I know that the mouse is somewhere else.
Hope somebody can help me out.
回答1:
You can achieve this by handling events of clientesToolStripMenuItem itself. When the mouse enters your clients main-menu rectangle, just show your container and hide it when it leaves this rectangle. Assuming picContainer is your rectangle, you may do something like this:
private void clientToolStripMenuItem_MouseEnter(object sender, EventArgs e)
{
picContainer.Location = clientToolStripMenuItem.ContentRectangle.Location;
picContainer.Show();
}
private void clientToolStripMenuItem_MouseLeave(object sender, EventArgs e)
{
this.picContainer.Hide();
}
来源:https://stackoverflow.com/questions/15170720/closing-winform-menustrip-when-mouse-leaves-the-container