{
MenuItem newDyItem = new MenuItem(mItems[i][j]);
newDyMainItem.MenuItems.Add(newDyItem);
//将每个菜单的Click事件指向同一个方法
newDyItem.Click += new System.EventHandler(this.NewClick);
}
}//End
//这里可以添加一些固定的菜单(不要定义index值,而且一定要在动态生成菜单的后面加,因为后面Click事件判断是按index的值来确定的)
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {});
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(584, 341);
this.IsMdiContainer = true;
this.Menu = this.mainMenu1;
this.Name = "Form1";
this.Text = "Form1";
}
#endregion
///
/// 应用程序的主入口点。
///
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
//
//使用反射生成菜单事件
//
private void NewClick(object sender, System.EventArgs e)
{
MenuItem item = (MenuItem)sender;
MenuItem par = (MenuItem)item.Parent;
int i = par.Index;
int j = item.Index;
string iDll = mDlls[i][j];
string iClass = iDll.Substring(0,iDll.IndexOf("."))
+ "."
+ iDll.Substring(0,iDll.IndexOf("."));
string iFunc = mFuncs[i][j];
try
{
Assembly asm = Assembly.LoadFrom(iDll);
Type mytype = asm.GetType(iClass);
MethodInfo mi = mytype.GetMethod(iFunc);
object obj = Activator.CreateInstance(mytype);
mi.Invoke(obj,new object[] {this});
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}//End菜单事件
//
//读取菜单文件dymenu.xml
//
public void ReadXml()
{
XmlDocument doc = new XmlDocument();
try
{
doc.Load("dymenu.xml");
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("主菜单");
mMenus = new string[nodes.Count];
mItems = new string[nodes.Count][];
mDlls = new string[nodes.Count][];
mFuncs = new string[nodes.Count][];
int j=0;
foreach(XmlNode node in nodes)
{
mMenus[j] = node.InnerXml.Substring(0,node.InnerXml.IndexOf("<")).Trim();
XmlNodeList ns1 = node.SelectNodes("子菜单");
int i=0;
mItems[j] = new string[ns1.Count];
foreach(XmlNode n in ns1)
{
mItems[j][i] = n.InnerXml.Trim();
i++;
}
XmlNodeList ns2 = node.SelectNodes("菜单DLL");
i=0;
mDlls[j] = new string[ns2.Count];
foreach(XmlNode n in ns2)
{
mDlls[j][i] = n.InnerXml.Trim();
i++;
}
XmlNodeList ns3 = node.SelectNodes("菜单Func");
i=0;
mFuncs[j] = new string[ns3.Count];
foreach(XmlNode n in ns3)
{
mFuncs[j][i] = n.InnerXml.Trim();
i++;
}
j++;
}
}//End读取
}
}
