简体   繁体   中英

How do you get a different Context Menu if you Lt-Click or Rt-Click on a notify icon?

I have a application that is based out of the system tray. I have a nice context menu if you right click on it however I would like a different context menu to show up if you left click on it. Right now I make the different menu show up with

private void niTrayIcon_MouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Left)
    {
        cmsTrayLeftClick.Show(Cursor.Position);
    }

}

That makes the menu show up but clicking off the menu does not make it go away, the only way to make the menu disappear is either click on a item or rt click on the tray icon.

I have also came up with this hack but it does feel like it is the correct way to do it.

private void niTrayIcon_MouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Left)
    {
        niTrayIcon.ContextMenuStrip = cmsTrayLeftClick;
        MethodInfo mi = typeof(NotifyIcon).GetMethod("ShowContextMenu", BindingFlags.Instance | BindingFlags.NonPublic);
        mi.Invoke(niTrayIcon, null);
        niTrayIcon.ContextMenuStrip = cmsTrayRtClick;
    }
}

Is this the correct way of doing it or is there a more elegant way?

As no one else has posted a way that works I guess the correct way of doing it is

private void niTrayIcon_MouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Left)
    {
        niTrayIcon.ContextMenuStrip = cmsTrayLeftClick;
        MethodInfo mi = typeof(NotifyIcon).GetMethod("ShowContextMenu", BindingFlags.Instance | BindingFlags.NonPublic);
        mi.Invoke(niTrayIcon, null);
        niTrayIcon.ContextMenuStrip = cmsTrayRtClick;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM