solidworks2006 api 2 - ocw.snu.ac.krocw.snu.ac.kr/sites/default/files/note/4847.pdf · automation...
TRANSCRIPT
SolidWorks 2006 API 2
Human Centered CAD Laboratory
2009-04-211
Automation Tool for Parts This macro is designed to explore the various API calls
associated with creating parts. It automates user preferences, sketch commands, placement of dimensions, contour selection and feature definitions.
The macro has one form containing a multi-page tab control. Each tab allows the user to choose which option to set: Material (aluminum or brass) Profile (rectangular or circular) Machine operation (extrusion, extrusion with contour selection, or revolution).
2
Automation Tool for Parts – cont’ Edit macro
Open the macro PartAutomation.swp.
3
Automation Tool for Parts Add constants file
Import swconst.bas to the macro \SolidWorks\Samples\appComm\swconst.bas
If you have already swConst, you don’t need to import constants file
4
Automation Tool for Parts3. Store values to database and set units.
Double-click the command button Build Part and enter the following lines of code:
We call ModelDoc2::SetAddToDB to add sketch entities while avoiding grid and entity snapping.
5
Private Sub cmdBuild_Click()Set swApp = Application.SldWorksSet swModel = swApp.NewPartswModel.SetAddToDB TrueswModel.SetUserPreferenceIntegerValue swUnitsLinear, swMM'MATERIAL 'PROFILE 'MACHINE OPERATIONswModel.SetAddToDB False
End Sub
!! See the SolidWorks API Help !!
ModelDoc2::SetAddToDBThis method will allow you to set whether sketch entities are added directly to the SolidWorks database.
Automation Tool for Parts SolidWorks API Help Topics
6
Automation Tool for Parts Setting Material
For the first tab, call ModelDoc2::SetUserPreferenceDoubleValue to set the material density and crosshatch pattern.
7
Automation Tool for Parts4. Add code to set material.
8
Private Sub cmdBuild_Click()Set swApp = Application.SldWorksSet swModel = swApp.NewPartswModel.SetAddToDB TrueswModel.SetUserPreferenceIntegerValue swUnitsLinear, swMM'MATERIALIf optAl.Value = True Then
swModel.SetUserPreferenceDoubleValue swMaterialPropertyDensity, 2700swModel.SetUserPreferenceStringValue _swMaterialPropertyCrosshatchPattern, "ISO (Aluminum)"
ElseswModel.SetUserPreferenceDoubleValue swMaterialPropertyDensity, 8300swModel.SetUserPreferenceStringValue _swMaterialPropertyCrosshatchPattern, "ISO (Bronze Brass)"
End If'PROFILE'MACHINE OPERATIONswModel.SetAddToDB False
End Sub
Automation Tool for Parts Creating the Sketch Rectangle
For the second tab, call ModelDoc2::SketchRectangle to create the first profile, ModelDoc2::SketchOffset2 to offset the profile and ModelDoc2::CreateLine2().ConstructionGeometry to create the axis.
In order to avoid problems with a sketch overlapping the revolution axis, a value of 50 cm(0.05) has been added throughout the code.
9
Automation Tool for Parts5. Add code to sketch rectangle.
10
swModel.InsertSketch2 False'PROFILEIf optRectangular.Value = True Then
Dim Height As DoubleDim Width As DoubleHeight = CDbl(txtHeight.text) / 1000Width = CDbl(txtWidth.text) / 1000swModel.SketchRectangle 0.05, 0.05, 0, 0.05 + Width, 0.05 + Height, 0, 1swModel.SketchOffset2 0.002, 0, 1swModel.ViewZoomtofit2
End IfswModel.CreateLine2(0, 0, 0, 0, 0.05, 0).ConstructionGeometry = TrueswModel.ViewZoomtofit2'MACHINE OPERATION
!! See the SolidWorks API Help !!
ModelDoc2::SketchRectangleThis method creates a rectangle.
ModelDoc2::CreateLine2This function will allow you to create a sketch line in the currently active 2D or 3D sketch.
SketchSegment::ConstructionGeometryThis property gets or sets whether this sketch segment is construction geometry, for example, a centerline for a feature revolve operation.
Automation Tool for Parts Creating the Sketch Circle Call ModelDoc2::CreateCircleByRadius2 to create the
second profile.
11
Automation Tool for Parts6. Add code to sketch circle.
Creating the construction line is the same in both cases so there only needs to be one call for that method. As long as the call is placed outside the IF.. Then statement, it will run for either case.
12
'PROFILEIf optRectangular.Value = True Then
Dim Height As DoubleDim Width As DoubleHeight = CDbl(txtHeight.text) / 1000Width = CDbl(txtWidth.text) / 1000swModel.SketchRectangle 0.05, 0.05, 0, 0.05 + Width, 0.05 + Height, 0, 1swModel.SketchOffset2 0.002, 0, 1swModel.ViewZoomtofit2
ElseDim Radius As Double Radius = CDbl(txtRadius.text) / 1000swModel.CreateCircleByRadius2 0.05 + Radius, 0.05 + Radius, 0, RadiusswModel.SketchOffset2 0.002, 0, 1swModel.ViewZoomtofit2
End IfswModel.CreateLine2(0, 0, 0, 0, 0.05, 0).ConstructionGeometry = TrueswModel.ViewZoomtofit2
Automation Tool for Parts Creating Extruded Features
Call FeatureManager::FeatureExtrusion to create the extrude feature.
7. Add code to create extruded feature.
13
'MACHINE OPERATIONDim swFeatMgr As SldWorks.FeatureManagerIf optExtrude.Value = True Then
Dim Depth As DoubleDepth = CDbl(txtDepth.text) / 1000Set swFeatMgr = swModel.FeatureManagerswFeatMgr.FeatureExtrusion True, False, True, 0, 0, Depth, 0, False, False, False, False, 0, 0, 0, _0, 0, 0, False, False, FalseswModel.ViewZoomtofit2
End If
Automation Tool for Parts Enabling Contour Selection in the Extrusion Call the SelectionManager::EnableContourSelection to
create the revolve feature.
14
Automation Tool for Parts8. Add code to enable contour selection.
15
'MACHINE OPERATIONDim swFeatMgr As SldWorks.FeatureManager
(…omitted…)Set swFeatMgr = swModel.FeatureManagerIf optRectangular.Value = True Then
If chkContour1.Value = True ThenswModel.SelectionManager.EnableContourSelection = 1swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", 0.055, 0.05, 0, True, 4, Nothing, swSelectOptionDefault
End IfIf chkContour2.Value = True Then
swModel.SelectionManager.EnableContourSelection = 1'swModel.Extension.SelectByID "", "SKETCHCONTOUR", 0.05 - 0.002, 0.05, 0, True, 4, NothingswModel.Extension.SelectByID2 "", "SKETCHCONTOUR", 0.05 - 0.002, 0.05, 0, True, 4, Nothing, swSelectOptionDefault
End IfElse
If chkContour1.Value = True ThenswModel.SelectionManager.EnableContourSelection = 1swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", 0.05 + Radius, 0.05, 0, True, 4, Nothing, swSelectOptionDefault
End IfIf chkContour2.Value = True Then
swModel.SelectionManager.EnableContourSelection = 1swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", 0.05 + Radius, 0.05 - 0.002, 0, True, 4, Nothing, swSelectOptionDefault
End IfEnd IfswFeatMgr.FeatureExtrusion True, False, True, 0, 0, Depth, 0, False, False, False, False, 0, 0, 0, 0, 0, 0, False, False, FalseswModel.SelectionManager.EnableContourSelection = 0swModel.ViewZoomtofit2
End If
Automation Tool for Parts Function Specification
16
!! See the SolidWorks API Help !!
SelectionMgr::EnableContourSelectionDescriptionThis method enables and disables contour selection.Syntax (OLE Automation)valueOut = SelectionMgr.EnableContourSelection (VB Get property)SelectionMgr.EnableContourSelection = valueIn (VB Set property)Property: (VARIANT_BOOL) valueIn : TRUE to enable contour selection, FALSE to disable it
ModelDocExtension::SelectByID2DescriptionThis method selects the specified entity.Syntax (OLE Automation)retval = ModelDocExtension.SelectByID2 ( Name, Type, X, Y, Z, Append, Mark, Callout, SelectOption )
Automation Tool for Parts Creating Revolved Features
Call FeatureManager::FeatureRevolve to create the revolve feature.
9. Add code to create revolved feature.
17
'MACHINE OPERATIONIf optExtrude.Value = True Then
(…omitted…)swModel.SelectionManager.EnableContourSelection = 0swModel.viewzoomtofit2
ElseDim Angle As DoubleAngle = CDbl(txtAngle.text * 3.14 / 180)Set swFeatMgr = swModel.FeatureManagerswFeatMgr.FeatureRevolve Angle, True, 0, 0, 0, True, False, True
End If
Automation Tool for Parts10. Save and run macro.
Test the various options and combinations. Does the tool perform correctly? Use breakpoint to debug potential problem in the codes.
Return to VBA when finished.
18
Automation Tool for Parts Adding Dimensions
Call ModelDoc2::AddDimension2, AddVerticalDimenion2 and AddHorizontalDimension2 to dimension sketch entities. A dimension is only added if an entity is selected. In this next section we will create the rectangle line by line, allowing us to dimension the sketch without involving selections.
19
Automation Tool for Parts11. Modify code to sketch rectangle line by line.
20
'PROFILEIf optRectangular.Value = True Then
(…omitted…)Height = CDbl(txtHeight.text) / 1000Width = CDbl(txtWidth.text) / 1000 'swModel.SketchRectangle 0.05, 0.05, 0, 0.05 + Width, 0.05 + Height, 0, 1swApp.SetUserPreferenceToggle swInputDimValOnCreate, FalseswModel.CreateLine2 0.05, 0.05, 0, 0.05, 0.05 + Height, 0swModel.AddDimension2 0, 0.05 + Height / 2, 0swModel.CreateLine2 0.05, 0.05 + Height, 0, 0.05 + Width, 0.05 + Height, 0swModel.CreateLine2 0.05 + Width, 0.05 + Height, 0, 0.05 + Width, 0.05, 0swModel.CreateLine2 0.05 + Width, 0.05, 0, 0.05, 0.05, 0swModel.AddDimension2 0.05 + Width / 2, 0, 0swModel.ClearSelectionswModel.Extension.SelectByID2 "", "EXTSKETCHPOINT", 0, 0, 0, False, 0, Nothing, swSelectOptionDefaultswModel.AndSelectByID "", "SKETCHPOINT", 0.05, 0.05, 0swModel.AddVerticalDimension2 0, 0.025, 0swModel.ClearSelectionswModel.Extension.SelectByID2 "", "EXTSKETCHPOINT", 0, 0, 0, False, 0, Nothing, swSelectOptionDefaultswModel.AndSelectByID "", "SKETCHPOINT", 0.05, 0.05, 0swModel.AddHorizontalDimension2 0.025, 0, 0swModel.ClearSelectionswModel.Extension.SelectByID2 "Line1", "SKETCHSEGMENT", 0, 0, 0, False, 0, Nothing, swSelectOptionDefaultswModel.AndSelectByID "Line2", "SKETCHSEGMENT", 0, 0, 0swModel.AndSelectByID "Line3", "SKETCHSEGMENT", 0, 0, 0swModel.AndSelectByID "Line4", "SKETCHSEGMENT", 0, 0, 0swModel.SketchOffset2 0.002, 0, 1swModel.ViewZoomtofit2
Else
Additional Commands
21
Additional Commands
22
Additional Commands
23
Additional Commands
24
Preselection This macro
demonstrates how to access and modify the data specific to certain features in a part or assembly file.
It requires that the user selects the Extrude1 feature before executing the macro..
25
Preselection1. Open existing part and macro. Open the part Preselection.sldprt and the macro Preselection.swp.
2. Add constants file. Import swconst.bas to the macro if need.
3. Connect to SldWorks and ModelDoc2.
26
Private Sub cmdGenerate_Click()Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2
‘Add code hereSet swApp = Application.SldWorksSet swModel = swApp.ActiveDoc
End Sub
Preselection Accessing the Selection Manager In order to handle selected objects made in the
SolidWorks user interface, use the SelectionManager object. It exposes methods that help the user determine what objects are currently selected and provides access to them. To make any selected object available to the user, first call ModelDoc2::SelectionManager.
27
ModelDoc2::Selection ManagerSelectionManager = ModelDoc2.SelectionManager
Output: SelectionManager Pointer a dispatch object, the Selection Manager for this document.
Preselection Counting Selected Objects To determine if the user has a made a valid selection or to
get the number of selected objects, call SelectionMgr::GetSelectedObjectCount.
28
SelectionMgr::GetSelectedObjectCountretval = SelectionMgr.Getselectedobjectcount( )
Return: retval Number of currently selected objects.
Preselection4. Connect to SelectionManager and count selected
objects.
29
Private Sub cmdGenerate_Click()Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swSelMgr As SldWorks.SelectionMgrDim count As Long
‘Add code hereSet swApp = Application.SldWorksSet swModel = swApp.ActiveDocSet swSelMgr = swModel.SelectionManagercount = swSelMgr.GetSelectedObjectCountIf count > 1 Then
swApp.SendMsgToUser2 "Please select only Extrude1.", swMbWarning, swMbOkMe.HideExit Sub
End IfEnd Sub
Preselection Getting Selected Objects To get an interface to the currently selected object, call
SelectionMgr::GetSelectedObject6.
Getting Selected Object Types To determine the object type selected, call
SelectionMgr::GetSelectedObjectType3. 30
SelectionMgr::GetSelectedObject6retval = SelectionMgr.GetSelectedObject6 (Atindex, Mark)
Return: Retval Pointer a dispatch object.
Input: Atindex Index position within the current list of selected items where Atindex ranges:From 1 To selectionMgr::GetSelectObjectCount
Mark -1 = All selections regardless of marks0 = only the selections without marksAny other value = Value that was used to mark and select an object
Preselection
Getting Feature Type Names To verify that a specific feature is selected, call
Feature::GetTypeName.
31
SelectionMgr::GetSelectedObjectType3retval = SelectionMgr.GetSelectedobjectType3 (Atindex, Mark)Note: If the object returned is a feature, use Feature::GetTypeName for determining the feature type.
Return: retval Object type. See API Help file for full list.
Input: Atindex Index position within the current list of selected items where Atindexranges:From 1 To selectionMgr::GetSelectObjectCount
Mark -1 = All selections regardless of marks0 = only the selections without marksAny other value = Value that was used to mark and select an object
Feature::GetTypeNameretval = Feature.GetTypeName ( )
Return: retval Feature type. See API Help file for full list.
Preselection5. Determine the selected feature type.
32
Private Sub cmdGenerate_Click()Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swSelMgr As SldWorks.SelectionMgrDim count As LongDim Feature As Object
'Add code hereSet swApp = Application.SldWorksSet swModel = swApp.ActiveDocSet swSelMgr = swModel.SelectionManagercount = swSelMgr.GetSelectedObjectCountIf count > 1 Then
swApp.SendMsgToUser2 "Please select only Extrude1.", swMbWarning, swMbOkMe.HideExit Sub
End IfSet Feature = swSelMgr.GetSelectedObject3(count)If Not Feature.GetTypeName = swTnExtrusion Then
swApp.SendMsgToUser2 "Please select the Extrude1.", swMbWarning, swMbOkExit Sub
End IfEnd Sub
Preselection Accessing the Object Definition To access the parameters that control the definition of the
feature, call Feature::GetDefinition.
Accessing Selections For extrusions, call
ExtrudeFeatureData2::AccessSelections to put the model into a rollback state and to allow access to the selections that define the extrude feature.
33
Feature::GetDefinitionretval = Feature.GetDefintion( )
Return: retval Dispatch pointer to the feature definition object. SeeAPI Help file for full list of feature objects.
Preselection
Releasing Selections When using AccessSelections, you must also make a
corresponding call to ExtrudeFeatureData2::ReleaseSelectionAccess to restore the rollback state for cases when a feature is not modified.
34
ExtrudeFeatureData2::AccessSelectionsaccessGained = ExtrudeFeatureData2.AccessSelections (Topdoc, component)
Return: accessGained TRUE if the selections were accessed successfully, FALSE if not.
Input: TopDoc Top-level document.
Input: component Component in which the feature is to be modified.
ExtrudeFeatureData2::ReleaseSelectionAccessvoid ExtrudeFeatureData2.ReleaseSelectionAccess()
Return: void No return value.
Preselection6. Get feature definition, access extrude feature data and release.
35
Private Sub cmdGenerate_Click()Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swSelMgr As SldWorks.SelectionMgrDim count As LongDim Feature As ObjectDim swComponent As SldWorks.Component2Dim retval As BooleanDim ExtrudeFeatureData As Object
‘Add code hereSet swApp = Application.SldWorks
(…omitted…)
If Not Feature.GetTypeName = swTnExtrusion ThenswApp.SendMsgToUser2 "Please select the Extrude1.", swMbWarning, swMbOkExit Sub
End IfSet ExtrudeFeatureData = Feature.GetDefinitionretval = ExtrudeFeatureData.AccessSelections(swModel, swComponent)If Not retval Then
swApp.SendMsgToUser2 "Unable to modify feature data.", swMbWarning, swMbOkExtrudeFeatureData.ReleaseSelectionAccess
End IfEnd Sub
Preselection Making Specific Changes
One of the modifications allowed for an extrude is setting the depth. First call ExtrudeFeatureData2::GetDepth to retrieve the existing depth value and then call ExtrudeFeatureData2::SetDepth to set a new value.
Modify the Object Definition Finally, call Feature::ModifyDefinition to implement changes.
36
Feature:: ModifyDefinitionretval = Feature.ModifyDefinition(Definition, TopDoc, Component)
Return: retval TRUE if the feature is updated successfully, FALSE if not.
Input: Definition Dispatch pointer to the feature definition object.
Input: TopDoc Top-level document.
Input: Component Component for the feature.
Preselection7. Modify extrude depth.
37
Private Sub cmdGenerate_Click()Dim swApp As SldWorks.SldWorks
(…omitted…)
Dim retval As BooleanDim ExtrudeFeatureData As ObjectDim Depth As DoubleDim Factor As Integer
‘Add code hereFactor = CInt(txtDepth.Text)Set swApp = Application.SldWorks
(…omitted…)
Set ExtrudeFeatureData = Feature.GetDefinitionretval = ExtrudeFeatureData.AccessSelections(swModel, swComponent)Depth = ExtrudeFeatureData.GetDepth(True)ExtrudeFeatureData.SetDepth True, Depth * Factorretval = Feature.ModifyDefinition(ExtrudeFeatureData, swModel, swComponent)If Not retval Then
swApp.SendMsgToUser2 "Unable to modify feature data.", swMbWarning, swMbOkExtrudeFeatureData.ReleaseSelectionAccess
End IfEnd Sub
Preselection8. Save and run macro Return to VBA when finished.
38