bdeetz
bdeetz

Reputation: 185

C# WinForms trayapp MenuItem mouse hover detection

I have a fairly simple question, but I'm failing to find the solution. I have an application that resides in the task tray. When a user right clicks the tray icon, the program displays a menu of MenuItems. I would like to execute code when some of my MenuItems are mouse hovered over.

Is this possible?

Can you send me in the right direction?

I am using NotifyIcon

        trayMenu = new ContextMenu();
        trayMenu.MenuItems.Add("Exit", OnExit);

        trayIcon = new NotifyIcon();
        trayIcon.Text = "blah";

        trayIcon.Icon = new Icon("favicon.ico", 40, 40);
        trayIcon.ContextMenu = trayMenu;
        trayIcon.Visible = true;

Upvotes: 2

Views: 2664

Answers (3)

NoWar
NoWar

Reputation: 37633

Here is your solution https://www.codeproject.com/Tips/254525/Automatically-display-Menu-on-Hover

private void Form1_Load(object sender, EventArgs e)
{
    this.menuStrip1.Items[0].MouseHover += new EventHandler(Form1_MouseHover);
}


void Form1_MouseHover(object sender, EventArgs e)
{
    if (sender is ToolStripDropDownItem)
    {
        ToolStripDropDownItem item = sender as ToolStripDropDownItem;
        if (item.HasDropDownItems && !item.DropDown.Visible)
        {
            item.ShowDropDown();
        }
    }
}

Upvotes: 0

Unknown
Unknown

Reputation: 411

You'll have to use MouseHover or MouseEnter and MouseLeave events of each menuitem.

Update: Yep, NotifyIcon controls have a property named ContextMenuStrip. You'll have to create the ContextMenuStrip control to display the menu. It contains items of ToolStripMenuItems type. I tried to create a simple prototype - MouseHover works just fine.

Upvotes: 2

stuartd
stuartd

Reputation: 73253

I think you might want the MenuItem's Select event:

This event is typically raised when the user places the mouse pointer over the menu item. The event can also be raised when the user highlights a menu item using the keyboard by scrolling to the menu item with the arrow keys.

Upvotes: 1

Related Questions