簡體   English   中英

與NotifyIcon關聯時檢查ContextMenu的可見性

[英]Checking the visibility of a ContextMenu when associated with a NotifyIcon

根據另一個問題的答案 ,只有在調用Show()之前將ContextMenu的Collapsed事件與控件關聯,才會引發它。

因為NotifyIcon不算作控件,所以我無法掛起Collapsed事件來檢測與之關聯的菜單何時被隱藏。

有什么解決方法嗎?

TrackPopupMenuEx上的MSDN文檔的“備注”部分下,它說:

若要顯示通知圖標的上下文菜單,在應用程序調用TrackPopupMenu或TrackPopupMenuEx之前,當前窗口必須是前景窗口。 否則,當用戶在菜單或創建菜單的窗口之外單擊時(如果可見),菜單將不會消失。 如果當前窗口是子窗口,則必須將(頂層)父窗口設置為前景窗口。

因此,這意味着當ContextMenu可見時, NotifyIcon上的窗口將成為前景窗口。 通過查看NotifyIcon.ShowContextMenu()可以看到確實如此:

    private void ShowContextMenu()
    {
        if (this.contextMenu != null || this.contextMenuStrip != null)
        {
            NativeMethods.POINT pOINT = new NativeMethods.POINT();
            UnsafeNativeMethods.GetCursorPos(pOINT);
            UnsafeNativeMethods.SetForegroundWindow(new HandleRef(this.window, this.window.Handle));
            if (this.contextMenu != null)
            {
                this.contextMenu.OnPopup(EventArgs.Empty);
                SafeNativeMethods.TrackPopupMenuEx(new HandleRef(this.contextMenu, this.contextMenu.Handle), 72, pOINT.x, pOINT.y, new HandleRef(this.window, this.window.Handle), null);
                UnsafeNativeMethods.PostMessage(new HandleRef(this.window, this.window.Handle), 0, IntPtr.Zero, IntPtr.Zero);
                return;
            }
            if (this.contextMenuStrip != null)
            {
                this.contextMenuStrip.ShowInTaskbar(pOINT.x, pOINT.y);
            }
        }
    }

然后,我使用ILSpy注意到NotifyIcon有一個私有成員window ,該window引用具有基本類型NativeWindow的私有類。 因此,您可以像這樣檢查:

[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetForegroundWindow();

...

FieldInfo notifyIconNativeWindowInfo = typeof(NotifyIcon).GetField("window", BindingFlags.NonPublic | BindingFlags.Instance);
NativeWindow notifyIconNativeWindow = (NativeWindow)notifyIconNativeWindowInfo.GetValue(notifyIcon1);

bool visible = notifyIcon1.Handle == GetForegroundWindow();

暫無
暫無

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

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