C# 插件开发学习实例

来源:互联网 发布:2级野猪骑士升级数据 编辑:程序博客网 时间:2024/05/17 02:48

最近在看蒋波涛先生的插件式GIS开发的书。由于对插件原理不懂。进展不是很顺利。看了某个教学视频关于插件的介绍,略懂,写下此文,记录。

以下是模拟一个记事本,将其中的格式用插件的形式实现。

STEP 1:新建一个窗体应用程序。

此时格式下面没有内容。将通过插件添加颜色和字体下拉选项。

 

STEP2: 添加一个类库。该类库用来生成接口。

 public interface ImyInterFace    {        // 显示在按钮中的字符        string Name        {            get;                   }        // 执行操作        void Func(TextBox content);    }

其中,Name,用来设置下拉菜单名字,Func执行对下拉菜单的操作。同理,可以设置诸如图片等属性。

STEP3:编写插件 用来具体实现下拉菜单的功能。

新建一个类库。类库中的类继承 STEP2 中的接口ImyInterFace。

 public class Class1:ImyInterFace    {        #region ImyInterFace 成员        public string Name        {            get {                                return "设置字体颜色";                        }        }        public void Func(System.Windows.Forms.TextBox content)        {            ColorDialog cd = new ColorDialog();            if(cd.ShowDialog()==DialogResult.OK)            {                content.ForeColor = cd.Color;            }        }

设置字体颜色的定义。

STEP4:生成解决方案。

将插件的类库的 dll文件放在窗体启动Debug目录下新建的plugins目录下。每次启动程序,遍历该文件夹下的dll文件,即插件。

STEP5: 宿主程序中加载插件

在form的load事件中。加载插件。生成插件的事件。

   // 加载插件        private void Form1_Load(object sender, EventArgs e)        {            string path = Application.StartupPath;            path = System.IO.Path.Combine(path,"plugins");            //遍历里面所有的dll文件            string [] dlls =System.IO.Directory.GetFiles(path,"*.dll");            foreach (string item in dlls)            {                //加载程序集                Assembly asm;                try                {                    asm = Assembly.LoadFile(item);                }                catch(Exception ex)                {                    System.IO.File.AppendAllText("log.txt",ex.Message.ToString()+"\t"+System.DateTime.Now.ToString()+"\r\n");                    continue;                                    }                //开始得到类型                Type[] myType = asm.GetTypes();                //遍历type数组,找到实现接口的非抽象类                for (int i = 0; i < myType.Length; i++)                {                    if (typeof(ImyInterFace).IsAssignableFrom(myType[i]) )                    {                        if (myType[i].IsAbstract)                        { return; }                                            //创建对象                        ImyInterFace myEditor = (ImyInterFace)Activator.CreateInstance(myType[i]);                        ToolStripMenuItem tsmi = new ToolStripMenuItem(myEditor.Name);                        tsmi.Tag = myEditor;                        msFormat.DropDownItems.Add(tsmi);                        tsmi.Click += new EventHandler(tsmi_Click);                    }                }                            }        }

 

STEP6: 编写插件的触发事件。

  void tsmi_Click(object sender, EventArgs e)        {            ImyInterFace my=(ImyInterFace)((ToolStripMenuItem)sender).Tag;            my.Func(textBox1);        }

STEP: 启动程序。

 

0 0
原创粉丝点击