Reputation: 239
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).
Upvotes: 4
Views: 11159
Reputation: 3477
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
Upvotes: 0
Reputation: 164281
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.
Upvotes: 5