检查与NotifyIcon关联时的ContextMenu的可见性

检查与NotifyIcon关联时的ContextMenu的可见性

本文介绍了检查与NotifyIcon关联时的ContextMenu的可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据关于另一个问题, Collapsed 一个ContextMenu的事件只有在调用 Show()之前与控件相关联才会引发。

According to this answer on another question, the Collapsed event of a ContextMenu is only raised if it's associated to a control before calling Show().

code> NotifyIcon 不算作控件,我无法钩住 Collapsed 事件,以检测何时将菜单关联到一个被隐藏。

SInce a NotifyIcon does not count as a control, I can't hook onto the Collapsed event to detect when the menu associated to one is hidden.

是否有任何解决方法?

推荐答案

关于 TrackPopupMenuEx 的MSDN文档的备注部分/ a>,它说:

Under the "Remarks" section for the MSDN docs on TrackPopupMenuEx, it says:

所以这可能意味着当 ContextMenu 可见时, NotifyIcon 上的窗口将前台窗口。通过查看 NotifyIcon.ShowContextMenu()可以看出,确实如此:

So that could mean that when the ContextMenu is visible, the window on the NotifyIcon will be the foreground window. You can see from by looking at NotifyIcon.ShowContextMenu() that it is indeed the case:

    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 有一个私有成员窗口,它指的是一个基类型为 NativeWindow 。因此,您可以这样检查:

Using ILSpy I then noticed NotifyIcon has a private member window, which refers to a private class with base type NativeWindow. Therefore, you can check like this:

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

这篇关于检查与NotifyIcon关联时的ContextMenu的可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!