1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 using System.IO; 10 using System.Reflection; 11 using NotePadInfer; 12 13 namespace NotePad 14 { 15 public partial class Form1 : Form 16 { 17 public Form1() 18 { 19 InitializeComponent(); 20 } 21 22 private void Form1_Load(object sender, EventArgs e) 23 { 24 25 //找到路径 26 string exepath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "add"); 27 28 29 //find all dll 30 string[] files = Directory.GetFiles(exepath, "*.dll"); 31 Type extInterface = typeof(NotePadInfer.ExtInfo);//接口类型 32 33 34 foreach (string file in files) 35 { 36 // load dll 37 Assembly assemly = Assembly.LoadFrom(file); 38 //find all public type 39 Type[] extTypes = assemly.GetExportedTypes(); 40 //foreach types 41 foreach (Type item in extTypes) 42 { 43 //判断item是否是实现了接口extInterface 44 if (extInterface.IsAssignableFrom(item) && !item.IsAbstract) 45 { 46 ///实例化类,用实例来调方法和属性 47 ExtInfo instanceInterface = (ExtInfo)Activator.CreateInstance(item); 48 //向菜单栏中动态添加一个菜单项 49 ToolStripItem toolItem = this.格式ToolStripMenuItem.DropDownItems.Add(instanceInterface.Name); 50 toolItem.Tag = instanceInterface;//把实例赋给Tag 51 //注册加载的控件的事件 52 toolItem.Click += new EventHandler(toolItem_Click); 53 } 54 } 55 56 } 57 } 58 59 void toolItem_Click(object sender, EventArgs e) 60 { 61 //sender这里是下拉单 62 ToolStripItem strip = sender as ToolStripItem; 63 if (strip!=null) 64 { 65 if (strip.Tag!=null) 66 { 67 ExtInfo t = strip.Tag as ExtInfo; 68 t.Run(textBox1); 69 } 70 } 71 } 72 73 74 75 76 77 78 } 79 }
NoteInfo接口中的代码
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Windows.Forms; 6 7 namespace NotePadInfer 8 { 9 public interface ExtInfo 10 { 11 //插件的名字 12 string Name 13 { 14 get; 15 } 16 17 //插件的运行 插件修改的是textbox 18 void Run(TextBox text); 19 20 21 22 } 23 }
控件的代码
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using NotePadInfer; 6 using System.Windows.Forms; 7 8 9 namespace NotePadExtControl 10 { 11 public class ExtControl:ExtInfo 12 { 13 14 public string Name 15 { 16 get { return "To Upper" ; } 17 } 18 19 20 21 public void Run(TextBox text) 22 { 23 text.Text = text.Text.ToUpper(); 24 } 25 } 26 }
原文:http://www.cnblogs.com/nanxiaoxiang/p/5166850.html