2017-07-26 80 views
0

我有一個WinForms應用程序,只能在托盤中啓動。點擊它,它會打開一個表單。這工作正常。單擊NotifyIcon上下文菜單中的ContextMenuItem調用NotifyIcon單擊事件

notifyIcon.Click += notifyIcon_Click; 

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

我添加了一個上下文菜單,但是當我點擊的ContextMenuItem,它首先觸發NotifyIcon的單擊事件,然後點擊的ContextMenuItem事件,開兩種形式。

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(); 
      } 

不知道如何要麼沒有它火的notifiyicon點擊事件,或者告訴點擊是上下文菜單上?

+1

不記得行爲,沒有看到任何明顯的錯誤,但你總是可以看看'sender'來看看被點擊的東西。 – Will

+0

是的,我也這麼認爲,但發件人是該點擊的ContextMenuItem,以及該點擊的NotifyIcon。原來,這是右鍵單擊以獲取導致我的問題的上下文菜單。不過感謝您的幫助! – Mike

回答

1

所以事實證明,右鍵單擊不會被註冊,直到上下文菜單被點擊後,所以它是右鍵單擊註冊並引發了NotifyIcon點擊事件。因此,我必須將提供用於點擊的EventArgs作爲MouseEventArgs,並檢查按鈕。

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