C# NotifyIcon 鼠标左键弹出托盘菜单的两个方法

  最近在做一个小程序,要求程序的图标显示在任务栏的通知区域,就和QQ的图标显示一样。NotifyIcon类提供了这类的实现方法。NotifyIcon控件的Icon属性定义显示在通知区域中的图标。图标的弹出菜单由 ContextMenu属性确定。Text属性分配工具提示文本。在默认情况下,在图标上单击鼠标右键,图标的弹出菜单才显示出来。如果想点击左键,图标的弹出菜单也显示的话,可以由如下两个方法实现:

方法一:使用notifyicon的show方法,缺点是鼠标单击左键出来菜单后,单击左键显示菜单后该菜单式一直存在的,且在任务栏里出现了一个没有程序名的小方块,如图

 

 

  void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)  //单击鼠标左键也弹出菜单
            {
                Control control = new Control(null, Control.MousePosition.X, Control.MousePosition.Y, 1, 1);
                control.Visible = true;
                control.CreateControl();
                Point pos = new Point(0, 0);//这里的两个数字要根据你的上下文菜单大小适当地调整 
                this.contextMenuStrip1.Show(control, pos);
            } 
        }

方法二:利用反射的方法,其实现的效果与单击右键完全一致

void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)  //单击鼠标左键也弹出菜单
            {
                Type t = typeof(NotifyIcon);
                MethodInfo mi = t.GetMethod("ShowContextMenu", BindingFlags.NonPublic | BindingFlags.Instance);
                mi.Invoke(this.notifyIcon1, null);
            } 
        }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值