管理

C#动态添加菜单栏

Posted on 2022-09-30 14:14  lzhdim  阅读(87)  评论(0编辑  收藏  举报
             /// <summary>
            /// 动态添加串口号到菜单栏
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void Form_Main_Load(object sender, EventArgs e)
            {
                foreach (string com in System.IO.Ports.SerialPort.GetPortNames())//枚举所有可用的串口
                {
                    AddContextMenu(com, Menu_ComChoose.DropDownItems, new EventHandler(MenuClicked));
                }
            }
            /// <summary>
        /// 添加目前存在的串口号到Menu_ComChoose菜单的子菜单栏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Menu_Refresh_Click(object sender, EventArgs e)
        {
            for (int i = 1; i < Menu_ComChoose.DropDownItems.Count; i++)
            {
                Menu_ComChoose.DropDownItems.RemoveAt(i);
            }
            foreach (string com in System.IO.Ports.SerialPort.GetPortNames())//枚举所有可用的串口
            {
                AddContextMenu(com, Menu_ComChoose.DropDownItems, new EventHandler(MenuClicked));
            }
            Menu_ComChoose.ShowDropDown();//展开子菜单
        }
        /// <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;
        }
        /// <summary>
        ///动态子菜单的响应事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void MenuClicked(object sender, EventArgs e)
        {
            Dev_IP_param.comPort = (sender as ToolStripMenuItem).Text;
            //Console.WriteLine("Dev_IP_param.comPort="+Dev_IP_param.comPort);
        }

 

Copyright © 2000-2022 Lzhdim Technology Software All Rights Reserved