今天在博客园第一次写博,献丑了,有不对的角度,请大家指出并帮忙分析,十分感谢。

      上次看了《C# 插件式程序开发》有关插件模式开发,

  地址:http://www.cnblogs.com/sndnnlfhvk/archive/2011/06/02/2067713.html

  很有兴趣,今天提手在电脑前稍微改了下。

      目录如下(目录结构和《C# 插件式程序开发》类似,只是多加 WindowShow项目,所有需要加载DLL都放在Plugins目录下):

     

    Proplugins为启动项目,主界面基本没变化,在此引用下图片:

    WindowShow生成DLL文件也被保存在Plugins文件夹下,作为插件加载,显示名称为Form3
    FormShow显示按钮名称为Form2,之前名称没命名好
    Plugins显示按钮名称为Form1,之前名称没命名好
    Interfaces目录下是主接口,所有窗体都会实现这个接口中包含方法。
  生成DLL文件如下:
    
       AllPlugins.dll含有Form1和Form2
       Windowshow.dll 包含Form3

 启动界面显示如下:

        

    来看看点击Form2按钮后效果:(出现窗体2,点击出现对话框,窗体2就是FormShow)

        

            看看Form3效果:窗体3既是WindowShow项目下的Form3
           
       在主界面显示时,给每个按钮都加了事件,以便点击出现效果:
            在界面生成时按钮是如何加载的:
   
1 ///返回Arraylist对象,内包含所有要显示窗体的对象
2  list= PluginsIn.instance.Plugins;
3  for (int i = 0; i < list.Count;i++)
4 {
5 Type t=list[i].GetType();
6 listBox1.Items.Add(t.Name);
7 Button bt = new Button();
8 //bt.Size = new Size(new Point(100, 40));
9 //按钮名称以数字形式命名,既list中object的序列
10   bt.Name = i.ToString();
11 bt.Text = t.Name;
12 //给按钮加入更多内容
13 //bt.Image=ImageClass.Images.Images[i];
14 //每个按钮加入事件
15 bt.Click += new EventHandler(button_Click);
16 this.MenuButtonPanel.Controls.Add(bt);
17 }
        点击按钮后触发内容:
View Code
1 private void button_Click(object sender, EventArgs e)
2 {
3 Button b = sender as Button;
4 int i=Convert.ToInt32(b.Name);
5 // i的值就是list中object
6 object obj = list[i];
7 Type t = obj.GetType();
8 MethodInfo OnShowDlg = t.GetMethod("OnShowDlg");
9 OnShowDlg.Invoke(obj, null);
10 }

            加载DLL程序:

View Code
1 public class PluginsIn
2 {
3 public readonly static PluginsIn instance=new PluginsIn();
4
5 public PluginsIn()
6 {
7 loadAllPlugins();
8 }
9
10 /// <summary>
11 /// 存储控件
12 /// </summary>
13 private ArrayList plugins = new ArrayList();
14
15 public ArrayList Plugins
16 {
17 get { return plugins; }
18 }
19
20 /// <summary>
21 /// 载入所有插件
22 /// </summary>
23 private void loadAllPlugins()
24 {
25 ///获取插件目录(plugins)所有DLL
26 string[] DLLfiles = Directory.GetFiles(Application.StartupPath + @"\Plugins");
27 foreach (string file in DLLfiles)
28 {
29 if (file.ToUpper().EndsWith(".DLL"))
30 {
31 try
32 {
33 Assembly ass = Assembly.LoadFrom(file);
34 Type[] types = ass.GetTypes();
35 foreach (Type t in types)
36 {
37 if (t.GetInterface("IMainPlugin") != null)
38 {
39 ///实例化对象
40 plugins.Add(ass.CreateInstance(t.FullName));
41 }
42 }
43 }
44 catch (Exception ex)
45 {
46 MessageBox.Show(ex.Message);
47 }
48 }
49 }
50 }
51 }

            以上是实现步骤,欢迎大家指点与评论。

posted on 2011-06-08 01:03  菊花香  阅读(1487)  评论(1编辑  收藏  举报