终于解决:可以单独写成一个方法,自己可以试试。 Imports System.Reflection Public Class Form1 Private Sub NotifyIcon1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick If e.Button = Windows.Forms.MouseButtons.Left Then NotifyIcon1.ContextMenuStrip = ContextMenuStrip1 Dim eventSource As NotifyIcon = Nothing Dim niHandle As Type = Nothing eventSource = CType(sender, NotifyIcon) niHandle = eventSource.GetType niHandle.InvokeMember("ShowContextMenu", BindingFlags.Instance Or BindingFlags.Instance Or BindingFlags.NonPublic Or BindingFlags.InvokeMethod, Nothing, eventSource, Nothing) Else NotifyIcon1.ContextMenuStrip = ContextMenuStrip2 Dim eventSource As NotifyIcon = Nothing Dim niHandle As Type = Nothing eventSource = CType(sender, NotifyIcon) niHandle = eventSource.GetType niHandle.InvokeMember("ShowContextMenu", BindingFlags.Instance Or BindingFlags.Instance Or BindingFlags.NonPublic Or BindingFlags.InvokeMethod, Nothing, eventSource, Nothing) End If End Sub C#方案(要简单调整一下,对着VB就知道了): using System.Reflection;
左边是一个隐含的pancel
Imports System.Reflection
Public Class Form1
Private Sub NotifyIcon1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick
If e.Button = Windows.Forms.MouseButtons.Left Then
NotifyIcon1.ContextMenuStrip = ContextMenuStrip1
Dim eventSource As NotifyIcon = Nothing
Dim niHandle As Type = Nothing
eventSource = CType(sender, NotifyIcon)
niHandle = eventSource.GetType niHandle.InvokeMember("ShowContextMenu", BindingFlags.Instance Or BindingFlags.Instance Or BindingFlags.NonPublic Or BindingFlags.InvokeMethod, Nothing, eventSource, Nothing)
Else
NotifyIcon1.ContextMenuStrip = ContextMenuStrip2
Dim eventSource As NotifyIcon = Nothing
Dim niHandle As Type = Nothing
eventSource = CType(sender, NotifyIcon)
niHandle = eventSource.GetType niHandle.InvokeMember("ShowContextMenu", BindingFlags.Instance Or BindingFlags.Instance Or BindingFlags.NonPublic Or BindingFlags.InvokeMethod, Nothing, eventSource, Nothing)
End If
End Sub
C#方案(要简单调整一下,对着VB就知道了):
using System.Reflection;
可以在NotifyIcon的Click事件中加入以下代码来实现:
private void notifyIcon1_Click(object sender, System.EventArgs e)
{
NotifyIcon eventSource = null;
Type niHandle = null;
eventSource = (NotifyIcon)sender;
niHandle = eventSource.GetType();
Invoke the private ShowContextMenu method.
niHandle.InvokeMember(
"ShowContextMenu",
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.InvokeMethod,
null,
eventSource,
null
);
}