C#通过插件向表单添加控件

时间:2013-10-05 14:37:20

标签: c#

我正在研究插件系统。我正在尝试通过类/插件添加控件但是我得到的stackoverflow错误

using System;
using System.Windows.Forms;

namespace TGPT_Plugin_Class
{
    public interface MPlugin
    {
        Form CurrentForm { get; set; }
    }
}

插件:

    using System;
    using TGPT_Plugin_Class;
    using System.Windows.Forms;

    namespace Plugin_For_TGPT
    {
        public class ControlAdder : MPlugin
        {
        Button b = new Button();
            public ControlAdder ()
        {
        b.Location = new System.Drawing.Point(50, 50);
        b.Text = "Plugin Button";
        b.Size = new System.Drawing.Size(70, 30);
        CurrentForm.Controls.Add(b);
    }



        public Form CurrentForm
        {
            get
            {
                return CurrentForm;
            }
            set
            {
                CurrentForm = value;
            }
        }
    }
}

主要应用:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
using TGPT_Plugin_Class;

namespace The_Great_Plugin_Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Assembly.LoadFrom(ofd.FileName);
                foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
                {
                    foreach (Type t in a.GetTypes())
                    {
                        if (t.GetInterface("MPlugin") != null)
                        {
                            try
                            {
                                MPlugin pluginclass = Activator.CreateInstance(t) as MPlugin;
                                pluginclass.CurrentForm = this;
                                return;
                            }
                            catch
                            {
                            }
                        }
                    }
                }
            }
        }
    }
}

无论如何都要远程添加控件?或者无论如何要制作更好的插件?

1 个答案:

答案 0 :(得分:1)

在c#项目中实现addin有很多可能性:

1)这是一个说明基本技术的例子:

Plugin architecture using c#

2)在.NET 4和4.5中,您可以使用MEF来完成大部分管道工作。

3)使用.NET 3.5你有System.AddIn但我认为太复杂了(如果你愿意,可以看一个例子here