簡體   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