先看效果,这个方法可以用于任何形式的程序,思路就是这样我比较喜欢偷懒
这个按钮是自动添加上去的
1# 定义一个特性
public class MyPdmsFunction : Attribute
{
public string FunctionName { get; set; }
public string ClassName { get; set; }
public MyPdmsFunction(string _Name,string _clsName="")
{
this.FunctionName = _Name;
this.ClassName = _clsName;
}
}
2# 写自己的方法,并在方法上标记该特性
public class 画圆测试
{
[MyPdmsFunction(nameof(画圆测试), nameof(画圆测试函数))]
public static void 画圆测试函数(WindowManager wm, Command _cmd)
{
var draftApp = new MarDrafting();
MarUi marui = new MarUi();
var pt = new MarPointPlanar();
marui.PointPlanarReq("指定一个圆心:\n", pt);
var pt1 = new MarPointPlanar();
marui.PointPlanarReq("指定一个圆上的一点:\n", pt1);
var r = pt.DistanceToPoint(pt1);
draftApp.CircleNew(new Aveva.Marine.Geometry.MarCirclePlanar(pt, r));
wm.StatusBar.Text = "创建成功!";
}
}
3#在你的主窗体上做文章,利用特性和反射知识动态加载按钮和按钮的事件
public partial class UserControl1 : UserControl
{
public WindowManager WinManager { get; set; }
public Command Cmd { get; set; }
public UserControl1(WindowManager wm, Command _cmd)
{
InitializeComponent();
this.WinManager = wm; this.Cmd = _cmd;
//反射读取程序集
var allCls = Assembly.GetExecutingAssembly().GetTypes().Where(a => a.IsClass && a.IsPublic);
List<MethodInfo> mis = new List<MethodInfo>();
//提取所有含有自定义特性标记的方法
foreach (var item in allCls)
{
var curClsMis = item.GetMethods().Where(m => m.GetCustomAttributes(typeof(MyPdmsFunction), true).Any());
if (curClsMis.Count() > 0) mis.AddRange(curClsMis);
}
if (mis.Any())
{
var i = 0;
foreach (var mi in mis)
{
MyPdmsFunction myAtt = mi.GetCustomAttributes(true).First(att => att.GetType().FullName == typeof(MyPdmsFunction).FullName) as MyPdmsFunction;
var btn = new Button();
this.SuspendLayout();
btn.Location = new System.Drawing.Point(15, 30 * (i + 1));
btn.Name = myAtt.FunctionName;
btn.Size = new System.Drawing.Size((int)(this.Width * 0.85), 25);
btn.TabIndex = i;
btn.Text = myAtt.FunctionName;
btn.UseVisualStyleBackColor = true;
btn.Click += (o, e) => mi.Invoke(mi.IsStatic ? null : Activator.CreateInstance(mi.DeclaringType), new object[] { wm, _cmd });
this.Controls.Add(btn);
i++;
}
}
}
}
}