Add a function to contextMenu item at notifyIcon

AnDr3yy picture AnDr3yy · Sep 15, 2012 · Viewed 9.9k times · Source

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).

Answer

driis picture driis · Sep 15, 2012

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.