简体   繁体   中英

How to dynamically add menu item in Systray app using C#

I would like to dynamically add a menu item to a systray app. I already have an "Exit" and "Add more" menu. I would like to add more menus at run-time when I click on Add more.

For example, when I clicked on Add more, it automatically add a new menuItem to the tray App.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            NotifyIcon notify = new NotifyIcon();
            notify.ContextMenuStrip = MainContextMenu();
            notify.Icon = new Icon("Led.ico");
            notify.Visible = true;

            Application.Run();
        }

        private static ContextMenuStrip MainContextMenu()
        {
            ContextMenuStrip ConextMenuApp = new ContextMenuStrip();


            ConextMenuApp.Items.Add("Add More", null, new EventHandler(AddMoreMenus));
            ConextMenuApp.Items.Add("-");
            ConextMenuApp.Items.Add("Exit", null, new EventHandler(Exit_Click));


            return ConextMenuApp;
        
        }

        private static ContextMenuStrip AddMoreMenus(Object sender, EventArgs e)
        {
            ContextMenuStrip AddNewMenu = new ContextMenuStrip();
            AddNewMenu.Items.Add("Menu One Addedd");
            return AddNewMenu;
        }

        private static void Exit_Click(Object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

There are many ways you can do this, however the simplest way is just hold a Reference to the MenuStrip or MenuStrip Item and pass it around.

Though in all honesty, just choose your poison:

  1. Make a DI Service that holds the Reference
  2. Make it Static
  3. Pass it in as a Reference to the classes who want to manipulate it
  4. Use Decouple Message or an Event Aggregator or some other pub/sub architecture

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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