因为工作需要,想学习一下SAP2000插件的开发。有幸在网上找到了“酷鱼”写的API开发入门指南(http://blog.sina.com.cn/s/blog_539bb0a70100cnok.html),可是我按照教程,在 Win7 + SAP2000 v15.2.1 + Visual Studio 2010 的环境下无法生成可用的插件,后来在网上重新搜索了一番,总算找到了答案。
主要步骤和酷鱼的文章是一样的,打开VS2010,新建一个C#的类库(Class Library)项目,然后添加对SAP2000.exe的引用,并添加.NET中的 System.Windows.Forms 的引用,然后新建一个类,添加如下代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace SelectCount { // enable class interface for COM [ClassInterface(ClassInterfaceType.AutoDual)] public class cPlugin { // main method for sap2000 plugin public void Main(ref SAP2000v15.cSapModel SapModel, ref SAP2000v15.cSapPlugin ISapPlugin) { int Num = 0; Array objTypes = null; Array objNames = null; SapModel.SelectObj.GetSelected(ref Num, ref objTypes, ref objNames); MessageBox.Show(string.Format("Selected {0} objects.", Num)); ISapPlugin.Finish(0); } // information for sap2000 plugin public long Info(ref String info) { info = "Count Selected Objects. \r\n author: xiaoding"; return 0; } } }
然后在项目属性里,将“为COM互操作注册”勾上,并在AssemblyInfo.cs中,将 ComVisible 属性改为 true
编译后,即可生成SAP2000插件。注意Win7/Vista系统需要用管理员权限运行Visual Studio,否则会出现组件注册失败的信息,这是因为没有足够的权限向系统注册组件。不影响组件的生成,但不能注册就无法在其它软件中使用,所以需要管理员权限。
在此说一下 cPlugin 类中的两个方法,第一个是
public void Main(ref SAP2000v15.cSapModel SapModel, ref SAP2000v15.cSapPlugin ISapPlugin)
这是插件的主方法,提供插件运行的主要逻辑给SAP2000主程序调用。在完成插件操作以后,应该及时调用 ISapPlugin 中的 Finish() 方法,将界面的控制权交回给 SAP2000 主程序。
另外一个方法是可选的,它的方法声明为
public long Info(ref String info)
这是用来在SAP2000主程序中,向用户显示插件说明信息的方法。方法接收一个字符串引用,修改这个引用的String即可更改输出的说明信息,方法返回0表示成功。
以下是 SelectObject 插件在 SAP2000 的插件管理界面的截图,可以看到已经添加成功,并且 Info 按钮可用,按下之后,将显示我们在程序中设置的字符串。
点击这里可以下载以上的插件项目(在VS2010中打开)
--
Courtesy of 结构狮会编程