I’m trying to implement a ‘preview’ scenario when the user hover a menu item.
For example, lets say a program has a context-menu with ‘Set Color’ sub-menu.
The sub-menu pop a list of color to choose from.
Now, when the mouse cursor is over a specific color, I want it to change a label of “Selected color”.
And when the mouse cursor leave the selected color menu-item, I want to label to restore its original text.
The following code demonstrate changing the label when menu-item selected – mouse is over.
private void Init()
{
var mnuContextMenu = new ContextMenu();
this.ContextMenu = mnuContextMenu;
var smthingElseMenu = new MenuItem("Do something else");
var setColorMenu = new MenuItem("Set Color");
var colorBlue = new MenuItem("Blue");
var colorRed = new MenuItem("Red");
var colorGreen = new MenuItem("Green");
mnuContextMenu.MenuItems.Add(smthingElseMenu);
mnuContextMenu.MenuItems.Add(setColorMenu);
setColorMenu.MenuItems.Add(colorBlue);
setColorMenu.MenuItems.Add(colorRed);
setColorMenu.MenuItems.Add(colorGreen);
colorBlue.Select += ColorSelect;
colorRed.Select += ColorSelect;
colorGreen.Select += ColorSelect;
}
void ColorSelect(object sender, EventArgs e)
{
lblSelectedColor.Text = ((MenuItem) sender).Text;
}
But I couldn’t find a way to make the label text restore when the mouse cursor leave the menu-item.
Any ideas how can I implement some kind of ‘Unselect’/’MouseLeave’ event for MenuItem?
There’s no “un-select” event for MenuItems, unfortunately.
I would just catch the Collapse event of your context menu, and reset your label there. This would have the added benefit that if your user hovers over the “Red” option, then hovers off the context menu, the label should stay red until the context menu closes.
If you really need it to reset the label when your mouse leave the context menu, then you could catch the
MouseEnterevent of the Panel (or whatever) you have that surrounds the ContextMenu.EDIT Do consider using the ContextMenuStrip class instead. The ToolSTripMenuItem class has a MouseLeave event. And a Checked property, probably what you really want.