Add a function to contextMenu item at notifyIcon
-
02-07-2021 - |
Frage
I use an contextMenu1
and an notifyIcon1
for the app. When the app is in Tray Icon
and I will press Right Click
, a menu will appear.
The code is this (I add only 2 items for test):
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")
. When I will pres the Exit
item, to close my app (example).
Lösung
There is a second parameter to Add
that lets you assign an eventhandler:
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:
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.
Andere Tipps
I am assuming that you have a Windows Form and a Button (name : btnShowMessage). When you dobule click on the button you will get a event handler "btnShowMessage_Click". Also you have a notificationIcon with ContextMenuStrip attached with it. You have even an menu option in the context menu strip (name : btnContextOpenMsg). With The following steps you can use to achieve your requirement.:
Below image is for your clear understanding :
Go to Context Menu --> select btnContextOpenMsg
Press F4 to open the property sheet
- Click on "Events" button on top of the property sheet
- Click on "Click" and expend the drop down beside the click event by clicking "..."
- Select the btnShowMessage_Click from the drop down.
- Compile you code after saving it.
- You should see your notification (system tray) menu when you minimized your app.
- Click on the "Show Message" option so that it will execute the same function as for the button.