《solidworks二次开发全教程系列.doc》由会员分享,可在线阅读,更多相关《solidworks二次开发全教程系列.doc(63页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、solidworks二次开发全教程系列solidworks二次开发-01-录制一个宏 第一步:我们需要自己录制一个宏,然后看看程序产生了什么代码。当初学习excel时候就是这么干的。只是,solidworks要复杂一些,直接录制的宏不能使用,需要做一些调整。在没有经验的时候我们最好按照下面的建议来做。Edit or Debug SolidWorks MacroEdit or debug SolidWorks macros using Microsoft VBA. 使用Microsoft VBA编辑或调试宏To edit or debug a SolidWorks macro:Click Edi
2、t Macro on the Macro toolbar, or click Tools, Macro, Edit.NOTES: 注意:To automatically edit a macro after recording it, click Tools, Options, Systems Options. On the General tab, select Automatically edit macro after recording and click OK. This setting is persistent across SolidWorks sessions. 此选项Aut
3、omatically edit macro after recording 顾名思义是在记录宏完毕后自动打开编辑界面。If you recently edited the macro, you can select it from the menu when you click Tools, Macro. This menu lists the last nine macros that you edited. 已经编辑了宏,菜单中会有最近的9个宏程序列表供选择。In the dialog box, select a macro file (.swp) and click Open. 选择一个
4、宏swp文件NOTE: You can also edit .swb files, which are older-style SolidWorks macro files. When you run or edit a .swb file, it is automatically converted to a .swp file. 旧的宏文件后缀为swb,你也可以打开swb,那么会自动保存为swp。Edit or debug the macro. If it is a new macro, be sure to:如果是新的宏Delete extra lines of code: 删除一些多余
5、的代码:The following variables are declared automatically in a SolidWorks macro. Delete any variables not used in the macro. 这些对象的声明是自动产生的,可以将没用的删除 Dim swApp As ObjectDim Part As ObjectDim boolstatus As BooleanDim longstatus As Long, longwarnings As LongDim FeatureData As ObjectDim Feature As ObjectDim
6、 Component As ObjectDelete all lines of code that change the view. 删除切换试图的代码 译者注:像这样的 Part.ActiveView().RotateAboutCenter 0.0662574, 0.0346621 无情的删掉吧Delete all ModelDocExtension:SelectByID2 calls appearing immediately before ModelDoc2:ClearSelection2 calls. However, do not delete ModelDocExtension:S
7、electByID2 calls appearing immediately after ModelDoc2:ClearSelection2 calls.Delete all ModelDoc2:ClearSelection2 calls appearing immediately before ModelDocExtension:SelectByID2. solidworks二次开发-02-用来访问特征的两个API 来学习两个api:SelectByID2和GetSelectedObject5。这两个函数,第一个通过给出对象的name选择对象。第二个通过启用程序前已经选择的索引得到对象。看下
8、面程序:Option ExplicitDim swApp As SldWorks.SldWorksDim Model As ModelDoc2Dim feature As featureDim boolstatus As VariantSub main()Set swApp = Application.SldWorksSet Model = swApp.ActiveDoc 选择叫拉伸1的特征boolstatus = Model.Extension.SelectByID2(拉伸1, BODYFEATURE, 0, 0, 0, False, 0, Nothing, swSelectOptionDe
9、fault)主要就是这一句话,在写Option Explicit后函数的最后一个参数swSelectOptionDefault可以使用0来代替 If the selection was successful, that is, Extrude1 was selected and it is a BODYFEATURE, then get that feature; otherwise, indicate failureIf boolstatus = True Then 如果有“拉伸1”这个特征下面的代码将其选中 Dim SelMgr As SelectionMgr Set SelMgr = M
10、odel.SelectionManager Set feature = SelMgr.GetSelectedObject5(1) 此处使用一个索引来得到特征 Debug.Print feature.NameElse Debug.Print ErrorEnd IfEnd Sub最后列出这两个函数的VB语法:ModelDocExtension:SelectByID2DescriptionThis method selects the specified entity.Syntax (OLE Automation)retval = ModelDocExtension.SelectByID2 ( Na
11、me, Type, X, Y, Z, Append, Mark, Callout. SelectOption )Input:(BSTR) NameName of object to select or an empty stringInput:(BSTR) TypeType of object (uppercase) as defined in swSelectType_e or an empty stringInput:(double) XX selection location or 0Input:(double) YY selection location or 0Input:(doub
12、le) ZZ selection location or 0Input:(VARIANT_BOOL) AppendIf.And if entity is.Then. TRUENot already selectedThe entity is appended to the current selection listAlready selectedThe entity is removed from the current selection listFALSENot already selectedThe current selection list is cleared, and then
13、 the entity is put on the listAlready selectedThe current selection list remains the sameInput:(long) MarkValue that you want to use as a mark; this value is used by other functions that require ordered selectionInput:(LPCALLOUT) CalloutPointer to the associated calloutInput:(long) SelectOptionSelec
14、tion option as defined in swSelectOption_e (see Remarks)Output:(VARIANT_BOOL) retvalTRUE if item was successfully selected, FALSE if notSelectionMgr:GetSelectedObject5DescriptionThis method gets the selected object.Syntax (OLE Automation)retval = SelectionMgr.GetSelectedObject5 ( AtIndex )Input:(lon
15、g) AtIndexIndex position within the current list of selected items, where AtIndex ranges from 1 to SelectionMgr:GetSelectedObjectCountOutput:(LPDISPATCH) retvalPointer to the Dispatch object as defined in swSelType_e; NULL may be returned if type is not supported or if nothing is selected solidworks
16、二次开发-03-访问特征数据 coder arden filename : getchoosed.swpdate :2005-03-22used to get the simple hole infomation dep & diafinished lucky !-Option ExplicitDim swApp As SldWorks.SldWorksDim Model As ModelDoc2Dim curfeature As featureDim boolstatus As BooleanDim featdata As SimpleHoleFeatureData2 声明一个简单直孔对象D
17、im component As Component2 Dim dep As DoubleDim dia As DoubleDim SelMgr As SelectionMgrDim ncount As IntegerSub getselected()Set swApp = Application.SldWorksSet Model = swApp.ActiveDocSet SelMgr = Model.SelectionManagerSet curfeature = SelMgr.GetSelectedObject5(1) 得到当前选中的第一个特征 MsgBox curfeature.Name
18、 Set featdata = curfeature.GetDefinition 得到特征的定义boolstatus = featdata.AccessSelections(Model, component) 可以对数据进行访问了ncount = featdata.GetFeatureScopeBodiesCount MsgBox ncountdep = featdata.Depth dia = featdata.DiameterMsgBox dia & * & depMsgBox error arden 在solidworks中可以使用swAPP.sendmsgtouser2 featdat
19、a.ReleaseSelectionAccessModel.SaveModel.EditRebuildEnd Sub*上面程序运行前,假设你选择了一个简单直孔特征。然后得到这个孔德一些参数。孔深、直径等。solidworks的API虽然是e文的。介绍的还算详细,并且有很多的example。大家可以多看看代码。要访问一个特征,需要经历这样的步骤:定义一个特征对象: dim.as .得到这个特征 :比如使用GetSelectedObject5 还有SelectebyID等.得到定义:GetDefinition进行访问:AccessSelections上面的程序没有if选择的容错机制,需要添加上。
20、solidworks二次开发-04-修改数据 上次已经可以访问特征的各参数了,今天我们来修改它:要修改前面的步骤不能少,当我们已经可以读取一些特征时,我们就可以给他设定一些值。当然有时需要调用特定的参数。solidworks是ole和com的,所以要习惯这样。在修改完特征后需要调用函数modifydefinition()来实现变化。我们给一个例子,这个例子比前面的都要全面,它有很好的容错引导机制,可以直接拿来成为一个稳定的宏程序。This example doubles the length of the base extrude.这个例子将拉伸凸台的长度增加一倍Dim swApp As Sl
21、dWorks.SldWorksDim Model As ModelDoc2Dim Component As Component2Dim CurFeature As featureDim isGood As Boolean Will become an ExtrudeFeatureData ObjectDim FeatData As Object Dim Depth As DoubleDim SelMgr As SelectionMgrSub doubleBE()- -Set swApp = CreateObject(sldWorks.application)- -Set Model = swA
22、pp.ActiveDoc- - Make sure that the active document is a part- -If Model.GetType swDocPART And Model.GetType swDocASSEMBLY Then这里的swDocPART 、swDocASSEMBLY 我的环境没有通过。我使用msgbox Model.GetType 的笨办法得到整数为1和2 - -Msg = Only Allowed on Parts or Assemblies Define message- -Style = vbOKOnly OK Button only- -Titl
23、e = Error Define title- -Call MsgBox(Msg, Style, Title) Display error message- -Exit Sub Exit this program- -End If- - - Get the Selection Manager- -Set SelMgr = Model.SelectionManager- - - Get the selected object (first in the group if there are more than one)- - Note that at this point CurFeature
24、is just a Feature Object- -Set CurFeature = SelMgr.GetSelectedObject3(1)- -If CurFeature Is Nothing Then- - Tell the user that nothing is selected- -swApp.SendMsgToUser2 Please select the Base-Extrude, swMbWarning, swMbOk- -Exit Sub- -End If- - Check the features type name- - Make sure it is an extr
25、usion- -If Not CurFeature.GetTypeName = swTnExtrusion Then 在这里使用swTnExtrusion我的环境没有通过,我改成了Extrusion才ok- -swApp.SendMsgToUser2 Please select the Base-Extrude, swMbWarning, swMbOk- -Exit Sub- -End If- - Get the Extrusions Feature Data- -Set FeatData = CurFeature.GetDefinition- - - Get the access selec
26、tions for the feature data- - Note that Component is NULL when accessing the selections of a standalone part. - -If we were calling AccessSelections from within an assembly, then model would refer to the top-level document in the assembly and component would refer to the actual part.- -isGood = Feat
27、Data.AccessSelections(Model, Component)- - - Inform the user of an error- -If Not isGood Then- -swApp.SendMsgToUser2 Unable to obtain access selections, swMbWarning, swMbOk- -Exit Sub- -End If- - - Make sure the user has selected the base extrude- -If Not FeatData.IsBaseExtrude Then- -swApp.SendMsgT
28、oUser2 Please select the Base-Extrude, swMbWarning, swMbOk- -FeatData.ReleaseSelectionAccess- -Exit Sub- -End If- - - Change the depth of this extrusion to double its previous depth- -Depth = FeatData.GetDepth(True)- -FeatData.SetDepth True, Depth * 2- - - Implement the changes to the feature- -isGo
29、od = CurFeature.ModifyDefinition(FeatData, Model, Component)- - - If the modify definition failed- -If Not isGood Then- -swApp.SendMsgToUser2 Unable to modify feature data, swMbWarning, swMbOk- - Release the AccessSelections- -FeatData.ReleaseSelectionAccess- -End If- -End Sub如果出现特征出现“退回”状态,我现在还没有找到
30、问题的原因,只能在代码执行到最后调用 Model.Save Model.Rebuild 这两个函数来自动更新。 Solidworks二次开发-05-装配体中插入零部件 在往装配体中插入零部件时,我们使用addcomponent 函数。如果需要选定零部件的配置,则需要使用addcomponent4。先学习下语法:addcomponent4:retval = AssemblyDoc.AddComponent4 ( compName, configName, x, y, z)Input: (BSTR) compName Path name of a loaded part or assembly t
31、o add as a component Input: (BSTR) configName Name of the configuration from which to load the componentInput: (double) x X coordinate of the component centerInput: (double) y Y coordinate of the component centerInput: (double) z Z coordinate of the component centerOutput: (LPCOMPONENT2) retval Poin
32、ter to the Component2 object需要注意的是:参数1为文件的全名(包括路径);参数2为文件的配置名称;当函数执行成功购返回一个指向该零件的指针。于是我们可以如下写一个小程序,用来给装配体中插零件:filename:insertPart.swpwrite by arden2005-4-4this function add a part called “零件1.SLDPRT” in CurrentWorkingDirectoryprecondition is there has a part document called “零件1.SLDPRT” in CurrentWo
33、rkingDirectoryand it has a configuration called “配置1”Dim swApp As SldWorks.SldWorksDim Model As ModelDoc2Dim pth As StringDim strpath As StringSub insertPart()Set swApp = Application.SldWorksstrpath = swApp.GetCurrentWorkingDirectory 当前工作路径Set Model = swApp.ActiveDocpth = strpath & 零件1.SLDPRT 得到文件的F
34、ULLPATH全名Model.AddComponent4 pth, 配置1, 0, 0, 0 添加零部件End Sub然而,这个程序比不是想象中那么好用。为什么呢?回头看addcomponent4的remark,上面这样写:The specified file must be loaded in memory. A file is loaded into memory when you load the file in your SolidWorks session (SldWorks:OpenDoc6) or open an assembly that already contains th
35、e file.就是说你想指定的插入的文件必须在调用函数之前已经在内存中加载了。不习惯,你就不能直接打开多简单,没办法,我还没有找到好的方法,只能按人家的来:看看下面的函数Opendoc6,它打开一个文档:Opendoc6:retval = SldWorks.OpenDoc6 ( filename, type, options, configuration, &Errors, &Warnings )Input: (BSTR) Filename Document name or full path if not in current directory, including extensionIn
36、put: (long) Type Document type as defined in swDocumentTypes_eInput: (long) Options Mode in which to open the document as defined in swOpenDocOptions_eInput: (BSTR) Configuration Model configuration in which to open this document:Applies to parts and assemblies, not drawingsIf this argument is empty
37、 or the specified configuration is not present in the model, the model is opened in the last-used configuration.Output: (long) Errors Load errors as defined in swFileLoadError_eOutput: (long) Warnings Warnings or extra information generated during the open operation as defined in swFileLoadWarning_e
38、Return: (LPDISPATCH) retval Pointer to a Dispatch object, the newly loaded ModelDoc2, or NULL if failed to open这个函数参数1就是文档的全名,参数2是要插入的类型描述,其中0123分别表示: 0 swDocNONE:不是sw文件1 swDocPART:零件2 swDocASSEMBLY:装配体3 swDocDRAWING:工程图如果想使用swDocNONE,需要定义:Public Enum swDocumentTypes_e- -swDocNONE = 0- -swDocPART= 1- -swDocASSEMBLY = 2 swDocDRAWING=3End Enum参数3是打开文档的模式,一般我们就选择swOpenDocOptions_Silent 用0 表示,当然还有只读、只看等选项参数4是打开选项,一般置空后面是两个OutPut,用来显示错误打开时的提示函数返回一个指向打开文件的指针。按照上面的要求我们在向装配体中插入一个零部件时,需要这样步骤:1、得到装配体2、使用opendoc6打开需要插入的零件3、使用addcomponent4插入零件到装配体我们上面的程序