I have created a simple application with plugin system using reflection, it is working very well. I want to handle the event in the host application using the method, which is provided in the plugin. how can i do this. my application code are as follow
Plugin Manager
namespace PluginManager
{
public interface PluginImplementor
{
string PluginName();
void MenuAdder(ToolStripItem m);
}
}
Host Application
namespace MYPLUGINAPP
{
public partial class Form1 : Form
{
PluginImplementor PM;
ToolStripItem ts;
string[] DllAdd = new string[1000];
PluginsInfo pi = new PluginsInfo();
bool formplugin = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
LoadPlugins();
}
private void addPluginToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK && openFileDialog1.FileName.Length > 0)
{
string filename = openFileDialog1.SafeFileName;
string targetAdd = @"../../Plugins";
string target = System.IO.Path.Combine(targetAdd, filename);
System.IO.File.Copy(openFileDialog1.FileName, target, true);
LoadPlugins();
pi.listBox1.Items.Add(PM.PluginName());
}
}
public void LoadPlugins()
{
foreach (var files in Directory.GetFiles(@"../../Plugins", "*dll"))
{
var assembly = Assembly.LoadFrom(@"../../Plugins" + files);
foreach (var type in assembly.GetTypes())
{
if (type.GetInterfaces().Contains(typeof(PluginImplementor)))
{
PM = Activator.CreateInstance(type) as PluginImplementor;
string name = PM.PluginName();
ts = menuStrip1.Items.Add(name);
PM.MenuAdder(ts);
}
}
}
}
private void showInstalledPluginsToolStripMenuItem_Click(object sender, EventArgs e)
{
pi.ShowDialog();
}
}
}
Plugin
namespace Library_Plugin
{
public class Starter : PluginImplementor
{
public string PluginName()
{
return "Hello";
}
public void MenuAdder(System.Windows.Forms.ToolStripItem ts)
{
ts.Click += ts_Click;
}
void ts_Click(object sender, EventArgs e)
{
System.Windows.Forms.MessageBox.Show("I am plugin");
}
}
}
Please provide any better way through i can solve this problem, if i am doing it wrong.
Thanks in Advance
Aucun commentaire:
Enregistrer un commentaire