簡體   English   中英

NotifyIcon ContextMenu和太多的點擊事件

[英]NotifyIcon ContextMenu and too many click events

我正在使用NotifyIcon類在任務欄中顯示一個圖標。 該圖標執行2個功能 - 當用戶單擊左鍵時,它應顯示一個窗口,當用戶單擊右鍵時,它應顯示上下文菜單。 除了在用戶單擊上下文菜單中的選項后顯示的窗口之外,此方法也可以正常工作。 這是我的代碼:

contextMenuItems = new List<MenuItem>();
contextMenuItems.Add(new MenuItem("Function A", new EventHandler(a_Clicked)));
contextMenuItems.Add(new MenuItem("-"));
contextMenuItems.Add(new MenuItem("Function B", new EventHandler(b_Clicked)));
trayIcon = new System.Windows.Forms.NotifyIcon();
trayIcon.MouseClick += new MouseEventHandler(trayIcon_IconClicked);
trayIcon.Icon = new Icon(GetType(), "Icon.ico");
trayIcon.ContextMenu = contextMenu;
trayIcon.Visible = true;

問題是當用戶選擇“功能A”或“功能B”時會觸發我的trayIcon_IconClicked事件。 為什么會這樣?

謝謝,J

通過將上下文菜單分配給NotifyIcon控件,它會自動捕獲右鍵單擊並在那里打開指定的上下文菜單。 如果要在實際顯示上下文菜單之前執行某些邏輯,請將委托分配給contextMenu.Popup事件。

...
contextMenu.Popup += new EventHandler(contextMenu_Popup);
...

private void trayIcon_IconClicked(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        //Do something here.
    }
    /* Only do this if you're not setting the trayIcon.ContextMenu property, 
    otherwise use the contextMenu.Popup event.
    else if(e.Button == MouseButtons.Right)
    {
        //Show uses assigned controls Client location to set position, 
        //so must go from screen to client coords.
        contextMenu.Show(this, this.PointToClient(Cursor.Position));
    }
    */
}

private void contextMenu_Popup(object sender, EventArgs e)
{
    //Do something before showing the context menu.
}

我猜測窗口彈出的原因是你打開的上下文菜單是使用NotifyIcon作為目標控件,所以當你點擊它時它會運行你分配給NotifyIcon的點擊處理程序。

編輯:要考慮的另一個選擇是使用ContextMenuStrip。 NotifyIcon也有一個ContextMenuStrip屬性,它似乎有更多與之相關的功能(注意我可以做更多,可編程)。 如果某些事情由於某種原因不能正常工作,可能想要給出一個機會。

我遇到了同樣的問題。 將NotifyIcon的ContextMenu更改為ContextMenuStrip並沒有解決問題(實際上當我更改了ContextMenu時,在ContextMenuStrip顯示時發生了Click事件,而不是當用戶實際點擊其中一個項目時。

我對此問題的解決方案是更改用於顯示左鍵單擊上下文菜單的事件。 我沒有使用Click事件處理程序,而是使用MouseUp並檢查單擊了哪個MouseButton。

構建NotifyIcon(notifyContext是一個System.Windows.Forms.ContextMenuStrip)

m_notifyIcon.MouseUp += new Forms.MouseEventHandler(m_notifyIcon_MouseUp);
m_notifyIcon.ContextMenuStrip = notifyContext;

Handling the left click event and show the main contextmenu:

        void m_notifyIcon_MouseUp(object sender, Forms.MouseEventArgs e)
        {
            if (e.Button == Forms.MouseButtons.Left)
            {
                mainContext.IsOpen = ! mainContext.IsOpen;
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM