繁体   English   中英

如何使用 C# 在 Systray 应用程序中动态添加菜单项

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

我想将菜单项动态添加到系统托盘应用程序。 我已经有了“退出”和“添加更多”菜单。 当我单击“添加更多”时,我想在运行时添加更多菜单。

例如,当我单击“添加更多”时,它会自动向托盘应用程序添加一个新的菜单项。

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();
        }
    }
}

有很多方法可以做到这一点,但最简单的方法是持有对MenuStripMenuStrip Item 的引用并将其传递。

尽管老实说,请选择您的毒药:

  1. 创建一个包含引用的 DI 服务
  2. 让它Static
  3. 将它作为参考传递给想要操作它的类
  4. 使用解耦消息事件聚合器或其他一些发布/订阅架构

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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