总体思路
基于.NET Framework控制台应用程序进行SolidWorks二次开发,选中输入零件,实现干涉检查功能。
使用SelectByID2方法,选中待检查零件,然后使用ToolsCheckInterference2方法,传入待检查零件,进行检测。
注意:如果出现无法选中的情况,可能是输入的零件名有问题,本文中零件命名规则为:零件名-sw软件中的序号(在sw软件中为零件名<序号>),之前使用2018年版本的SolidWorks做二次开发的命名规则为:零件名@装配体名,需要多尝试修改几次。
方法介绍
void ToolsCheckInterference2( System.int NumComponents, System.object LpComponents, System.bool CoincidentInterference, out System.object PComp, out System.object PFace )
NumComponents | 待检查的组件数 |
LpComponents | 待检查干涉的组件阵列 |
CoincidentInterference | 如果为 True,则将实体视为干涉,否则为False |
PComp | 输出 发现干涉的组件阵列 |
PFace | 输出 发现干涉的面阵列 |
具体代码
static void Main(string[] args)
{
string[] checkComp = { "part2-1", "part5-1" };
InterCheck(checkComp);
Console.Read();
}
// 对零件执行干涉检查
public static bool InterCheck(string[] checkComp)
{
SldWorks swApp = (SldWorks)Marshal.GetActiveObject("Sldworks.Application");
ModelDoc2 swModel = swApp.ActiveDoc;
SelectionMgr swSelMgr = swModel.SelectionManager;
SelectData selData = swSelMgr.CreateSelectData();
AssemblyDoc swAssy = swModel as AssemblyDoc;
bool checkstatus = false;
object vIntCompArray = null;
object vIntFaceArray = null;
Component2[] compArray = new Component2[checkComp.Length];
int nSelCount;
bool boolstatus = false;
if (swApp != null)
{
// 读取零件名
swModel.ClearSelection();
for (int i = 0; i < checkComp.Length; i++)
{
// 选中零件
boolstatus = Global.swModel.Extension.SelectByID2(checkComp[i], "COMPONENT", 0, 0, 0, true, 0, null, 0);
Global.swSelMgr.AddSelectionListObject(checkComp[i], selData);
}
nSelCount = swSelMgr.GetSelectedObjectCount();
}
else
{
Console.WriteLine("SolidWorks is not connected!");
}
for (int i = 0; i < checkComp.Length; i++)
{
compArray[i] = swSelMgr.GetSelectedObjectsComponent2(i + 1);
}
// 干涉检查
swAssy.ToolsCheckInterference2(checkComp.Length, ObjectArrayToDispatchWrapper(compArray), checkstatus, out vIntCompArray, out vIntFaceArray);
if (vIntCompArray == null && vIntFaceArray == null)
{
checkstatus = false;
Console.WriteLine("不干涉");
}
else
{
checkstatus = true;
Console.WriteLine("干涉");
}
return checkstatus;
}
public static DispatchWrapper[] ObjectArrayToDispatchWrapper(IEnumerable<object> objects)
{
return objects.Select(o => new DispatchWrapper(o)).ToArray();
}