Get Mass Properties Using IMassProperty (VB.NET)
This example shows how to get the mass of a selected assembly component.
'---------------------------------------------
' Preconditions:
' 1. Specified assembly document exists.
' 2. Open the Immediate window.
' 3. Run the macro.
'
' Postconditions: Mass of the selected component printed to
' Immediate window.
'----------------------------------------------
Imports
SolidWorks.Interop.sldworks
Imports
SolidWorks.Interop.swconst
Imports
System.Runtime.InteropServices
Imports System
Imports System.Diagnostics
Partial
Class SolidWorksMacro
Public
Sub main()
Dim swModelDoc2
As ModelDoc2
Dim swComponent
As Component2
Dim bodyInfo
As
Object = Nothing
Dim
bodies As
Object
Dim
val As
Double
Dim
params As
Object
Dim
swMass As MassProperty
Dim boolstatus
As
Boolean
Dim
errors As
Integer
Dim
warnings As
Integer
swModelDoc2 = swApp.OpenDoc6("C:\program
files\solidworks corp\solidworks\samples\tutorial\edraw\claw\claw-mechanism.sldasm",
swDocumentTypes_e.swDocASSEMBLY, swOpenDocOptions_e.swOpenDocOptions_Silent,
"", errors, warnings)
boolstatus = swModelDoc2.Extension.SelectByID2("collar-1@claw-mechanism",
"COMPONENT", 0, 0, 0,
False, 0,
Nothing,
swSelectOption_e.swSelectOptionDefault)
swComponent = swModelDoc2.SelectionManager.GetSelectedObject6(1,
0)
bodies = swComponent.GetBodies3(swBodyType_e.swAllBodies,
bodyInfo)
swMass = swModelDoc2.Extension.CreateMassProperty
' Convert .NET objects to IDispatch by using
DispatchWrapper
' for call to
IMassProperty::AddBodies, whose input objects
' must be
marshaled to Dispatch object arrays
bodyArray =
ObjectArrayToDispatchWrapperArray(bodies)
boolstatus = swMass.AddBodies((bodyArray))
swMass.UseSystemUnits = False
val = swMass.Mass
Debug.Print(" Mass - "
& val)
val = swMass.Volume
Debug.Print(" Volume - "
& val)
val = swMass.Density
Debug.Print(" Density - "
& val)
val = swMass.SurfaceArea
Debug.Print(" Surface area - "
& val)
params = swMass.CenterOfMass
Debug.Print(" Center of mass - X: "
& params(0) & " ,Y: " &
params(1) & " ,and Z: "
& params(2))
End
Sub
Public
Function
ObjectArrayToDispatchWrapperArray(ByVal
SwObjects As
Object())
As DispatchWrapper()
Dim arraySize
As
Integer
arraySize = SwObjects.GetUpperBound(0)
Dim dispwrap
As DispatchWrapper() =
New DispatchWrapper(arraySize) {}
Dim arrayIndex
As
Integer
For
arrayIndex = 0 To arraySize
dispwrap(arrayIndex) = New
DispatchWrapper(SwObjects(arrayIndex))
Next
Return
dispwrap
End
Function
'''
<summary>
''' The SldWorks swApp
variable is pre-assigned for you.
'''
</summary>
Public
swApp As SldWorks
Public bodyArray
As DispatchWrapper()
End
Class