首页 > 其他 > 详细

menuStrip1动态添加菜单及快捷键

时间:2019-04-09 00:53:20      阅读:295      评论:0      收藏:0      [点我收藏+]
   public partial class FormMkTest : Form
    {
        public FormMkTest()
        {
            InitializeComponent();
        }

        private void FormMkTest_Load(object sender, EventArgs e)
        {
            //添加菜单一文本中加入 &F  即ALT+F  打开某子菜单
            ToolStripMenuItem subItem;
            subItem = AddContextMenu("文件(&F)", menuStrip1.Items, null);
            //添加子菜单
            AddContextMenu("打开(&O)", subItem.DropDownItems, new EventHandler(MenuClicked));
            AddContextMenu("下载(&D)", subItem.DropDownItems, new EventHandler(MenuClicked));

            //添加菜单二
            subItem = AddContextMenu("&Edit", menuStrip1.Items, null);
            //添加子菜单
            ToolStripMenuItem sub1 = AddContextMenu("&Update", subItem.DropDownItems, new EventHandler(MenuClicked));
            //孙子
            AddContextMenu("孙子", sub1.DropDownItems, new EventHandler(MenuClicked));
            AddContextMenu("-", subItem.DropDownItems, null);//增加一个分割线
            AddContextMenu("没有快捷键", subItem.DropDownItems, new EventHandler(MenuClicked));

        }
        /// <summary>
        /// 添加子菜单
        /// </summary>
        /// <param name="text">要显示的文字,如果为 - 则显示为分割线</param>
        /// <param name="cms">要添加到的子菜单集合</param>
        /// <param name="callback">点击时触发的事件</param>
        /// <returns>生成的子菜单,如果为分隔条则返回null</returns>

        ToolStripMenuItem AddContextMenu(string text, ToolStripItemCollection cms, EventHandler callback)
        {
            if (text == "-")
            {
                ToolStripSeparator tsp = new ToolStripSeparator();
                cms.Add(tsp);
                return null;
            }
            else if (!string.IsNullOrEmpty(text))
            {
                ToolStripMenuItem tsmi = new ToolStripMenuItem(text);
                tsmi.Tag = text + "TAG";
                if (callback != null) tsmi.Click += callback;
                cms.Add(tsmi);

                return tsmi;
            }

            return null;
        }
        void MenuClicked(object sender, EventArgs e)
        {
            //以下主要是动态生成事件并打开窗体

            //((sender as ToolStripMenuItem).Tag)强制转换

            //ObjectHandle t = Activator.CreateInstance("WinForms", "WinForms.Form2");
            //Form f = (Form)t.Unwrap();
            //f.ShowDialog();
            string s = (sender as ToolStripMenuItem).Text;
            MessageBox.Show(s);
        }
    }

  

menuStrip1动态添加菜单及快捷键

原文:https://www.cnblogs.com/lkf18/p/10674551.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!