標籤:
外掛程式介面
namespace IMsg{ ///<summary> /// 這是外掛程式必須實現的介面,也是主程式與外掛程式通訊的唯一介面 /// 換句話說,主程式只認識外掛程式裡的這些方法 ///</summary> public interface IMsgPlug { /// <summary> /// 顯示表單 /// </summary> void OnShowDlg(); /// <summary> /// 顯示資訊 /// </summary> /// <returns></returns> string OnShowInfo(); }}
外掛程式1
using IMsg;using System;namespace MYPlugin1{ public class myConsole : IMsgPlug { #region IMsgPlug 成員 public void OnShowDlg() { Console.WriteLine("控制台調用外掛程式的OnShowDlg方法"); } public string OnShowInfo() { return "myConsole"; } #endregion }}
外掛程式2
using IMsg;using System.Windows.Forms;namespace MYPlugin1{ public class MYDlg : Form, IMsgPlug { #region IMsgPlug 成員 public void OnShowDlg() { this.Text = "外掛程式子表單"; this.ShowDialog();//調用Form的ShowDialog,顯示表單 } public string OnShowInfo() { return "MyDlg"; } #endregion }}
winform調用外掛程式
using System;using System.Collections;using System.IO;using System.Reflection;using System.Windows.Forms;namespace MsgBoxMain{ public partial class FormMain : Form { ///<summary> /// 存放外掛程式的集合 ///</summary> private ArrayList plugins = new ArrayList(); public FormMain() { InitializeComponent(); } ///<summary> /// 載入所有外掛程式 ///</summary> private void LoadAllPlugs() { //擷取外掛程式目錄(plugins)下所有檔案夾 DirectoryInfo dirs = new DirectoryInfo(Application.StartupPath + @"\Plugins"); foreach (DirectoryInfo dir in dirs.GetDirectories()) { //擷取檔案夾下檔案 string[] files = Directory.GetFiles(dir.FullName); foreach (string file in files) { if (file.ToUpper().EndsWith(".DLL")) { try { //載入dll Assembly ab = Assembly.LoadFrom(file); Type[] types = ab.GetTypes(); foreach (Type t in types) { //如果某些類實現了預定義的IMsg.IMsgPlug介面,則認為該類適配與主程式(是主程式的外掛程式) if (t.GetInterface("IMsgPlug") != null) { plugins.Add(ab.CreateInstance(t.FullName)); listBox1.Items.Add(t.FullName); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } } private void btnLoadPlug_Click(object sender, EventArgs e) { LoadAllPlugs(); } //調用外掛程式的方法 private void btnExecute_Click(object sender, EventArgs e) { if (this.listBox1.SelectedIndex == -1) return; object selObj = this.plugins[this.listBox1.SelectedIndex]; Type t = selObj.GetType(); MethodInfo OnShowDlg = t.GetMethod("OnShowDlg"); MethodInfo OnShowInfo = t.GetMethod("OnShowInfo"); OnShowDlg.Invoke(selObj, null); object returnValue = OnShowInfo.Invoke(selObj, null); this.lblMsg.Text = returnValue.ToString(); } }}
介面
c# winform外掛程式