用C#对Inventor做开发,网上案例比较少,多数是VBA的代码示例,官方的示例多数也是VBA,仅提供了一部分C#示例,并不完整。
此外,Inventor提供的API文档也是全英文的,刚入门着实不太好理解API的层次关系,需要借助API对象关系图。另外,还需要将英文与中文一一对应,例如Balloon用词典翻译是“气泡”,但是在Inventor中则是一种“标注”。
首先需要引入Inventor的DLL,地址在:C:\Program Files\Autodesk\Inventor 2019\Bin\Public Assemblies\Autodesk.Inventor.Interop.dll。网上有个C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Autodesk.Inventor.Interopv4.0_17.0.0.0__d84147f8b4276564\autodesk.inventor.interop.dll,这个路径里面包含了很多不同版本的DLL,我试了一下,似乎都不能用,可能是因为实际使用的Inventor与DLL之间版本不一致,用上面的地址则没有问题。
话不多说,直接上代码:
//第一段
using Inventor;
using Application = Inventor.Application;
#region 获取Inventor实例
//第二段
private static Inventor.Application inventorApp = null;
private static void GetInventorApplication()
{
try
{
//Marshal.GetActiveObject 从运行对象表(ROT)获取指定对象的运行实例
//第三段
//获取一个Inventor的参考
inventorApp = (Inventor.Application)Marshal.GetActiveObject("Inventor.Application");
Console.WriteLine("查找到可用的实例");
}
catch
{
try
{
Console.WriteLine("没有正常连接到Inventor");
//创建新实例
//第四段
Type inventorAppType = Type.GetTypeFromProgID("Inventor.Application");
Console.WriteLine(inventorAppType.GUID.ToString());
Console.WriteLine("重新创建一个Inventor实例");
inventorApp = Activator.CreateInstance(inventorAppType) as Application;
Console.WriteLine("创建新Inventor实例完毕");
}
catch
{
Console.WriteLine("创建新实例失败");
Process.GetCurrentProcess().Close(); //Diagnostics.Process 获取新的Process组件并将其与当前活动的进程关联
}
}
finally
{
if (inventorApp != null)
{
Console.WriteLine("生成了Inventor实例并显示Inventor");
//第五段
inventorApp.ApplicationEvents.OnQuit += ApplicationEvents_OnQuit;
//inventorApp.WindowState = WindowsSizeEnum.kMaximize; //将Inventor窗口大小设置为最大窗口
inventorApp.WindowState = WindowsSizeEnum.kNormalWindow;
inventorApp.Visible = false;
inventorApp.SilentOperation = true;
}
}
}
private static void ApplicationEvents_OnQuit(EventTimingEnum BeforeOrAfter, NameValueMap context, out HandlingCodeEnum HandlingCode)
{
Console.WriteLine("触发OnQuit事件");
//HandlingCodeEnum 从某些事件中返回的代码
//OnQuit 当Inventor被关闭时通知client
//第六段
inventorApp.ApplicationEvents.OnQuit -= ApplicationEvents_OnQuit;
HandlingCode = HandlingCodeEnum.kEventHandled; //kEventHandled绕过本地行为 /更多详见后面的备注
//inventorApp = null; //仅仅用这个不能关闭Inventor进程,必须要用杀进程的方法
///inventorApp.Quit(); //用于毙掉Inventor进程
// Process.GetCurrentProcess().Kill();
Console.WriteLine("关闭Inventor,结束操作");
}
#endregion