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

War es hilfreich?

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 :

  1. Go to Context Menu --> select btnContextOpenMsg

  2. Press F4 to open the property sheet

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

enter image description here

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top