Inventor 重心标记

官方帮助文档有一个用工作点来标记中心的代码,不过那个代码貌似只对零件模型有效。下面是一个增加了装配体文件有效的代码。

这个版本需求:

  • 自动检测并更新现有重心点位置
  • 不存在时创建新的固定工作点
  • 保持工程图引用不变
  • 适用于零件和装配体文档
  • 有完善的错误处理
Private Sub ToolStripButton7_Click(sender As Object, e As EventArgs) Handles ToolStripButton7.Click
    Try
        ' 验证Inventor应用程序和文档状态
        If g_inventorApplication Is Nothing OrElse g_inventorApplication.Documents.Count = 0 Then
            MsgBox("请打开零件或装配体文档")
            Return
        End If

        ' 获取活动文档并验证类型
        Dim oDoc As Document = g_inventorApplication.ActiveDocument
        
        If oDoc.DocumentType <> DocumentTypeEnum.kAssemblyDocumentObject AndAlso 
           oDoc.DocumentType <> DocumentTypeEnum.kPartDocumentObject Then
            MsgBox("请打开具备质量的装配体或者零件图。")
            Return
        End If

        ' 获取当前重心位置
        Dim oCenterOfMass As Inventor.Point = oDoc.ComponentDefinition.MassProperties.CenterOfMass

        ' 查找现有重心点
        Dim oWorkPoint As WorkPoint = Nothing
        Dim workPointExists As Boolean = False
        
        Try
            ' 尝试通过名称获取工作点
            oWorkPoint = oDoc.ComponentDefinition.WorkPoints.Item("重心点")
            workPointExists = True
        Catch
            workPointExists = False
        End Try

        If workPointExists Then
            ' 根据文档类型更新工作点位置
            If oDoc.DocumentType = DocumentTypeEnum.kAssemblyDocumentObject Then
                Dim oAssemblyDef As AssemblyWorkPointDef = oWorkPoint.Definition
                oAssemblyDef.Point = oCenterOfMass
            Else
                Dim oFixedDef As FixedWorkPointDef = oWorkPoint.Definition
                oFixedDef.Point = oCenterOfMass
            End If
        Else
            ' 创建新的固定工作点
            oWorkPoint = oDoc.ComponentDefinition.WorkPoints.AddFixed(oCenterOfMass)
            oWorkPoint.Name = "重心点"
            oWorkPoint.Visible = True ' 确保工作点可见
        End If

        ' 更新文档
        oDoc.Update()
        
    Catch ex As Exception
        MsgBox("更新重心点时出错: " & ex.Message)
    End Try
End Sub

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注