作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图让 NotifyIcon
显示上下文菜单,即使用鼠标左键单击也是如此。我可以通过图标的 MouseDown
事件将其显示在正确的位置:
sysTrayIcon.ContextMenuStrip = TrayContextMenu
If e.Button = MouseButtons.Left Then TrayContextMenu.Show()
但是,由于当我左键单击时,sysTrayIcon
未指定为控件,因此如果我单击菜单外部或按转义键,它不会从屏幕上清除。
我知道通常的方法是使用菜单的重载 Show(control, location)
方法,但这会引发此错误:
Value of type 'System.Windows.Forms.NotifyIcon' cannot be converted to 'System.Windows.Forms.Control'.
请问如何将菜单附加到通知图标?
最佳答案
是的,此代码无法按照发布的方式正常工作。几个secret incantations需要在正确的位置获取上下文菜单并正确设置鼠标捕获,以便在其外部单击可以正常工作。这些咒语是必需的,因为管理通知图标的是 Windows 资源管理器,而不是您的程序。
您需要将其留给 NotifyIcon 类来完成此操作。然而,一个重要的问题是它没有公开显示上下文菜单的方法,它是一个私有(private)方法。您唯一能做的就是使用反射来调用该方法。像这样(使用默认名称):
Imports System.Reflection
...
Private Sub NotifyIcon1_MouseDown(sender As Object, e As MouseEventArgs) Handles NotifyIcon1.MouseDown
NotifyIcon1.ContextMenuStrip = ContextMenuStrip1
Dim mi = GetType(NotifyIcon).GetMethod("ShowContextMenu", BindingFlags.NonPublic Or BindingFlags.Instance)
mi.Invoke(NotifyIcon1, Nothing)
End Sub
关于.net - 如何将 ContextMenuStrip 附加到 NotifyIcon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21076156/
我是一名优秀的程序员,十分优秀!