且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

调用的NotifyIcon的上下文菜单

更新时间:2023-11-30 21:46:10

您通常会处理MouseClick事件检测点击调用ContextMenuStrip.Show()方法:

You would normally handle the MouseClick event to detect the click and call the ContextMenuStrip.Show() method:

    private void notifyIcon1_MouseClick(object sender, MouseEventArgs e) {
        contextMenuStrip1.Show(Control.MousePosition);
    }

但实际上并没有正常工作,当你点击它外面CMS不会关闭。根本的问题是Windows怪癖(又名错误),它在描述此知识库文章

在自己的code调用此解决方法是pretty痛苦的PInvoke的是不愉快的。 NotifyIcon的类有此解决办法在其ShowContextMenu()方法,他们只是做它去,因为它是一个私有方法困难。反射可以绕过限制。我5年前发现了这个技巧,没有人报出了问题呢。设置NFI的ContextMenuStrip属性和实施这样的MouseUp事件:

Invoking this workaround in your own code is pretty painful, the pinvoke is unpleasant. The NotifyIcon class has this workaround in its ShowContextMenu() method, they just made it difficult to get to since it is a private method. Reflection can bypass that restriction. I discovered this hack 5 years ago and nobody reported a problem with it yet. Set the NFI's ContextMenuStrip property and implement the MouseUp event like this:

using System.Reflection;
...
    private void notifyIcon1_MouseUp(object sender, MouseEventArgs e) {
      if (e.Button == MouseButtons.Left) {
        MethodInfo mi = typeof(NotifyIcon).GetMethod("ShowContextMenu", BindingFlags.Instance | BindingFlags.NonPublic);
        mi.Invoke(notifyIcon1, null);
      }
    }