[翻译]kean' blog 在一个.net应用程序中调用autocad - 精华帖集合
www.dimcax.com
[翻译]kean' blog 在一个.net应用程序中调用autocad
程序员通常要么整合功能到autocad(利用其plug-in结构,以增加命令,用户界面,对象等),或者调用它自动完成任务。显然,这两者之间的界限已经比较模糊,但是今天我们重点介绍第二类。 用于帮助理解后面的说明,我想介绍两种类型的应用程序交互。 out-of-process 在这种情况下,我们有两个独立的程序试图交互。试想你有一个exe和你想调用的autocad。你需要某种方式来启动它,并却与它通讯,通常可是使用com,之前是dde。通讯按照定义来说是由跨进程间通信(),ipc对于发送大量数据显得效率十分低下。这时就为什么原来的ads和外部vb程序运行十分缓慢的原因。 in-process 当你的代码打包为dll(无论是vb6的activex dll还是objectarx模块,或者.net封装的dll),他和主进程(autocad)的通讯与ipc相比就要快捷的多,数据可以通过指针和引用进行传递。 目前大部分autocad的api都是为in-process设计的。包括lisp,objectarx和autocad的.net api。许多人希望autocad可以通过.net remoting在out-of-pocess模式下被调用,但这并不是托管api的初衷:它实际上被封装在使用指针调用和存取objects的objectarx之上,而且它并不是跨越进程界限的处理工作。com的一个很好的特点是,它既可以工作于out-of-process模式(外部exe),也可以在in-process(vba,或者通过调用getinterfaceobject()来装载一个vb6 activex dll)。这是一个从外部应用程序调用autocad的最好的办法。 我通常不推荐越过进程边界传递太多的信息。如果你需要从一个外部应用程序中调用autocad,启动它(或者连接到它的一个正在运行的实例),然后在autocad进程内部加载一个in-process模块处理大量的信息。 下面的代码说明了怎么做到上面的方法。它连接到一个正在运行的autocad实例(可选,你可以调整代码直接启动autocad),如果失败,再启动autocad。一旦有一个正在运行的实例,我们使之可见,并且运行一个自定义的命令。 你需要在你的应用程序中添加"autocad type library"引用 this c# code can be added to an “on-click” event handler for a button (for example) or another function that makes sense in the context of your application. using system; using system.runtime.interopservices; using autodesk.autocad.interop; // "autocad.application.17" uses 2007 or 2008, // whichever was most recently run // "autocad.application.17.1" uses 2008, specifically const string progid = "autocad.application.17.1"; acadapplication acapp = null; try { acapp = (acadapplication)marshal.getactiveobject(progid); } catch { try { type actype = type.gettypefromprogid(progid); acapp = (acadapplication)activator.createinstance( actype, true ); } catch { messagebox.show( "cannot create object of type \"" + progid + "\"" ); } } if (acapp != null) { // by the time this is reached autocad is fully // functional and can be interacted with through code acapp.visible = true; acapp.activedocument.sendcommand("_mycommand "); }