最近做了一个C#的插件式编程的项目,涉及到了在winform下插件和宿主的数据传递。希望实现插件主动向宿主传递数据而不是宿主通过运行一个方法去索要数据。
具体实现是Form1为宿主,在textbox里输入字符串可以传到插件里。
另外是可以在插件里通过鼠标绘图,单击确定将图传递到宿主。
考虑到插件编程,必然涉及到接口,这里我定义接口
namespace interclass
{
public delegate void ChangeDataHandler(List<List<Point>> ptlists); //定义委托
public interface inter
{
DataTransfer DataTransfer { get; set; }
string WhoAmI(DataTransfer DT); //传递DataTransfer进入插件同时获得插件的名字
void Action(object sender, EventArgs e); //插件程序入口
List<List<Point>> PointLists { get; }
event ChangeDataHandler ChangeData; //定义事件
}
public class DataTransfer
{
private string testdata;
public string Testdata { get => testdata; set => testdata = value; }
}
}
参考跨线程和跨窗体传递数据的相关资料,通过委托可以实现插件向宿主主动传递。
在宿主插件中添加动态菜单,绑定单击事件到Action,以开始插件的运行。
下面是宿主窗体载入插件的代码,包含动态菜单的操作。
private List<inter> _plugIns = new List<inter>(); //插件列表
int _countPlugAdded = 0; //插件成功载入计数
int _countPlugAddError = 0; //插件加载失败计数
DataTransfer MainDT; //数据传递的实例
private void Form1_Load(object sender, EventArgs e)
{
List<string> list = new List<string>();
MainDT = new DataTransfer();
//读取插件
string path = System.IO.Path.Combine(System.Environment.CurrentDirectory + @"\dlls\");
DirectoryInfo dir = new DirectoryInfo(path);
FileInfo[] fil = dir.GetFiles();
foreach (FileInfo f in fil)
{
if (f.Extension.Equals(".dll"))
{
list.Add(f.FullName)