反射应用一则

来源:互联网 发布:四川广电广元网络纪检 编辑:程序博客网 时间:2024/06/08 17:58

        private void MenuDropDownOpenedHandler(object sender, EventArgs e)
        {
            ToolStripMenuItem menu = sender as ToolStripMenuItem;
            //Console.WriteLine("this DropDown menu is : {0}", menu.Text);
            foreach (ToolStripItem item in menu.DropDownItems)
            {
                ToolStripMenuItem childMenu = item as ToolStripMenuItem;
                if (childMenu == null)//非ToolStripMenuItem项,不处理
                {
                    continue;
                }
                else
                {
                    if(childMenu.DropDownItems.Count > 0 )//DropDown菜单,不处理
                    {
                        continue;
                    }
                    else//叶子菜单,判断是否订阅Click事件,已决定是否Disable
                    {
                        PropertyInfo propertyInfo = (typeof(ToolStripItem)).GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
                        EventHandlerList eventHandlerList = (EventHandlerList)propertyInfo.GetValue(childMenu, null);
                        FieldInfo fieldInfo = (typeof(ToolStripItem)).GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic);
                        Delegate d = eventHandlerList[fieldInfo.GetValue(null)];
                        //Console.WriteLine("this Click menu is: {0}", childMenu.Text);
                        if (d != null)
                        {
                            //foreach (Delegate de in d.GetInvocationList())
                            //{
                            //    Console.WriteLine(de.Method.Name);
                            //}
                            childMenu.Enabled = true;
                        }
                        else
                        {
                            childMenu.Enabled = false;
                        }
                    }
                }
            }
        }

原创粉丝点击