Files
Set selected object's .p2m appearance file using IRenderMaterial
Code
Module: mMain
'Demonstrates how to add a new appearance file (.p2m) to selected object.
'Preconditions:
'1. Part or assembly is open and object is selected.
'2. APPEARANCE_PATH points to an appearance file.
'Results:
'The appearance is applied to the selected object.
'Notes:
'It is not possible to apply the .p2m only at the assembly level. Use _
IModelDocExtension::DisplayStateSpecMaterialPropertyValues with _
appearance setting values identical to those in the .p2m (if possible) _
to apply appearances at the assembly level. (The aforementioned API _
call cannot apply .p2m files as of SolidWorks 2015.)
'IRenderMaterial::AddEntity can take any of the following objects: _
IComponent2, IModelDoc2, IBody2, IFeature, IFace.
'To remove a .p2m, use IDisplayStateSetting::RemoveAppearance.
'There is no way, at least based on my research, to edit an existing .p2m. _
Rather, simply re-add the new .p2m to that object.
'Written by Keith Rice
'CADSharp LLC
'www.cadsharp.com
Option Explicit
Const APPEARANCE_PATH As String = _
"C:\Program Files\SolidWorks 2014\SolidWorks\data\graphics\materials\color.p2m"
Sub main()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swSelMgr As SldWorks.SelectionMgr
Dim swObj As Object
Dim swRenderMat As SldWorks.RenderMaterial
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swSelMgr = swModel.SelectionManager
Set swObj = swSelMgr.GetSelectedObject6(1, -1)
If swModel.GetType = swDocPART Then
If swObj Is Nothing Then Set swObj = swModel
ElseIf swModel.GetType = swDocASSEMBLY Then
Dim swAssy As SldWorks.AssemblyDoc
Dim swComp As SldWorks.Component2
Dim lngInfo As Long
Set swAssy = swModel
If TypeOf swObj Is SldWorks.Face2 Or _
TypeOf swObj Is SldWorks.Feature Or _
TypeOf swObj Is SldWorks.Body2 Then
Set swComp = swSelMgr.GetSelectedObjectsComponent3(1, -1)
swComp.Select4 False, Nothing, False
swAssy.EditPart2 False, True, lngInfo
If lngInfo = -1 Then
swApp.SendMsgToUser "Failed to edit component."
Exit Sub
End If
End If
Else
Exit Sub
End If
Set swRenderMat = swModel.Extension.CreateRenderMaterial(APPEARANCE_PATH)
swRenderMat.PrimaryColor
If swRenderMat.AddEntity(swObj) = False Then
swApp.SendMsgToUser "Failed to add entity."
Exit Sub
End If
If swModel.Extension.AddDisplayStateSpecificRenderMaterial( _
swRenderMat, swAllDisplayState, Empty, Empty, Empty) = False Then
swApp.SendMsgToUser "Failed to add appearance."
Exit Sub
End If
swModel.EditRebuild3
If Not swComp Is Nothing Then
swComp.Select4 False, Nothing, False
swAssy.EditAssembly
End If
End Sub