简体   繁体   English

在notifyIcon中向contextMenu项添加一个函数

[英]Add a function to contextMenu item at notifyIcon

I use an contextMenu1 and an notifyIcon1 for the app. 我为app使用了contextMenu1notifyIcon1 When the app is in Tray Icon and I will press Right Click , a menu will appear. 当应用程序处于Tray Icon ,我将按Right Click ,将出现一个菜单。

The code is this (I add only 2 items for test): 代码就是这个(我只添加了2个项目进行测试):

contextMenu1.MenuItems.Add("View");
contextMenu1.MenuItems.Add("Exit");

notifyIcon1.ContextMenu = contextMenu1;

In this moment, in the menu I see only the items that don't do enything. 在这一刻,在菜单中我只看到了没有做的东西。

How I can add a function, like private void exit() to the contextMenu1.MenuItems.Add("Exit") . 我如何添加一个函数,如private void exit()contextMenu1.MenuItems.Add("Exit") When I will pres the Exit item, to close my app (example). 当我打开Exit项目时,关闭我的应用程序(示例)。

There is a second parameter to Add that lets you assign an eventhandler: Add的第二个参数允许您分配事件处理程序:

contextMenu1.MenuItems.Add("Exit", ExitApplication);
// or using an anonymous method:
contextMenu1.MenuItems.Add("Exit", (s,e) => Application.Exit()); 

In the first example, ExitApplication is your event handler: 在第一个示例中,ExitApplication是您的事件处理程序:

private void ExitApplication(object sender, EventArgs e) 
{
    // exit..
}

You can also construct a MenuItem first and assign the eventhandler in the constructor, if you prefer. 如果您愿意,还可以首先构造一个MenuItem并在构造函数中指定eventhandler。

I am assuming that you have a Windows Form and a Button (name : btnShowMessage). 我假设您有一个Windows窗体和一个Button(名称:btnShowMessage)。 When you dobule click on the button you will get a event handler " btnShowMessage_Click ". 当你按下按钮时,你会得到一个事件处理程序“ btnShowMessage_Click ”。 Also you have a notificationIcon with ContextMenuStrip attached with it. 你也有一个带有ContextMenuStrip的notificationIcon。 You have even an menu option in the context menu strip (name : btnContextOpenMsg). 您甚至在上下文菜单条中有一个菜单选项(名称:btnContextOpenMsg)。 With The following steps you can use to achieve your requirement.: 使用以下步骤可以实现您的要求:

Below image is for your clear understanding : 下图是为了您的清晰理解:

  1. Go to Context Menu --> select btnContextOpenMsg 转到上下文菜单 - >选择btnContextOpenMsg

  2. Press F4 to open the property sheet 按F4打开属性表

  3. Click on " Events " button on top of the property sheet 单击属性表顶部的“ 事件 ”按钮
  4. Click on " Click " and expend the drop down beside the click event by clicking "..." 单击“ 单击 ”,然后通过单击“...”将下拉消息放在单击事件旁边
  5. Select the btnShowMessage_Click from the drop down. 从下拉列表中选择btnShowMessage_Click
  6. Compile you code after saving it. 保存后编译代码。
  7. You should see your notification (system tray) menu when you minimized your app. 最小化应用程序时,您应该会看到通知(系统托盘)菜单。
  8. Click on the "Show Message" option so that it will execute the same function as for the button. 单击“显示消息”选项,使其执行与按钮相同的功能。

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM