I am new to windows Forms so I am wondering what the best approach to my problem is.
I want the ToolStripMenuItems of the ToolStripDropDownMenu to close only when the user's mouse leaves the area containing them (All the ToolStripMenuItems)
Currently I have the following code:
{ ToolStripDropDownMenu menu = new ToolStripDropDownMenu();
menu.AutoClose = true;
foreach (ToolStripMenuItem toolStripItem in this.collectionToolStripMenuItems)
{
menu.Items.Add(toolStripItem);
}
menu.Show(sender, e.ControlLocation);
}
I define the toolStripMenuItems in the list: collectionToolStripMenuItems with the code:
ToolStripMenuItem ToolStripItem = new ToolStripMenuItem(item.Name);
ToolStripItem.Click += new EventHandler(this.ValueMenuItem_Click);
ToolStripItem.MouseLeave += new EventHandler(MouseLeave);
ToolStripItem.MouseEnter += new EventHandler(MouseEnter);
where
private void MouseLeave(object sender, EventArgs e)
{
ToolStripMenuItem item2 = (ToolStripMenuItem)sender;
ToolStripDropDownMenu menu = (ToolStripDropDownMenu)item2.Owner;
menu.Hide();
}
private void MouseEnter(object sender,EventArgs e)
{
ToolStripMenuItem item2 = (ToolStripMenuItem)sender;
ToolStripDropDownMenu menu = (ToolStripDropDownMenu)item2.Owner;
menu.Show();
}
private void ValueMenuItem_Click(object sender, EventArgs e)
{// Do something
ToolStripMenuItem item2 = (ToolStripMenuItem)sender;
ToolStripDropDownMenu menu = (ToolStripDropDownMenu)item2.Owner;
menu.Show();
return;
}
This works however each time the user clicks or leaves a toolStripMenuItem the dropDown closes for a very brief moment so it looks like the whole thing is flashing.
Can someone please recommend a better approach? Many thanks!
I am facing a similar problem. Let me share the whole solution. Let toolStripMenuItem be our ToolStripMenuItem object.
Do this OUTSIDE the Form1.Designer.cs:
toolStripMenuItem.DropDown.AutoClose = false;toolStripMenuIntem.DropDown.MouseLeave += System.EventHandler(this.DropDown_MouseLeave)You need of course to create this event handler:
The solution above is partial. You may need also to close the dropdown when mouse leaves the toolStripMenuItem control itself. For that, what I did is to check if mouse is inside drop down when it leaves toolStripMenuItem control. If mouse is outside toolStripMenuItem and outside dropdown, then I close the drop down menu.
Remember to link the event MouseLeave of the toolStripMenuItem object to
ToolStripMenuItem_MouseLeave.Hope it helps!