0
votes

I have a WinForms app that starts up in the tray only. On clicking it, it opens a form. This works fine.

    notifyIcon.Click += notifyIcon_Click;

//Fires on icon click, AND on contextmenuitem click
    private void notifyIcon_Click(object sender, EventArgs e)
            {
                new ActiveIssues(_hubProxy).Show();
            }

I have added a context menu, but when I click the ContextMenuItem, it first fires the NotifyIcon click event, THEN the ContextMenuItem click event, opening both forms.

    notifyIcon.ContextMenu = GetCrestContextMenu();

     private ContextMenu GetCrestContextMenu()
            {
                var contextMenu = new ContextMenu();
                contextMenu.Name = "CResT Alerts";
                contextMenu.MenuItems.Add(GetTextOptionMenuItem());
                return contextMenu;
            }

            private MenuItem GetTextOptionMenuItem()
            {
                var textOptionMenuItem = new MenuItem { Text = _textOptedIn ? "Opt Out of Text Alerts" : "Opt In to Text Alerts" };
                textOptionMenuItem.Click += TextOptionMenuItem_Click;
                return textOptionMenuItem;
            }

//Fires on menuitem click, after the NotifyIcon click event is called
            private void TextOptionMenuItem_Click(object sender, EventArgs e)
            {
                if (_textOptedIn) new TextOptOut().Show();
                else new TextOptIn().Show();
            }

Any idea how to either NOT have it fire the notifiyicon click event or to tell that the click was on the context menu?

1
Don't remember the behavior, don't see any obvious screw-ups, but you can always look at the sender to see what got clicked.user1228
Yeah, I thought that as well, but the sender was the ContextMenuItem for that click, and the NotifyIcon for that click. Turns out it was the right-click to get the context menu that was causing my issue. Thanks for your help, though!Mike

1 Answers

3
votes

So it turns out that the right-button click is not registered until after the context menu is clicked, so it is the right-button click that registered and raised the NotifyIcon click event. As such, I had to cast the EventArgs provided for the click as MouseEventArgs, and check the button.

private void notifyIcon_Click(object sender, EventArgs e)
    {
        if(((MouseEventArgs)e).Button == MouseButtons.Left) new ActiveIssues(_hubProxy).Show();
    }