日期:2009-06-10  浏览次数:20541 次

在不重新编译主程序的情况下要对程序的功能进行扩充,我们可以使用动态生成菜单,将新增的窗体编译成dll文件,然后在主程序的菜单定义文件中注册,即可解决,以后程序升级,只需将对应的dll覆盖。


1.菜单定义文件可以使用ini或XML格式,这里使用的是XML格式

定义主菜单,子菜单,子菜单对应的dll,子菜单对应的函数

dymenu.XML内容如下

<?XML version='1.0'?>
<ROOT>
<主菜单>动态菜单1
<子菜单>OpenForm1</子菜单>
<菜单DLL>MyForms.dll</菜单DLL>
<菜单Func>OpenForm1</菜单Func>
<子菜单>OpenForm2</子菜单>
<菜单DLL>MyForms.dll</菜单DLL>
<菜单Func>OpenForm2</菜单Func>
</主菜单>
<主菜单>动态菜单2
<子菜单>OpenForm3</子菜单>
<菜单DLL>MyForms.dll</菜单DLL>
<菜单Func>OpenForm3</菜单Func>
</主菜单>
<主菜单>动态菜单3
<子菜单>OpenForm4</子菜单>
<菜单DLL>MyForms.dll</菜单DLL>
<菜单Func>OpenForm4</菜单Func>
</主菜单>
</ROOT>

2.菜单对应的MyForms.dll

MyForms.cs 代码如下:

using System;


namespace MyForms
{
public class MyForms
{
public MyForms()
{
}
public void OpenForm1(System.Windows.Forms.Form mainf)
{
Form1 fm = new Form1();
fm.MdiParent = mainf;
fm.Show();
}

public void OpenForm2(System.Windows.Forms.Form mainf)
{
Form2 fm = new Form2();
fm.MdiParent = mainf;
fm.Show();
}
public void OpenForm3(System.Windows.Forms.Form mainf)
{
Form3 fm = new Form3();
fm.MdiParent = mainf;
fm.Show();
}

public void OpenForm4(System.Windows.Forms.Form mainf)
{
Form4 fm = new Form4();
fm.MdiParent = mainf;
fm.Show();
}

}
}


另外还有4个窗体Form1 Form2 Form3 Form4

这里使用的namespace 构造函数 都和dll的名字一致,是为了方便后面主程序调用

3.主程序DyMenu.cs

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Reflection;
using System.XML;

namespace DyMenu
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.MainMenu mainMenu1;

//主菜单
private string[] mMenus;
//子菜单
private string[][] mItems;
//子菜单对应的dll
private string[][] mDlls;
//子菜单对应的函数
private string [][] mFuncs;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;

public Form1()
{
//
// Windows 窗体设计器支持所必需的
//