如何通过SolidWorks API判断工程图视图或草图对象是否为空
SolidWorks API 空对象判断实现方案
官方文档确实没有直接给出这两类空对象的判定属性,实际开发中可以通过遍历对象关联的特征、实体、注解集合来做判定,覆盖所有非空场景即可,具体逻辑如下:
判定工程图视图(Drawing View)是否为空
没有单一属性可以直接返回视图空状态,按优先级依次做以下检查,任意一项满足即可判定为非空:
- 调用
GetAnnotations()方法获取视图挂载的所有注解对象,返回数组长度大于0则非空,注解包含尺寸、注释、符号、表格等所有依附于视图的标注内容 - 调用
GetVisibleEntities(swViewEntityType_e.swViewEntityType_All)获取视图内所有可见实体,返回数组长度大于0则非空,可覆盖模型投影、配置显示的实体内容 - 调用
ReferencedDocument获取视图关联的参考文档,如果返回值不为空,再调用GetRootDrawingComponent()获取视图根组件,只要根组件下存在有效子组件,哪怕实体被临时隐藏也不属于空视图 - 针对手动创建的空白视图,额外获取视图绑定的草图对象,按空草图逻辑做校验,草图非空则视图非空
对应可直接复用的VBA/VB.NET代码片段:
Function IsEmptyDrawingView(swView As SldWorks.View) As Boolean IsEmptyDrawingView = True ' 检查注解 Dim annos As Object = swView.GetAnnotations() If Not IsNothing(annos) AndAlso UBound(annos) >= 0 Then IsEmptyDrawingView = False Exit Function End If ' 检查可见实体 Dim visEnts As Object = swView.GetVisibleEntities(swViewEntityType_e.swViewEntityType_All) If Not IsNothing(visEnts) AndAlso UBound(visEnts) >= 0 Then IsEmptyDrawingView = False Exit Function End If ' 检查关联模型与组件 Dim refDoc As ModelDoc2 = swView.ReferencedDocument If Not IsNothing(refDoc) Then Dim rootComp As DrawingComponent = swView.GetRootDrawingComponent() If Not IsNothing(rootComp) Then Dim children As Object = rootComp.GetChildren() If Not IsNothing(children) AndAlso UBound(children) >= 0 Then IsEmptyDrawingView = False Exit Function End If End If End If ' 检查空白视图绑定草图 Dim bindSketch As Sketch = swView.GetSketch() If Not IsNothing(bindSketch) Then If Not IsEmptySketch(bindSketch) Then IsEmptyDrawingView = False Exit Function End If End If End Function
判定草图(Sketch)是否为空
注意不要把草图默认自带的原点判定为有效内容,按以下逻辑检查即可:
- 调用
GetSketchSegments()获取所有草图段(直线、圆弧、样条、矩形等所有草绘几何),返回数组长度大于0则非空 - 调用
GetSketchPoints2()获取所有草绘点,遍历点集合只要存在非原点的点,即判定为非空 - 调用
GetConstraints()获取所有草图约束(几何约束、尺寸约束都包含在内),返回数组长度大于0则非空,可覆盖只加了悬空约束没画几何的特殊场景 - 调用
GetExternalReferences()获取所有外部参考引用,返回数组长度大于0则非空,可覆盖草图和外部几何建立了关联但没有本地几何的场景
对应可直接复用的代码片段:
Function IsEmptySketch(swSketch As SldWorks.Sketch) As Boolean IsEmptySketch = True ' 检查草图几何段 Dim segs As Object = swSketch.GetSketchSegments() If Not IsNothing(segs) AndAlso UBound(segs) >= 0 Then IsEmptySketch = False Exit Function End If ' 检查草绘点,排除默认原点 Dim pts As Object = swSketch.GetSketchPoints2() If Not IsNothing(pts) Then Dim pt As SketchPoint For Each pt In pts If Not pt.IsOrigin Then IsEmptySketch = False Exit Function End If Next End If ' 检查草图约束 Dim constraints As Object = swSketch.GetConstraints() If Not IsNothing(constraints) AndAlso UBound(constraints) >= 0 Then IsEmptySketch = False Exit Function End If ' 检查外部参考 Dim extRefs As Object = swSketch.GetExternalReferences() If Not IsNothing(extRefs) AndAlso UBound(extRefs) >= 0 Then IsEmptySketch = False Exit Function End If End Function
注意:SolidWorks 2018及更早版本的
GetVisibleEntities方法参数签名有差异,使用时需要匹配你当前引用的SolidWorks Interop 程序集版本做调整。不要通过视图名称、视图类型这类可被用户手动修改的属性做空判断,容错率极低。
内容的提问来源于stack exchange,提问作者Nirantar Vidyarthee
相关产品推荐
相关产品推荐

