从这四张图,看了来这个保存实体和分割图标是一样的,可能只是选项不一样,所以这里一起写了,不浪费时间。
经过了几个小时的研究,没搞定。大哭
CreateSaveBodyFeature这个没有api例子,2021上有例子,但只有VBA
https://help.solidworks.com/2021/english/api/sldworksapi/Create_Save_Bodies_Feature_and_Create_Assembly_Example_VB.htm
,但C#里面怎么就是失败,2022上只能建出来空装配体,不知道是api有bug还是啥情况,当然也可能 是我水平不行呀。
所以临时只能间接调用宏来简单实现这个功能了。结果如下图了: 至于宏的参数应该怎么指定,后面再写方案。
当前之前我开发实例中已经用别的办法实现过。其实就是把每个实体单独输出成零件,然后再组装成一个装配。
总结下来,有时候solidworks提供了功能,但api不一定好调用。只能靠自己想办法去处理了
//解决方案: // 在2021中找到一个示例,18版本中测试ok.所以可以采用调用宏//BodiesToAssembly.swp 保存到D\temp下面SldWorks swApp = Utility.ConnectToSolidWorks();var swModel = (ModelDoc2)swApp.ActiveDoc;var swModelDocExt = swModel.Extension;var swSelMgr = (SelectionMgr)swModel.SelectionManager;var swFeatMgr = swModel.FeatureManager;if (swModel.GetType() != (int)swDocumentTypes_e.swDocPART){return;}int err=0;var res= swApp.RunMacro2(RegDllPath("") + @"\BodiesToAssembly.swp", "Macro11", "main", 0, out err);
下面分割的例子拿出来看看,基本上执行正常。
SldWorks swApp = Utility.ConnectToSolidWorks();var swModel = (ModelDoc2)swApp.ActiveDoc;var swModelDocExt = swModel.Extension;var swSelMgr = (SelectionMgr)swModel.SelectionManager;var swFeatMgr = swModel.FeatureManager;//Select the cutting toolvar boolstatus = swModelDocExt.SelectByID2("Top Plane", "PLANE", 0, 0, 0, true, 0, null, 0);object vBodyNames = null;object[] bodiesToMark = new Body2[2];string[] bodyNames = new string[2];object[] bodyOrigins = new Vertex[2];//Get bodies that will result from the split operationobject[] vResultingBodies = null;vResultingBodies = (object[])swFeatMgr.PreSplitBody2();swModel.ClearSelection2(true);//Set up the arrays for the post-split operation//If you do not want to assign body origin, set it to nothing so that the default origin is usedbodyOrigins[0] = null;bodyOrigins[1] = null;bodiesToMark[0] = vResultingBodies[0];bodiesToMark[1] = vResultingBodies[1];//Save the first body to a separate part document//Substitute the name of the actual folder where to save the bodybodyNames[0] = "d:\\temp\\Body1.sldprt";//Do not save the second bodybodyNames[1] = "";DispatchWrapper[] preSplitBodies = null;preSplitBodies = (DispatchWrapper[])ObjectArrayToDispatchWrapperArray((bodiesToMark));vBodyNames = bodyNames;DispatchWrapper[] originsToUse = null;originsToUse = (DispatchWrapper[])ObjectArrayToDispatchWrapperArray((bodyOrigins));//Create the Split feature, consuming all split bodiesvar swFeat = (Feature)swFeatMgr.PostSplitBody2((preSplitBodies), true, (originsToUse), (vBodyNames), "");if (((swFeat != null))){Debug.Print("Split feature: " + swFeat.Name);var swSplitBodyFeat = (SplitBodyFeatureData)swFeat.GetDefinition();swSplitBodyFeat.AccessSelections(swModel, null);swSplitBodyFeat.GetSplitBodies(out object bodyVar, out object PathVar, out object FlagVar);swSplitBodyFeat.ReleaseSelectionAccess();Debug.Print("Bodies consumed? " + swSplitBodyFeat.Consume);Debug.Print(" ");}
这个分割的例子没有什么问题,可以用,我了不解释了。唯一的问题就是还不能指定只分割部分实体。