天天看點

給程式添加菜單及批量添加菜單點選事件

作者:逍遙總遙

首先向程式中添加一個菜單

給程式添加菜單及批量添加菜單點選事件

通過遞歸批量給菜單添加相關事件

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

namespace menu
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //根據點選菜單不同做不同的事
            AddMenuEvents(menuStrip1.Items);
        }

        void AddMenuEvents(ToolStripItemCollection c)
        {
            //周遊菜單項
            foreach (ToolStripItem items in c)
            {
                //如果是菜單而不是分隔線什麼其它的東西
                if (items is ToolStripItem)
                {
                    //得到其子菜單
                    ChildMenu((ToolStripMenuItem)items);
                }
            }
        }

        void ChildMenu(ToolStripMenuItem menu)
        {
            //如果有子菜單
            if (menu.HasDropDownItems)
            {
                //周遊所有子菜單
                foreach (ToolStripMenuItem m in menu.DropDownItems)
                {
                    //遞歸確定所有人都能吃到
                    ChildMenu(m);
                }
            }
            else
            {
                //如果是最後一級菜單,加事件
                menu.Click += new EventHandler(MenuCMD);
            }
        }

        void MenuCMD(object sender, EventArgs e)
        {
            ToolStripMenuItem ts = (sender as ToolStripMenuItem);
            //得到菜單标題
            string thecmdstr = ts.Text;
            //根據标題做事
            switch (thecmdstr)
            {
                case "A":
                    label1.Text = "您點了 A 菜單";
                    break;
                case "BBBB":
                    label1.Text = "您點了 BBBB 菜單";
                    break;
                default:
                    break;
            }

            //測試
            label2.Text = thecmdstr;
        }
    }
}           

這裡我通過 menu.HasDropDownItem 來控制如果使用者點選的不是最底層菜單就沒有做任何事,大家也可以不這樣做。結果如下

給程式添加菜單及批量添加菜單點選事件

繼續閱讀