[英]How can one get a ContextMenuStrip to show on left click of a NotifyIcon?
[英]How would one attach a ContextMenuStrip to a NotifyIcon
我正在嘗試讓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'.
那么如何將菜單附加到通知圖標呢?
是的,此代碼無法正常發布。 需要幾個秘密咒語才能將上下文菜單放在正確的位置,並正確設置鼠標捕獲,以便在其外部單擊可正常工作。 這些咒語是必需的,因為它是管理通知圖標的Windows資源管理器,而不是您的程序。
你需要將它留給NotifyIcon類才能做到這一點。 然而,一個重要的掛起是它不公開顯示上下文菜單的方法,它是一個私有方法。 您唯一能做的就是使用Reflection來調用該方法。 像這樣(使用默認名稱):
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.