Beruflich Dokumente
Kultur Dokumente
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
SolidWorks 2006
Do
API Fundamentals
SolidWorks Corporation
300 Baker Avenue
Concord, Massachusetts 01742
COMMERCIAL COMPUTER
SOFTWARE - PROPRIETARY
U.S. Government Restricted Rights. Use,
duplication, or disclosure by the government is
subject to restrictions as set forth in FAR 52.227-19
(Commercial Computer Software - Restricted
Rights), DFARS 227.7202 (Commercial Computer
Software and Commercial Computer Software
Documentation), and in the license agreement, as
applicable.
Contractor/Manufacturer:
SolidWorks Corporation, 300 Baker Avenue,
Concord, Massachusetts 01742 USA
Portions of this software 1988, 2000 Aladdin
Enterprises.
Portions of this software 1996, 2001 Artifex
Software, Inc.
Portions of this software 2001 artofcode LLC.
Portions of this software 2005 Bluebeam
Software, Inc.
Portions of this software 1999, 2002-2005
ComponentOne
Portions of this software 1990-2005 D-Cubed
Limited.
Portions of this product are distributed under license
from DC Micro Development, Copyright 19942002 DC Micro Development, Inc. All rights
reserved
Portions eHelp Corporation. All rights reserved.
Portions of this software 1998-2005 Geometric
Software Solutions Co. Limited.
Portions of this software 1986-2005 mental
images GmbH & Co. KG
Portions of this software 1996 Microsoft
Corporation. All Rights Reserved.
Portions of this software 2005 Priware Limited
Portions of this software 2001, SIMULOG.
Portions of this software 1995-2005 Spatial
Corporation.
Portions of this software 2003-2005, Structural
Research & Analysis Corp.
Portions of this software 1997-2005 Tech Soft
America.
Portions of this software are copyrighted by and are
the property of UGS Corp. 2005.
Portions of this software 1999-2005 Viewpoint
Corporation.
Portions of this software 1994-2005, Visual
Kinematics, Inc.
This software is based in part on the work of the
Independent JPEG group.
All Rights Reserved
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
API Fundamentals
Table of Contents
Do
Introduction
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Lesson 1:
Using the Macro Recorder
Macro Recording . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Macro Toolbar. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Understanding How Macro Code Works . . . . . . . . . . . . . . . . . . . . . . 20
Variable Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Entry Point Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
SolidWorks Application Object . . . . . . . . . . . . . . . . . . . . . . . . . . 20
SolidWorks Document Object . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
SolidWorks API Calls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Procedure End. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Understanding How to Call Members on API Interfaces . . . . . . . . . . 21
Passing Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Cleaning Up Code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Commenting Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Debugging Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Adding Forms to a Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Exercise 1: Recording a Macro. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Exercise 2: Adding Macro Code to a VBA Button Control . . . . . . . . 37
Exercise 3: Adding User Input Fields on a VBA Form . . . . . . . . . . . 40
Lesson 2:
The API Object Model
SolidWorks API Object Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Visual Basic Automatic Type Casting . . . . . . . . . . . . . . . . . . . . . 46
Application Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
SldWorks Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
SolidWorks 2006 Type Library . . . . . . . . . . . . . . . . . . . . . . . . . . 48
IntelliSense . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Early vs. Late Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Case Study: Connecting to New Documents . . . . . . . . . . . . . . . . . . . 51
Macro Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
ModelDoc2 Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
ModelDoc Extension Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
PartDoc Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
AssemblyDoc Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
DrawingDoc Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Case Study: Connecting to Existing Documents . . . . . . . . . . . . . . . . 69
Exercise 4: Working with New Documents . . . . . . . . . . . . . . . . . . . . 77
Exercise 5: Working with Existing Documents . . . . . . . . . . . . . . . . . 79
ii
API Fundamentals
Lesson 3:
Setting System Options and Document Properties
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
Lesson 4:
Automating Part Design
Case Study: Automation Tool for Parts . . . . . . . . . . . . . . . . . . . . . . 129
Setting Material. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Creating the Sketch Rectangle . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Adding Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Selection on Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Creating the Sketch Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Creating Extruded Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Enabling Contour Selection for the Extrusion . . . . . . . . . . . . . . 134
Creating Revolved Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Standard Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
View Commands. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Sketch Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Sketch Tools Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Features Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Sketch Relations Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Reference Geometry Commands . . . . . . . . . . . . . . . . . . . . . . . . 139
Exercise 8: Automating the Part Creation Process . . . . . . . . . . . . . . 141
Lesson 5:
Assembly Automation
Case Study: Automation Tool for Assemblies . . . . . . . . . . . . . . . . . 145
Transforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Creating MathTransforms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
The Transformation Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Activating Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Invisible Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Object Collections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Establishing the Curve and Edge Collections. . . . . . . . . . . . . . . 150
iii
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Lesson 6:
Drawing Automation
Do
Lesson 7:
Selection and Traversal Techniques
Case Study: Programming With a Selected Object . . . . . . . . . . . . . 179
SelectionManager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Accessing the Selection Manager . . . . . . . . . . . . . . . . . . . . . . . . 180
Counting Selected Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Accessing Selected Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Getting Selected Object Types . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Getting Feature Type Names . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Feature Data Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Accessing the Feature Data Object . . . . . . . . . . . . . . . . . . . . . . . 182
Accessing Selections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Releasing Selections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
Modifying Feature Data Properties. . . . . . . . . . . . . . . . . . . . . . . 183
Modify the Object Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
The SolidWorks BREP Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Traversing Topology and Geometry. . . . . . . . . . . . . . . . . . . . . . 186
Case Study: Body and Face Traversal . . . . . . . . . . . . . . . . . . . . . . . 187
Returning a List of Body Pointers . . . . . . . . . . . . . . . . . . . . . . . 188
Face Material Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
iv
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
Lesson 8:
Adding Custom Properties and Attributes
Case Study: Custom Properties. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
Adding Custom Properties to a SolidWorks Document . . . . . . . 208
Setting and Getting Custom Property Values . . . . . . . . . . . . . . . 209
Getting Custom Property Names . . . . . . . . . . . . . . . . . . . . . . . . 210
Getting the Custom Property Count . . . . . . . . . . . . . . . . . . . . . . 210
Case Study: Configurations With Custom Properties. . . . . . . . . . . . 211
Returning Mass Properties From a SolidWorks Model . . . . . . . 213
Using the API to Return the Mass Properties . . . . . . . . . . . . . . . 213
Case Study: File Summary Information . . . . . . . . . . . . . . . . . . . . . . 216
Adding Summary Information . . . . . . . . . . . . . . . . . . . . . . . . . . 216
Case Study: Document Attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . 217
Naming Attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
The Attribute Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
AttributeDef Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
Attribute Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Parameter Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Case Study: Face Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
Finding the Cylindrical Faces and Attaching Attributes . . . . . . 223
Displaying Callouts in the Model View . . . . . . . . . . . . . . . . . . . 225
Callout Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
Creating the CNC Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
Types of Attribute Traversal. . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
A Final Word about Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . 229
Exercise 14: Adding Mass Properties as Custom Properties . . . . . . 231
Exercise 15: Adding Attributes to Edges . . . . . . . . . . . . . . . . . . . . . 233
Lesson 9:
The SolidWorks API SDK
The API SDK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
Installing the SDK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
Case Study: Creating a VB.NET Add-In.. . . . . . . . . . . . . . . . . . . . . 244
References. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
Comparing Addin DLLs and Stand-Alone Executables. . . . . . . 249
Loading and Running an Add-in Application. . . . . . . . . . . . . . . 250
Case Study: Creating a C# Add-in . . . . . . . . . . . . . . . . . . . . . . . . . . 252
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Lesson 10:
Customizing the SolidWorks User Interface
Case Study: Customizing the UI With VB.NET. . . . . . . . . . . . . . . . 267
Debugging the DLL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
Debugger Keyboard Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . 271
Understanding The Add-in Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
Importing Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
The Add-in Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
Understanding the GUID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
Connecting to Solidworks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
Bidirectional Communication. . . . . . . . . . . . . . . . . . . . . . . . . . . 276
Setting Callback Information . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
Custom Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
Custom Menu Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Creating and Adding Custom Toolbars to an Add-in . . . . . . . . . 281
Creating the Toolbar Bitmaps. . . . . . . . . . . . . . . . . . . . . . . . . . . 282
Adding Toolbar Bitmaps to a VB.NET Solution . . . . . . . . . . . . 283
The Bitmap Handler Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
Adding Toolbars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
Adding Toolbar Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
Property Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
PropertyPage Members. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
Add-In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
SldWorks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
UserPMPage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
SldWorks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
Add-In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
ppage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
handler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
PropertyManager Page2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
PropertyManager Page2Handler2. . . . . . . . . . . . . . . . . . . . . . . . 290
Creating a PropertyManager Page . . . . . . . . . . . . . . . . . . . . . . . 291
Property Page Groups and Controls . . . . . . . . . . . . . . . . . . . . . . . . . 292
Adding Group Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
Group and control IDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
Adding Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
Adding Picture Labels to Controls . . . . . . . . . . . . . . . . . . . . . . . 297
Removing Menus and Toolbars . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
vi
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Lesson 11:
Notifications
Notifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
Notifications in VBA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
Case Study: Simple Notification. . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
The Class Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
Case Study: Using Notifications in .NET . . . . . . . . . . . . . . . . . . . . . 318
The AddHandler Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
The AddressOf Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
The Event Handler Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
The Document Event Handler Class. . . . . . . . . . . . . . . . . . . . . . 323
Attaching the DocumentEvent Handlers . . . . . . . . . . . . . . . . . . 324
Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
The Derived Event Handler Classes . . . . . . . . . . . . . . . . . . . . . . 328
The DocView Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
Detaching the Document and Model View Event Handlers. . . . 333
Detaching the SolidWorks Event Handlers . . . . . . . . . . . . . . . . 337
Interfaces That Support Notifications. . . . . . . . . . . . . . . . . . . . . 340
Exercise 19: Handling Events Using the Add-in Wizard . . . . . . . . . 347
Solution. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
Do
Appendix
vii
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
API Fundamentals
viii
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
API Fundamentals
Introduction
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Introduction
API Fundamentals
API Fundamentals
Introduction
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
About This
Course
Prerequisites
Laboratory
Exercises
Laboratory exercises give you the opportunity to apply and practice the
material covered during the lecture/demonstration portion of the
course. They are designed to represent typical programming and
automation situations, while being modest enough to be completed
during class time. However, many students work at different paces.
Therefore, we have included more lab exercises than you can
reasonably expect to complete during the course. This ensures that even
the fastest student will not run out of exercises.
Do
Course Design
Philosophy
Windows XP
The screen shots in this manual were created using SolidWorks 2006
running on Windows XP. If you are running on a different version of
Windows, you might notice subtle differences in the appearance of the
menus and windows. These differences do not affect the performance
of the software.
API Fundamentals
Introduction
Conventions Used
in this Book
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Meaning
Typewriter
Lucida Console
17 Do this step
Do
About the CD
The Case Study folder contains the files your instructor uses while
presenting the various lessons. The Exercises folder contains any files
that are required for doing the laboratory exercises. Solutions are
provided throughout each lesson.
API Fundamentals
Introduction
Getting Started
File Types
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Option Explicit
Do
Variables
Getting Started
API Fundamentals
Introduction
Choosing Data
Types
String
Integer -
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Long
Decimal -
Byte
Boolean -
Variant -
Object - holds a 32 bit (4-byte) address that refers to objects. Using the
Set statement, a variable declared as an object can have any object
Do
swApp
swApp
filename
dvarArray(2)
As
As
As
As
Object
SldWorks.SldWorks
String
Double
'Generic object
'Specific object
'Simple string
'Set of 3 doubles
There are additional data types available to the programmer once the
SolidWorks 2006 type library has been referenced (e.g. SldWorks).
API Units
All APIs use meters and radians for length and angle units.
Getting Started
API Fundamentals
Introduction
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
SolidWorks
Constants Type
Library
Do
Note
Getting Started
API Fundamentals
Introduction
Macro
Recording Tips
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Part.ActiveView().RotateAboutCenter
The SolidWorks 2006 API help file is designed for programmers and
end users who want to research information specific to API interfaces,
methods, properties, and events. To open the file in SolidWorks, click
Help, SolidWorks API and Add-In Help Topics.
API Object
Interfaces
Do
SolidWorks 2006
API Help
API Fundamentals
Introduction
The Contents tab of the API help file contains the following sections:
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Contents
SolidWorks 2006 API Release Notes - This part of the help file has
Obsolete APIs - This part of the help file has information on APIs that
Do
Index
Search
API Fundamentals
Introduction
Understanding API
Interface Member
Descriptions
1
2
3
4
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
10
API Fundamentals
Introduction
5. API Call - This section shows the complete syntax for using the
member. void SldWorks.ArrangeWindows (style), is written in VB:
swApp.ArrangeWindows 0
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Void means there is no return value for this call. You do not use
void in Visual Basic source code. It is simply written in the help file
as an indicator - not to return a value.
For other methods, a return value is necessary and the API call section
looks different:
swPart is our retval (short for Return Value). The return value of
SldWorks::NewPart is LPDISPATCH (a pointer to a dispatch object)
which we declare in Visual Basic as simply Object, because it points to
an API interface object (the newly created part document).
Note
In VBA if you are returning data on the left side return value, you will
need to encompass your input parameters in parenthesis. If you are not
returning data, parenthesis are not used. If you want to call a method or
a property directly from a returned object, you will need to use the
parenthesis.
This is shown in the following example.
Do
11
API Fundamentals
Introduction
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Note
The name style is just a descriptive name for the variable, you can name
this variable anything you like. Always try to give your variables
descriptive names.
7. Parameters - Descriptions of possible values for each parameter (if
the API call requires parameters). In this case, put a 0 to cascade, 1
tiles the windows horizontally, and 2 tiles the windows vertically.
8. Syntax (COM) - Devoted to COM programming syntax.
Do
12
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
API Fundamentals
Lesson 1
Using the Macro Recorder
Do
Record your first macro and edit the code using Microsoft Visual
Basic for Applications.
Debug a macro.
Add forms and controls that allow a user to interact with the macro.
13
Lesson 1
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
14
API Fundamentals
Lesson 1
Using the Macro Recorder
Macro Toolbar
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Macro
Recording
By default, the Macro toolbar is turned off. To create and use your
macros, it is best to view and dock the macro toolbar at the top of the
SolidWorks window. From the View menu, select Toolbars, Macro.
launches the Run Macro dialog box, where the user selects the
macro to execute.
Run
launches the Save As macro dialog box, where the user enters
a valid name and extension for the macro. If the save is cancelled, a
prompt appears that allows the user to continue or cancel the recording.
Stop
Record/Pause
launches the Edit Macro dialog box for selecting the macro to
view or modify.
Edit
Do
Custom
Macro Recording
15
Lesson 1
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Click Record
Click Sketch
Click Circle
Do
16
Macro Toolbar
API Fundamentals
Lesson 1
Using the Macro Recorder
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
8
9
Click Stop
11 Click Play
Do
Macro Toolbar
17
Lesson 1
API Fundamentals
Automation Review
Lets take a look at how much weve automated so far with this simple
macro
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Total Clicks: 9
All of the users input and time is eliminated simply by running the
macro.
Do
Note
18
Custom macro buttons can be placed on any toolbar, not just the Macro
toolbar.
Macro Toolbar
API Fundamentals
Lesson 1
Using the Macro Recorder
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Click OK.
Again, before running the macro, it is good practice to delete the boss
and sketch so you can see the new part creation without overlapping
features.
Do
Select Macro1.swp.
Macro Toolbar
19
Lesson 1
API Fundamentals
Understanding
How Macro
Code Works
Variable
Declaration
Option Explicit
'**********************************************************
' Macro1.swb - macro recorded on ##/##/##
'**********************************************************
Dim swApp As Object
Dim Part As Object
Dim SelMgr As Object
Dim boolstatus As Boolean
Dim longstatus As Long, longwarnings As Long
Dim Feature As Object
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
First thing to do is follow the code from top to bottom. Lets examine
our macro code more closely to understand how easy and powerful
macros are:
Entry Point
Procedure
Sub main()
SolidWorks
Application Object
SolidWorks
Document Object
Do
SolidWorks
API Calls
Procedure End
20
API Fundamentals
Lesson 1
Using the Macro Recorder
Understanding
How to Call
Members on
API Interfaces
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
21
Lesson 1
API Fundamentals
Passing
Parameters
FeatureManager::FeatureExtrusion2
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
pFeat = FeatureManager.FeatureExtrusion (sd, flip, dir, t1, t2, d1, d2, dchk1, dchk2,
ddir1, ddir2, dang1, dang2, offsetReverse1, offsetReverse2, translateSurface1,
translateSurface2, merge, useFeatScope, useAutoSelect, t0, startOffset, flipStartOffset )
Output:
pFeat
Input:
sd
TRUE
flip
TRUE
dir
TRUE
t1
Input:
Input:
Input:
swEndCondBlind
swEndCondThroughAll
swEndCondThroughNext
swEndCondUpToVertex
swEndCondUpToSurface
swEndCondOffsetFromSurface
swEndCondMidPlane
swEndCondUpToBody
Input:
Input:
Input:
d1
d2
dchk1
Do
Input:
t2
TRUE
Input:
dchk2
Input:
ddir1
TRUE
Input:
ddir2
Input:
dang1
Input:
dang2
22
TRUE
Passing Parameters
API Fundamentals
Lesson 1
Using the Macro Recorder
offsetReverse1
Input:
offsetReverse2
Input:
Input:
Input:
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Input:
translateSurface1
translateSurface2
merge
not.
Input:
useAutoSelect
TRUE
Do
Input:
useFeatScope
Input:
t0
TRUE
Input:
startOffset
Input:
flipStartOffset
Passing Parameters
23
Lesson 1
API Fundamentals
Cleaning Up
Code
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Sub main()
Part.ShowNamedView2 "*Trimetric", 8
Part.ClearSelection2 True
boolstatus = Part.Extension.SelectByID2("Arc1",
"SKETCHSEGMENT", 0, 0, 0, False, 0, Nothing, 0)
Part.SelectionManager.EnableContourSelection = 0
End Sub
Do
Note
24
Cleaning Up Code
API Fundamentals
Lesson 1
Using the Macro Recorder
As you study the API help file, youll notice that some methods have a
number suffixed to the end of the method name
(i.e. ModelDoc2.CircleCircleByRadius2.) This number represents the
version of the method. If you want to use a method in your program
you should consider using the latest version. This will ensure the
longevity of your code. The same practice should be done when you
choose a particular interface to use in your code.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Tip
Commenting Code
Modify the code and add comments. Also change the code to use
CreateCircleByRadius2 instead of CreateCircle.
Do
Option Explicit
Dim swApp As Object
Dim Part As Object
Dim boolstatus As Boolean
Sub main()
Connect to SolidWorks
Set swApp = Application.SldWorks
Set Part = swApp.ActiveDoc
Create a cylinder on the front plane
boolstatus = Part.Extension.SelectByID2("Front Plane", _
"PLANE", 0, 0, 0, False, 0, Nothing, 0)
Part.InsertSketch2 True
Part.CreateCircleByRadius2 0, 0, 0, 0.04
Part.FeatureManager.FeatureExtrusion2 True, False, False, 0,_
0, 0.015, 0, False, False, False, False, 0.01745, 0.01745,_
False, False, False, False, 1, 1, 1, 0, 0, False
End Sub
Cleaning Up Code
25
Lesson 1
API Fundamentals
Debugging Code
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Click in the column to the left of our entry point procedure to add a
breakpoint:
Breakpoint
Do
26
Cleaning Up Code
API Fundamentals
Lesson 1
Using the Macro Recorder
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
20 Press F8.
Do
21 Press F8.
Note
Cleaning Up Code
Certain API calls have a return value. In order to help debug a macro,
place the mouse cursor over a return value before executing a line.
27
Lesson 1
API Fundamentals
Note
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
22 Press F8.
Place the mouse cursor over the same return value to see if the call was
performed correctly. In this case, the return value boolstatus changes
from False, to True. This reveals that the macro selected the item
successfully.
Do
Adding Forms
to a Macro
Where to Find It
I
I
28
API Fundamentals
Lesson 1
Using the Macro Recorder
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Tip
If the properties window is not showing in your code editor press the
F4 key to display it. You can also display it by clicking
View, Properties Window... from the menu.
From the toolbox, drag and drop one label and five command buttons
onto the form. Use the following as a guide for each control:
CommandButton1:
(Name): cmd100mm
Caption: 100 mm
CommandButton2:
(Name): cmd500mm
Caption: 500 mm
Do
CommandButton3:
(Name): cmd1m
Caption: 1 m
CommandButton4:
(Name): cmd5m
Caption: 5 m
CommandButton5:
(Name): cmdExit
Caption: Exit
29
Lesson 1
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Tip
Use the Ctrl + Tab key to switch back to the userform every time you
add a new event handler. In VBA the form is separated from the source
code that runs behind the form.
Do
At this point the entire macro file should contain one module and one
form. We want to keep both, but move code to different locations.
Cut everything within the module leaving only an empty entry point
procedure (Sub main .... End Sub). Paste the code in the click event for
each command button (except the Exit button). Look closely at the
code below. Only one parameter (shown in bold) is changed to account
for the different extrusion depths of each button.
30
API Fundamentals
Lesson 1
Using the Macro Recorder
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
31
Lesson 1
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Save the macro. With SolidWorks open and a new part file created, run
the macro either from the Macro toolbar or from the VBA editor. Click
the buttons to create the different length cylinders.
100mm
500mm
1m
5m
Do
32
API Fundamentals
Lesson 1
Using the Macro Recorder
To capture input from a user, we add textbox controls that require the
user to specify the depth and diameter rather than hard coding the
values. Use the following diagram as a guide for laying out your
controls.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
TextBox1:
(Name): txtDiameter
Text: <leave blank>
TextBox2:
(Name): txtDepth
Text: <leave blank>
CommandButton1:
(Name): cmdBuild
Caption: Build
CommandButton2:
(Name): cmdExit
Caption: Exit
Do
Connect to SolidWorks
Set swApp = Application.SldWorks
Set Part = swApp.ActiveDoc
33
Lesson 1
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
10
50
Do
34
API Fundamentals
Exercise 1:
Recording a Macro
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Exercise 1:
Recording a
Macro
Objective
Skills Learned
I
I
SldWorks.ActiveDoc
ModelDocExtension.SelectByID2
ModelDoc2.InsertSketch2
ModelDoc2.CreateCircle
FeatureManager.FeatureExtrusion2
Procedure
1.
2.
3.
4.
Do
APIs Used
5.
6.
7.
8.
9.
35
Exercise 1:
API Fundamentals
Recording a Macro
Solution
Option Explicit
swApp As Object
Part As Object
SelMgr As Object
boolstatus As Boolean
longstatus As Long, longwarnings As Long
Feature As Object
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Dim
Dim
Dim
Dim
Dim
Dim
Do
Sub main()
Set swApp = Application.SldWorks
Set Part = swApp.ActiveDoc
Set SelMgr = Part.SelectionManager
boolstatus = Part.Extension.SelectByID2("Front Plane", _
"PLANE", 0, 0, 0, False, 0, Nothing, 0)
Part.InsertSketch2 True
Part.ClearSelection2 True
Part.CreateCircle 5.432844932845E-04, 0.001086568986569, _
0, 0.02227466422466, -0.005976129426129, 0
Part.ShowNamedView2 "*Trimetric", 8
Part.ClearSelection2 True
boolstatus = Part.Extension.SelectByID2("Arc1", _
"SKETCHSEGMENT", 0, 0, 0, False, 0, Nothing, 0)
Part.FeatureManager.FeatureExtrusion2 True, False, False, _
0, 0, 0.08, 0.00254, False, False, False, False, _
0.01745329251994, 0.01745329251994, False, False, _
False, False, 1, 1, 1, 0, 0, False
Part.SelectionManager.EnableContourSelection = 0
End Sub
36
API Fundamentals
Exercise 2:
Adding Macro Code to a VBA Button Control
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Exercise 2:
Adding Macro
Code to a VBA
Button Control
Objective
Skills Learned
I
I
I
I
I
Adding a form.
Displaying a form.
Adding command button controls to a form.
Adding code to the click event of a button.
Improving macro code with updated methods.
SldWorks.ActiveDoc
ModelDocExtension.SelectByID2
ModelDoc2.InsertSketch2
ModelDoc2.CreateCircleByRadius2
FeatureManager.FeatureExtrusion2
Procedure
1.
2.
3.
4.
5.
Do
APIs Used
37
Exercise 2:
API Fundamentals
Solution
Option Explicit
Sub main()
frmMacro1a.Show
End Sub
--------------------------------------------------------------Option Explicit
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
38
API Fundamentals
Exercise 2:
Adding Macro Code to a VBA Button Control
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
---------------------------------------------------------------
39
Exercise 3:
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Exercise 3:
Adding User
Input Fields on
a VBA Form
Objective
To automate the feature creation process while allowing for userdefined parameters. You will capture two parameters from the user
before running the macro: radius and depth. Within the code, you will
declare the variables as string values, convert them to double values
and pass them as parameters to the methods. When the user clicks the
Build button, the application should create the user-defined cylinder.
Skills Learned
I
I
I
SldWorks.ActiveDoc
ModelDocExtension.SelectByID2
ModelDoc2.InsertSketch2
ModelDoc2.CreateCircleByRadius2
FeatureManager.FeatureExtrusion2
Procedure
1.
2.
3.
4.
Do
APIs Used
5.
6.
7.
8.
9.
40
API Fundamentals
Exercise 3:
Adding User Input Fields on a VBA Form
Solution
Option Explicit
Sub main()
frmMacro1b.Show
End Sub
--------------------------------------------------------------Option Explicit
swApp As Object
Part As Object
boolstatus As Boolean
radius As Double
depth As Double
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Dim
Dim
Dim
Dim
Dim
Do
41
Exercise 3:
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
42
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
API Fundamentals
Lesson 2
The API Object Model
Do
Build a working macro with forms and controls that explores the
differences between each application object.
43
Lesson 2
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
44
API Fundamentals
Lesson 2
The API Object Model
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
SolidWorks API
Object Model
45
Lesson 2
API Fundamentals
The macro in this case study also highlights the differences between
connecting to new documents versus existing documents. There are
different accessor methods on the SldWorks interface that permit you to
do this. This case study will also help you understand how the
ModelDoc2 object is different from the more specific document object
types: PartDoc, AssemblyDoc, and DrawingDoc.
Visual Basic is an intuitive and simple to learn programming language
compared to C++. One thing that Visual Basic does very well is
automatic type casting. Consider the following statement: A PartDoc,
AssemblyDoc, and DrawingDoc are all derived from the ModelDoc2
object. This means that if you called a method that resided on the
ModelDoc2 object from one of its derived objects the call would be
successful because Visual Basic will automatically look to the upper
level object and see if the method existed on it. Visual Basic would
then make the call from that higher level object. In other words, Visual
Basic will do an automatic type cast from the calling object to the
object it was derived from. An example of this would be
PartDoc.InsertSketch (InsertSketch resides on the ModelDoc2 object.)
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Visual Basic
Automatic Type
Casting
Do
In C++, type casting would have to be done between the base classes
and their derived objects to call the specific methods on their interfaces.
46
API Fundamentals
Lesson 2
The API Object Model
Application
Objects
SldWorks Object
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
(swApp)
.DisplayStatusBar (OnOff)
.SolidWorksExplorer
.ArrangeWindows (Style)
Do
.ActiveDoc
Note
Application Objects
The tables used in this book are not a complete documentation of all
methods and properties that exist on the interface being described. For
a complete list refer to the API help file.
47
Lesson 2
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Sub main()
Set swApp = Application.SldWorks
End Sub
SolidWorks 2006
Type Library
Do
48
Application Objects
API Fundamentals
Lesson 2
The API Object Model
IntelliSense
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
Application Objects
49
Lesson 2
API Fundamentals
Late Binding
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
End Sub
I
Early Binding
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
End Sub
Tip
It is best to use early binding. Early binding helps to make your code
understandable by other programmers and also it will make your
application faster. Early binding also checks for coding errors at
compile time. When the compiler is bound to an object at compile time,
the compiler can check to see if the object supports the members that
are called from it. If you late bind, the error will not be found until you
run the code.
Edit the code from late bound to early bound by changing the object
declaration:
Dim swApp As SldWorks.SldWorks
Sub main()
Set swApp = Application.SldWorks
End Sub
Do
50
Application Objects
API Fundamentals
Lesson 2
The API Object Model
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Use the Up and Down arrow keys on the keyboard to navigate through
the drop down list and use the spacebar to have VBA automatically
type the rest of the selected method. This saves the programmer the
effort of typing things out completely. IntelliSense also corrects some
syntax errors automatically and will validate whether or not the type
library is being referenced properly. If IntelliSense does not appear by
this step, you know you have a problem with your variable declaration
or you havent correctly added the type library.
Sub main()
Set swApp = Application.SldWorks
swApp.SetUserPreferenceDoubleValue
End Sub
Do
Case Study:
Connecting to
New
Documents
Tip
51
Lesson 2
API Fundamentals
The properties have already been set for the user form. The top of the
form has a frame control with other controls inside its borders.
They are as follows:
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
UserForm1:
(Name): frmNewDocs
Caption: New Documents
BorderStyle: 1 fmBorderStyleSingle
Startup Position: 2 CenterScreen
ShowModal: False
Height: 300
Width: 270
Frame1:
(Name): fraSldWorks
Caption: SldWorks
Height: 72
Width: 252
CheckBox1:
(Name): chkRevNum
Caption: RevisionNumber
CheckBox2:
(Name): chkDispStatBar
Caption: DisplayStatusBar
CheckBox3:
(Name): chkSWExp
Caption: SolidWorksExplorer
CommandButton1:
(Name): cmdConnect
Caption: Connect to SolidWorks
Do
52
API Fundamentals
Lesson 2
The API Object Model
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
53
Lesson 2
API Fundamentals
Macro Results
+
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
1.
3.
Do
2.
54
API Fundamentals
Lesson 2
The API Object Model
Now lets examine the second highest level object in the API object
hierarchy, ModelDoc2.
ModelDoc2 Object
(swModel)
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
option 1
Dim swModel As SldWorks.ModelDoc2
Set swModel = swApp.ActiveDoc
option 2
Dim swModel As SldWorks.ModelDoc2
Set swModel = swApp.NewDocument (TemplateName, PaperSize, _
Width, Height)
option 3
Dim swModel As SldWorks.ModelDoc2
Set swModel = swApp.OpenDoc6 (FileName, Type, Options, _
Config, Errors, Warnings)
Do
.InsertFamilyTableNew
.InsertNote
55
Lesson 2
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
(swModelExt)
Do
=
=
=
=
=
=
=
=
=
=
=
=
=
CenterOfMassX
CenterOfMassY
CenterOfMassZ
Volume
Area
Mass
MomXX
MomYY
MomZZ
MomXY
MomZX
MomYZ
Accuracy
.void = ModelDocExtension.SetMaterialPropertyValues
( material_property_values, config_opt, config_names )
API Fundamentals
Lesson 2
The API Object Model
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Look to the second frame control on the form. It contains three option
buttons, one command button and three more checkboxes. These
controls will allow you to create a new ModelDoc2 object. The
ModelDoc2 object will be either a PartDoc, AssemblyDoc, or
DrawingDoc object. The controls have the following properties:
Frame2:
(Name): fraModelDoc2
Caption: ModelDoc2
Height: 114
Width: 252
OptionButton1:
(Name): optPart
Caption: Part
Value: True
OptionButton2:
(Name): optAssy
Caption: Assembly
Value: False
OptionButton3:
(Name): optDraw
Caption: Drawing
Value: False
CheckBox4:
(Name): chkSketch
Caption: InsertSketch2
CheckBox5:
(Name): chkFamilyTable
Caption: InsertFamilyTableNew
Do
CheckBox6:
(Name): chkNote
Caption: InsertNote
CommandButton2:
(Name): cmdNewModel
Caption: Connect to Model
57
Lesson 2
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Add conditional statements to account for each of the three radio button
choices.
Const filedir As String = "C:\SolidWorks 2006 Training
Files\API Fundamentals\Templates\"
Private Sub cmdNewModel_Click()
Dim swApp As SldWorks.SldWorks
Set swApp = Application.SldWorks
Do
Add the remaining code for each of the checkboxes. (This code should
added right after the code from the previous step and right before the
End Sub statement.)
' Determine which items are checked
' and call specific methods and properties on ModelDoc2
If chkSketch.Value = True Then
swModel.InsertSketch2 True
End If
If chkFamilyTable.Value = True Then
swModel.InsertFamilyTableNew
End If
58
API Fundamentals
Lesson 2
The API Object Model
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
New document
59
Lesson 2
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
New sketch
Next, try inserting a design table in both a part and assembly document:
+
Do
60
API Fundamentals
Lesson 2
The API Object Model
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
New note
Note
Not all ModelDoc2 methods work exactly the same across all three
document types. A drawing, for example, would need at least one view
inserted before we could use the methods FocusLocked and
InsertFamilyTableNew (see step 16 )
61
Lesson 2
API Fundamentals
Click the close icon in the upper right corner of the form.
16 Add code to prepare the drawing.
Add this user defined function at the bottom of the module to prepare a
drawing:
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
drawname = swModel.GetTitle
swApp.OpenDoc6 filedir + "BlockwithDesignTable.SLDPRT", 1, _
0, "", errors, warnings
Set swModel = swApp.ActivateDoc2(drawname, True, errors)
'Notice automatic typecasting to DrawingDoc!
Set preparedrawingView = swModel.CreateDrawViewFromModelView_
(filedir + "BlockwithDesignTable.SLDPRT", "*Isometric", 0.1,_
0.1, 0)
End Function
Note
Do
62
API Fundamentals
Lesson 2
The API Object Model
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Sketch mode is
now active in view
Design table is
inserted into view
Do
Click the close icon in the upper right corner of the form.
63
Lesson 2
API Fundamentals
Now lets look at all three specific Document object types: PartDoc,
AssemblyDoc and DrawingDoc.
PartDoc Object
(swPart)
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
AssemblyDoc
Object
(swAssy)
DrawingDoc Object
(swDraw)
Dim
Dim
Dim
Dim
swModel As SldWorks.ModelDoc2
swPart As SldWorks.PartDoc
swAssy As SldWorks.AssemblyDoc
swDraw As SldWorks.DrawingDoc
.MaterialPropertyValues
.CreateNewBody
Do
.MirrorPart
64
API Fundamentals
Lesson 2
The API Object Model
At the bottom of the form, each document type has a frame, a command
button, and a checkbox. The properties for the controls are as follows:
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Frame3:
(Name): fraPart
Caption: PartDoc
Height: 66
Width: 78
CommandButton3:
(Name): cmdPart
Caption: New Model
CheckBox7:
(Name): chkRollback
Caption: EditRollback
----------------------------frame4:
(Name): fraAssy
Caption: AssemblyDoc
Height: 66
Width: 84
CommandButton4:
(Name): cmdAssy
Caption: New Assembly
CheckBox8:
(Name): chkComponent
Caption: AddComponent
----------------------------Frame5:
(Name): fraDraw
Caption: DrawingDoc
Height: 66
Width: 78
Do
CommandButton5:
(Name): cmdDraw
Caption: New Drawing
CheckBox9:
(Name): chkFormat
Caption: EditFormat
65
Lesson 2
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Private Sub
Dim swApp
Set swApp
End Sub
Private Sub
Dim swApp
Set swApp
End Sub
Private Sub
Dim swApp
Set swApp
End Sub
cmdDraw_Click()
As SldWorks.SldWorks
= Application.SldWorks
Do
66
API Fundamentals
Lesson 2
The API Object Model
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Before
Do
After
Rollback
67
Lesson 2
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Before
After
New component
Before
Do
After
Click the close icon in the upper right corner of the form.
68
API Fundamentals
Lesson 2
The API Object Model
Case Study:
Connecting to
Existing
Documents
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
menu.
Connect to SolidWorks.
Do
69
Lesson 2
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Sub main()
frmNewDocs.Show
frmExistingDocs.Show
End Sub
2.
3.
32 Stop macro.
Click the close icon in the upper right corner of the form.
Return to the VBA editor.
Connect to Model.
Do
70
API Fundamentals
Lesson 2
The API Object Model
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Test each file with the checkboxes toggled on and off as shown:
SheetMetalSample.sldprt
SheetMetalSample.sldasm
SheetMetalSample.slddrw
+
Do
Toolbars hidden
71
Lesson 2
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Toolbars visible
Do
Custom Property
72
API Fundamentals
Lesson 2
The API Object Model
Existing Part.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
73
Lesson 2
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Mirrored part
Do
74
API Fundamentals
Lesson 2
The API Object Model
40 Run macro.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Edit part
Select component
Insert cavity
Do
Return to edit
assembly mode
Suppress part to
view cavity
75
Lesson 2
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
43 Run macro.
Do
New layer
44 Exit macro.
76
API Fundamentals
Exercise 4:
Working with New Documents
Exercise 4:
Working with
New Documents
Skills Learned
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Objective
I
I
I
APIs Used
SldWorks.SendMsgToUser2
------------------------------SldWorks.NewDocument
ModelDoc2.InsertSketch2
ModelDoc2.CreateCircleByRadius2
ModelDoc2.ViewZoomtofit2
Procedure
1.
2.
3.
4.
5.
6.
7.
8.
Do
77
Exercise 4:
API Fundamentals
Solution
Option Explicit
Sub main()
frmNewDocs.Show
End Sub
--------------------------------------------------------------Option Explicit
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
End Sub
Do
78
End Sub
---------------------------------------------------------------
API Fundamentals
Exercise 5:
Working with Existing Documents
Exercise 5:
Working with
Existing
Documents
Skills Learned
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Objective
I
I
I
APIs Used
SldWorks.OpenDoc6
---------------------------------------SldWorks.ActiveDoc
ModelDoc2.AddLightSource
ModelDoc2.SetLightSourcePropertyValuesVB
ModelDoc2.LockLightToModel
ModelDoc2.GraphicsRedraw
Procedure
1.
2.
3.
4.
5.
6.
7.
8.
Do
79
Exercise 5:
API Fundamentals
Solution
Option Explicit
Sub main()
frmExistingDocs.Show
End Sub
--------------------------------------------------------------Option Explicit
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
End If
End Sub
Do
80
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
API Fundamentals
Do
Lesson 3
Setting System Options and
Document Properties
81
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Lesson 3
82
API Fundamentals
API Fundamentals
User
Preferences System Options
Lesson 3
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
SldWorks::SetUserPreferenceIntegerValue
SldWorks::SetUserPreferenceDoubleValue
SldWorks::SetUserPreferenceStringValue
Note
Setting
Checkboxes
SldWorks::SetUserPreferenceToggle
Input:
onFlag
TRUE =
Do
Input:
UserPreferenceValue
FALSE
83
Lesson 3
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Sub main()
Set swApp = Application.SldWorks
End Sub
Sub main()
Set swApp = Application.SldWorks
swApp.SetUserPreferenceToggle _
swConst.swInputDimValOnCreate, True
swApp.SetUserPreferenceToggle _
swConst.swSingleCommandPerPick, True
swApp.SetUserPreferenceToggle _
swConst.swShowDimensionNames, True
swApp.SetUserPreferenceToggle _
swConst.swShowErrorsEveryRebuild, True
End Sub
Do
Tip
84
In many cases an option may only need to be changed when the macro
is run. It is polite to set a changed option to the value it was set before
the macro runs. An end user may become irritated if they have to
manually change the option back to their preference every time they
run the macro.
API Fundamentals
Lesson 3
Setting Textboxes
with Integers
SldWorks::SetUserPreferenceIntegerValue
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Output:
retval
TRUE
Input:
UserPreferenceValue
value
Input:
Do
85
Lesson 3
API Fundamentals
Setting Textboxes
with Doubles
SldWorks::SetUserPreferenceDoubleValue
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Output:
retval
TRUE
Input:
UserPreferenceValue
value
Input:
Do
Test to see if the textbox value has changed then return to VBA.
86
API Fundamentals
Lesson 3
Setting Textboxes
with String Values
SldWorks::SetUserPreferenceStringValue
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Output:
retval
TRUE
Input:
UserPreferenceValue
value
Input:
Do
Test to see if the textbox value has changed then return to VBA.
87
Lesson 3
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Setting Listboxes
API Fundamentals
Do
Setting Radio
Buttons
88
API Fundamentals
Lesson 3
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Sub main()
Set swApp = Application.SldWorks
swApp.SetUserPreferenceToggle _
swConst.swInputDimValOnCreate, True
swApp.SetUserPreferenceToggle _
swConst.swSingleCommandPerPick, True
swApp.SetUserPreferenceToggle _
swConst.swShowDimensionNames, True
swApp.SetUserPreferenceToggle _
swConst.swShowErrorsEveryRebuild,True
color = RGB(128, 255, 128) sets color to green
swApp.SetUserPreferenceIntegerValue _
swConst.swSystemColorsViewportBackground, color
swApp.SetUserPreferenceDoubleValue _
swConst.swDrawingDetailViewScale, 1.5
value = ("D:\Temp")
swApp.SetUserPreferenceStringValue _
swConst.swBackupDirectory, value
swApp.SetUserPreferenceIntegerValue _
swConst.swEdgesHiddenEdgeDisplay, _
swConst.swEdgesHiddenEdgeDisplayDashed
Do
Test to see if the radio button changed and the two slider bars moved.
13 Exit macro.
89
Lesson 3
API Fundamentals
User
Preferences Document
Properties
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
ModelDoc2::SetUserPreferenceIntegerValue
ModelDoc2::SetUserPreferenceDoubleValue
ModelDoc2::SetUserPreferenceStringValue
ModelDoc2::SetUserPreferenceToggle
Input:
Input:
UserPreferenceValue
onFlag
TRUE =
Do
FALSE =
90
API Fundamentals
Lesson 3
Connect to ModelDoc2.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
End Sub
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
swModel.SetUserPreferenceToggle _
swConst.swDetailingDualDimensions, True
End Sub
Do
Locating the
Correct APIs
and
Enumeration
Values
Change an option.
Click Tools, Options... from the menu and click View Rotation on the
91
Lesson 3
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Save the macro anywhere you like and edit the code.
The maximum and minimum values are recorded along with the
appropriate APIs for changing the settings.
Sub main()
Set swApp = Application.SldWorks
Fast value of Mouse Speed
swApp.SetUserPreferenceIntegerValue _
swViewRotationMouseSpeed, 100
Fast value of View Rotation Speed
swApp.SetUserPreferenceDoubleValue swViewAnimationSpeed, 0.5
Slow value of Mouse Speed
swApp.SetUserPreferenceIntegerValue swViewRotationMouseSpeed, 0
Slow value of View animation speed.
swApp.SetUserPreferenceDoubleValue swViewAnimationSpeed, 3
End Sub
UserPreference
Tables For
System Options
The following tables list all of the System Options and how they are
represented by the API.
The tables have three columns that show the:
Do
Note
92
Most of the options are supported by the API, however some are not.
The Enumeration / Value column will display Not Supported if the
setting cannot be changed by the API.
Some settings can be set on both the SldWorks and the ModelDoc2
object. An example would be the Mouse Speed that was shown in the
previous case study. Study the User Preference enumeration values in
the API help file for more information.
API Fundamentals
Lesson 3
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
General
Type
Enumeration / Values
Toggle
swOpenLastUsedDocumentAtStart
Toggle
swInputDimValOnCreate
Toggle
swSingleCommandPerPick
Toggle
swShowDimensionNames
Toggle
swShowErrorsEveryRebuild
Toggle
swMaximizeDocumentOnOpen
Toggle
swUseShadedFaceHighlight
Toggle
swThumbnailGraphics
Toggle
swUseSystemSeparatorForDims
Toggle
Not Supported
Toggle
Not Supported
Toggle
swEnablePerformanceEmail
Toggle
swEnableConfirmationCorner
Auto-show PropertyManager
Toggle
swAutoShowPropertyManager
Toggle
Not Supported
String
swCustomPropertyUsedAsComponentDescription
Do
Setting
93
Lesson 3
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Drawings
Type
Enumeration / Values
Toggle
swDrawingAutomaticModelDimPlacement
Toggle
swAutomaticScaling3ViewDrawings
Toggle
swDrawingViewShowContentsWhileDragging
Toggle
swDrawingViewSmoothDynamicMotion
Toggle
swDrawingCreateDetailAsCircle
Toggle
swDrawingSelectHiddenEntities
Toggle
swDrawingEliminateDuplicateDimsOnInsert
Toggle
swAutomaticDrawingViewUpdateDefault
Toggle
Not Supported
Toggle
Not Supported
Toggle
swRapidDraftPrintOutOfSynchWaterMark
Toggle
swShowRefGeomName
Toggle
swDrawingViewAutoHideComponents
Toggle
swDisplayArcCenterPoints
Toggle
swDisplayEntityPoints
Toggle
swDrawingSaveShadedData
Toggle
swDrawingPrintBreaklinesInBrokenView
Int
swDrawingPrintCrosshatchOutOfDateViews
Double
swDrawingDetailViewScale
String
swDrawingCustomPropertyUsedAsRevision
Do
Setting
94
Not Supported
API Fundamentals
Lesson 3
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Display Style
Type
Enumeration / Values
Int
swHiddenEdgeDisplayDefault
swDisplayMode_e
Int
swTangentEdgeDisplayDefault
swDisplayTangentEdges_e
Toggle
swDrawingsDefaultDisplayTypeFastHLRHLV
swDrawingsDefaultDisplayTypeHLREdgesWhenSha
ded
Do
Setting
95
Lesson 3
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Area Hatch
Setting
Type
Enumeration / Values
Int
swDrawingAreaHatchFillStyle
swAreaHatchFillStyle_e
Pattern
String
swDrawingAreaHatchPattern
String values can be found in the combo box
dropdown list.
Double
swDrawingAreaHatchScale
Double
swDrawingAreaHatchAngle
Scale
Do
Angle
96
API Fundamentals
Lesson 3
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Colors
Type
Enumeration / Values
Viewport Background
Int
swSystemColorsViewportBackground
Int
swSystemColorsTopGradientColor
Int
swSystemColorsBottomGradientColor
Dynamic Highlight
Int
swSystemColorsDynamicHighlight
Highlight
Int
swSystemColorsHighlight
Selected Item 1
Int
swSystemColorsSelectedItem1
Selected Item 2
Int
swSystemColorsSelectedItem2
Selected Item 3
Int
swSystemColorsSelectedItem3
Selected Item 4
Int
swSystemColorsSelectedItem4
Int
swSystemColorsSelectedFaceShaded
Int
swSystemColorsDrawingsPaper
Drawings, Background
Int
swSystemColorsDrawingsBackground
Int
swSystemColorsDrawingsVisibleModelEdge
Int
swSystemColorsDrawingsHiddenModelEdge
Int
swSystemColorsImportedDrivingAnnotation
Int
swSystemColorsImportedDrivenAnnotation
Dimensions, Dangling
Int
swSystemColorsDanglingDimension
Int
Not Supported
Int
swSystemColorsDTDim
Text
Int
swSystemColorsText
Int
swSystemColorsSketchOverDefined
Int
swSystemColorsSketchFullyDefined
Int
swSystemColorsSketchUnderDefined
Int
swSystemColorsSketchInvalidGeometry
Int
swSystemColorsSketchNotSolved
Sketch, Inactive
Int
swSystemColorsSketchInactive
Int
swSystemColorsGridLinesMinor
Do
Setting
97
Lesson 3
API Fundamentals
Int
swSystemColorsGridLinesMajor
Construction Geometry
Int
swSystemColorsConstructionGeometry
Int
swSystemColorsAssemblyEditPart
Int
swSystemColorsAssemblyEditPartHiddenLines
Int
swSystemColorsAssemblyNonEditPart
Inactive Entities
Int
swSystemColorsInactiveEntity
Temporary Graphics
Int
swSystemColorsTemporaryGraphics
Int
swSystemColorsTemporaryGraphicsShaded
Int
swSystemColorsActiveSelectionListBox
Int
swSystemColorsSurfacesOpenEdge
Int
swSystemColorsShadedEdge
Int
swSystemColorsRefTriadX
Int
swSystemColorsRefTriadY
Int
swSystemColorsRefTriadZ
Int
swSystemColorsTreeItemNormal
Int
swSystemColorsTreeItemSelected
Annotations, Imported
Int
swSystemColorsImportedAnnotation
Int
swSystemColorsNonImportedAnnotation
Int
swSytemColorsInterferenceBodyColor
Int
swSystemColorsHiddenEdgeSelectionShow
Int
swSystemColorsPropertyManagerColor
swPropertyManagerColorScheme_e
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
PropertyManagerSkin
Not Supported
Not Supported
Toggle
swColorsGradientPartBackground
Match graphics
Toggle
swColorsMatchViewAndFeatureManagerBackgroun
d
Toggle
swColorsUseShadedEdgeColor
Toggle
swColorsUseSpecifiedEditColors
Do
98
API Fundamentals
Lesson 3
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Sketch
Type
Enumeration / Values
Toggle
swFullyConstrainedSketchMode
Toggle
swDisplayArcCenterPoints
Toggle
swDisplayEntityPoints
Toggle
swSketchPromptToCloseSketch
Toggle
swSketchCreateSketchOnNewPart
Toggle
swSketchOverrideDimensionsOnDrag
Toggle
swSketchDisplayPlaneWhenShaded
Toggle
swDisplayVirtualSharps
Toggle
swSketchLineLengthVirtualSharp3d
Toggle
Not Supported
Toggle
swSketchShowSplineControlPolygon
Toggle
swSketchOverdefiningDimsPromptToSetState
Toggle
swSketchOverdefiningDimsSetDrivenByDefault
Do
Setting
99
Lesson 3
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Relations / Snaps
Setting
Type
Enumeration / Values
Enable Snapping
Toggle
swFullyConstrainedSketchMode
Toggle
swSketchInferFromModel
Automatic relations
Toggle
swSketchAutomaticRelations
Toggle
swSketchSnapsPoints
Center Points
Toggle
swSketchSnapsCenterPoints
Mid-points
Toggle
swSketchSnapsMidPoints
Quadrant Points
Toggle
swSketchSnapsQuadrantPoints
Intersections
Toggle
swSketchSnapsIntersections
Nearest
Toggle
swSketchSnapsNearest
Toggle
swSketchSnapsTangent
Perpendicular
Toggle
swSketchSnapsPerpendicular
Parallel
Toggle
swSketchSnapsParallel
Horizontal/vertical lines
Toggle
swSketchSnapsHVLines
Horizontal/vertical to points
Toggle
swSketchSnapsHVPoints
Length
Tangent
swSketchSnapsLength
Toggle
swSketchSnapsGrid
Toggle
swSnapOnlyIfGridDisplayed
Angle
Toggle
swSketchSnapsAngle
Snap angle
Double
swSnapToAngleValue
Do
Toggle
Grid
100
API Fundamentals
Lesson 3
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Display / Selection
Type
Enumeration / Values
Int
swEdgesHiddenEdgeDisplay
swEdgesHiddenEdgeDisplay_e
Toggle
swEdgesHiddenEdgeSelectionInWireframe
Toggle
swEdgesHiddenEdgeSelectionInHLR
Int
swEdgesTangentEdgeDisplay
swEdgesTangentEdgeDisplay_e
Int
swEdgesShadedModeDisplay
swEdgesShadedModeDisplay_e
Int
swEdgesInContextEditTransparencyType
swEdgesInContextEditTransparencyType_e
Percentage of transparency
Int
swEdgesInContextEditTransparency
Range is 0 - 100 / Increment by 10
Toggle
swEdgesHighlightFeatureEdges
Toggle
swEdgesDynamicHighlight
Toggle
swEdgesOpenEdgesDifferentColor
Anti-alias edges
Toggle
swEdgesAntiAlias
Toggle
swEdgesDisplayShadedPlanes
Toggle
swDisplayEnableSelectionThroughTransparency
Toggle
swDisplayReferenceTriad
Toggle
Not Supported
Int
swFourViewportProjectionType
swDrawingProjectionType_e
Do
Setting
101
Lesson 3
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Performance
Type
Enumeration / Values
Verification on rebuild
Toggle
swPerformanceVerifyOnRebuild
Toggle
swIgnoreSMFSelfInterCheck
Toggle
swUseAlphaTransparency
Toggle
swTransparencyHighQualityDynamic
Curvature generation
Toggle
swPerformanceAlwaysGenerateCurvature
Level of detail
Int
swLevelOfDetail
Range 0 - 20 - the smaller the number the
greater the detail
Toggle
swAutoLoadPartsLightweight
Toggle
Not Supported
Int
swCheckForOutOfDateLightweightComponents
swCheckOutOfDate_e
Int
swResolveLightweight
0 = Prompt
1 = Always
Int
swPerformanceAssemRebuildOnLoad
swPromptAlwaysNever_e
Int
swPerformanceViewsToDraftQuality
swPromptAlwaysNever_e
Double
swMateAnimationSpeed
0 = Off
0.5 = Fast
3 = Slow
Toggle
swUpdateMassPropsDuringSave
Toggle
swUseShadedPreview
Toggle
swUseSimpleOpenGL
Do
Setting
102
API Fundamentals
Lesson 3
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Assemblies
Type
Enumeration / Values
Toggle
swAssemblyAllowComponentMoveByDragging
Toggle
swLargeAsmModeEnabled
Int
swLargeAsmModeThreshold
Toggle
swLargeAsmModeAutoLoadLightweight
Toggle
swLargeAsmModeAutoRecover
Toggle
swLargeAsmModeHideAllItems
Toggle
swLargeAsmModeUseHLREdgesInShaded
Toggle
swLargeAsmModeSuspendAutoRebuild
Do
Setting
103
Lesson 3
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
External References
Type
Enumeration / Values
Toggle
swExtRefOpenReadOnly
Toggle
swExtRefNoPromptOrSave
Toggle
swExtRefMultipleContexts
Int
swLoadExternalReferences
swLoadExternalReferences_e
Toggle
Not Supported
Toggle
swUseFolderSearchRules
Int
swExternalReferencesUpdateOutOfDateLinkedDe
signTable
swExternalReferencesUpdateOutOfDateLinkedDe
signTable_e
Toggle
swExtRefAutoGenNames
Toggle
swExtRefUpdateCompNames
Toggle
swExternalReferencesDisable
Do
Setting
104
API Fundamentals
Lesson 3
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Default Templates
Setting
Type
Enumeration / Values
Parts
String
swDefaultTemplatePart
Assemblies
String
swDefaultTemplateAssembly
Drawings
String
swDefaultTemplateDrawing
Toggle
swAlwaysUseDefaultTemplates
Do
105
Lesson 3
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
File Locations
Type
Enumeration / Values
Document Templates
String
swFileLocationsDocumentTemplates
Referenced Documents
String
swFileLocationsDocuments
String
swFileLocationsCustomPropertyFile
Appearance Folders
String
swFileLocationsAppearances
Material Databases
String
swFileLocationsMaterialDatabases
Color Swatches
String
swFileLocationsColorSwatches
Textures
String
swFileLocationsTextures
Design Library
String
swFileLocationsDesignLibrary
Bend Tables
String
swFileLocationsBendTable
String
swFileLocationsBendNoteFormatFile
String
Not Supported
Sheet Formats
String
swFileLocationsSheetFormat
String
swFileLocationsLineStyleDefinitions
String
swFileLocationsDimensionFavorites
Blocks
String
swFileLocationsBlocks
BOM Templates
String
swFileLocationsBOMTemplates
String
swFileLocationsHoleTableTemplates
String
swFileLocationsHoleCalloutFormatFile
String
swFileLocationsRevisionTableTemplates
String
swFileLocationsWeldmentCutListTemplates
Weldment Profiles
String
swFileLocationsWeldmentProfiles
String
swFileLocationsWeldmentPropertyFile
Macros
String
swFileLocationsMacros
String
swFileLocationsMacroFeatures
Web Folders
String
swFileLocationsWebFolders
String
swFileLocationsJournalFile
String
swFileLocationsDesignJournalTemplate
Do
Setting
106
API Fundamentals
Lesson 3
Spelling Folders
String
Not Supported
Scene Folders
String
swFileLocationsScenes
Light Folders
String
swFileLocationsLights
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Type
Enumeration / Values
English Units
Double
swSpinBoxEnglishLengthIncrement
Metric Units
Double
swSpinBoxMetricLengthIncrement
Angle increments
Double
swSpinBoxAngleIncrement
Do
Setting
107
Lesson 3
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
View Rotation
Type
Enumeration / Values
Arrow keys
Double
swViewRotationArrowKeys
Mouse speed
Int
swViewRotationMouseSpeed
0 - 100 (100 is max speed)
Double
swViewAnimationSpeed
Range 0 - 3 (.5 is max speed, 3 is minimum
speed)
Do
Setting
108
API Fundamentals
Lesson 3
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Backups
Type
Enumeration / Values
Int
swAutoSaveInterval
Set to 0 to turn this option off
# changes
Int
swAutoSaveInterval
Anything larger than 0 will turn this on and
set the velue
Int
swBackupCopiesPerDocument
Toggle
swSaveBackupFilesInSameLocationAsOriginal
String
swBackupDirectory
Do
Setting
109
Lesson 3
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
File Explorer
Setting
Type
Enumeration / Values
My Documents
Toggle
swFileExplorerShowMyDocuments
My Computer
Toggle
swFileExplorerShowMyComputer
My Network Places
Toggle
swFileExplorerShowMyNetworkPlaces
Recent Documents
Toggle
swFileExplorerShowRecentDocuments
Toggle
swFileExplorerShowHiddenReferencedDocuments
Samples
Toggle
swFileExplorerShowSamples
Setting
Type
Enumeration / Values
Toggle
swCollabEnableMultiUser
Toggle
swCollabAddShortcutMenuItems
Toggle
swCollabCheckReadOnlyModifiedByOthers
Int
Do
Collaboration
110
API Fundamentals
UserPreference
Tables For
Document
Properties
Lesson 3
The following tables list all of the Document Properties and how they
are represented by the API.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Detailing
Type
Enumeration / Values
Dimensioning Standard
Int
swDetailingDimensionStandard
Use enumeration values from
swDetailingStandard_e to change the standard
Toggle
swDetailingDualDimensions
On Top / On Right
Int
swDetailingDualDimPosition
Use enumeration values from
swDetailingDualDimPosition_e to change the
position
Toggle
swDetailingFixedSizeWeldSymbol
Toggle
swDetailingDisplayDatumsPer1982
Leading Zeroes
Int
swDetailingLeadingZero
swDetailingLeadingZero_e
Trailing Zeroes
Int
swDetailingDimTrailingZero
Use enumeration values from
swDetailingDimTrailingZero_e to change the
trailing zeroes
Toggle
swDetailingDisplayAlternateSection
Centerline extension
Double
swDetailingCenterlineExtension
Gap
Double
swDetailingWitnessLineGap
Double
swDetailingWitnessLineExtension
Display type
Int
swDetailingDatumDisplayType
Use enumeration values from
swDatumDisplaytype_e
to change the datum display type
Next label
String
swDetailingNextDatumFeatureLabel
Toggle
swDetailingDisplaySFSymbolsPer2002
Do
Setting
111
Lesson 3
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Dimensions
Type
Enumeration / Values
Toggle
swDetailingDimsShowParenthesisByDefault
Toggle
swDetailingDimsSnapTextToGrid
Toggle
swDetailingDimsCenterText
Toggle
swDetailingDimsPrefixInsideBasicTolBox
Toggle
swDetailingDimsAutoJogOrdinates
Double
swDetailingDimToDimOffset
Double
swDetailingObjectToDimOffset
Arrows - Style
Int
swDetailingArrowStyleForDimensions
Use enumeration values from swArrowStyle_e.
Int
swDetailingDimensionArrowPosition
Use enumeration values from
swDimensionArrowSide_e.
Toggle
swDetailingRadialDimsDisplay2ndOutsideArrow
Toggle
swDetailingRadialDimsArrowsFollowText
Gap
Double
swDetailingDimBreakGap
Toggle
swDetailingDimBreakAroundArrow
Double
swDetailingDimBentLeaderLength
Int
swDetailingDimensionTextAlignmentHorizontal
Use enumeration values from
swTextJustification_e
Int
swDetailingDimensionTextAlignmentVertical
Use enumeration values from
swTextAlignmentVertical_e
Toggle
Not Supported
Do
Setting
112
API Fundamentals
Lesson 3
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Notes
Type
Enumeration / Values
Text Alignment
Int
swDetailingNoteTextAlignment
swTextJustification_e
Leader Anchor
Int
swDetailingNoteLeaderSide
swLeaderSide_e
Leader Style
Int
swDetailingNotesLeaderStyle
swLeaderStyle_e
Leader Length
Double
swDetailingNoteBentLeaderLength
Toggle
Not Supported
Border Style
Int
swDetailingBalloonStyle
swBaloonStyle_e
Border Size
Int
swDetailingBalloonFit
swBaloonFit_e
Toggle
swShowSheetMetalBendNotes
Int
swBendNoteStyle
swBendNoteStyle_e
Do
Setting
113
Lesson 3
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Balloons
Type
Enumeration / Values
Int
swDetailingBOMBalloonStyle
swBalloonStyle_e
Int
swDetailingBOMBalloonFit
swBalloonFit_e
Int
swDetailingBOMStackedBalloonStyle
swBalloonStyle_e
Int
swDetailingBOMStackedBalloonFit
swBalloonFit_e
Int
swDetailingBOMUpperText
swBalloonTextContent_e
Int
swDetailingBOMLowerText
swBalloonTextContent_e
Toggle
swDetailingBalloonsDisplayWithBentLeader
Double
swDetailingBalloonBentLeaderLength
Int
swDetailingAutoBalloonLayout
swBalloonLayoutType_e
Do
Setting
114
API Fundamentals
Lesson 3
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Arrows
Type
Enumeration / Values
Arrow Height
Double
swDetailingArrowHeight
Arrow Width
Double
swDetailingArrowWidth
Arrow Length
Double
swDetailingArrowLength
Int
swDetailingArrowStyleForEdgeVertexAttachmen
t
swArrowStyle_e
Int
swDetailingArrowStyleForFaceAttachment
swArrowStyle_e
Int
swDetailingArrowStyleForUnattached
swArrowStyle_e
Int
swDetailingForeshortenedDiameterStyle
swDetailingForeshortenedDiameterStyle_e
Double
swDetailingSectionArrowLength
Double
swDetailingSectionArrowWidth
Double
swDetailingSectionArrowHeight
Do
Setting
115
Lesson 3
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Virtual Sharps
Setting
Type
Enumeration / Values
Int
swDetailingVirtualSharpStyle
swDetailingVirtualSharp_e
Setting
Type
Enumeration / Values
Cosmetic Threads
Toggle
swDisplayCosmeticThreads
Datums
Toggle
swDisplayDatums
Datum Targets
Toggle
swDisplayDatumTargets
Feature dimensions
Toggle
swDisplayFeatureDimensions
Reference dimensions
Toggle
swDisplayReferenceDimensions
Toggle
swDisplayShadedCosmeticThreads
Geometric tolerances
Toggle
swDisplayGeometricTolerances
Notes
Toggle
swDisplayNotes
Surface finish
Toggle
swDisplaySurfaceFinishSymbols
Do
Annotations Display
116
API Fundamentals
Lesson 3
Toggle
swDisplayWeldSymbols
Toggle
swDisplayAllAnnotations
Int
swAnnotationTextScaleNumerator
Int
swAnnotationTextScaleDenominator
Toggle
swDisplayTextAtSameSizeAlways
Toggle
swDisplayOnlyInViewOfCreation
Display annotations
Toggle
swDisplayAnnotations
Toggle
swDisplayAnnotationsUseAssemblySettings
Toggle
swAnnotationDisplayHideDanglingDim
Setting
Type
Enumeration / Values
Note
Text
Format
swDetailingNoteTextFormat
Dimension
Text
Format
swDetailingDimensionTextFormat
Detail
Text
Format
swDetailingDetailTextFormat
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Welds
Section
Text
Format
swDetailingSectionTextFormat
View Arrow
Text
Format
swDetailingViewArrowTextFormat
Surface Finish
Text
Format
swDetailingSurfaceFinishTextFormat
Weld Symbol
Text
Format
swDetailingWeldSymbolTextFormat
Tables
Text
Format
swDetailingGeneralTableTextFormat
Balloon
Text
Format
swDetailingBalloonTextFormat
Annotations Font
117
Lesson 3
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Grid / Snap
Type
Enumeration / Values
Display Grid
Toggle
swGridDisplay
Dash
Toggle
swGridDisplayDashed
Automatic scaling
Toggle
swGridAutomaticScaling
Double
swGridMajorSpacing
Int
swGridMinorLinesPerMajor
Int
swSnapPointsPerMinor
Do
Setting
118
API Fundamentals
Lesson 3
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Units
Type
Enumeration / Values
Unit System
Int
swUnitSystem
swUnitSystem_e
Length Units
Int
swUnitsLinear
swLengthUnit_e
Int
swUnitsLinearDecimalDisplay
swFractionDisplay_e
Toggle
swUnitsLinearRoundToNearestFraction
Int
swUnitsLinearDecimalPlaces
Int
swUnitsLinearFractionDenominator
Toggle
swUnitsLinearFeetAndInchesFormat
Dual Units
Int
swUnitsDualLinear
swLengthUnit_e
Int
swUnitsDualLinearDecimalDisplay
swFractionDisplay_e
Toggle
swUnitsDualLinearRoundToNearestFraction
Int
swUnitsDualLinearDecimalPlaces
Int
swUnitsDualLinearFractionDenominator
Toggle
swUnitsDualLinearFeetAndInchesFormat
Angular Units
Int
swUnitsAngular
swAngleUnit_e
Int
swUnitsAngularDecimalPlaces
Int
swUnitsMassPropLength
swLengthUnit_e
Int
swUnitsMassPropMass
swUnitsMassPropMass_e
Int
swUnitsMassPropVolume
swUnitsMassPropVolume_e
Int
swUnitsMassPropDecimalPlaces
Force
Int
swUnitsForce
swUnitsForce_e
Do
Setting
119
Lesson 3
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Colors
Setting
Type
Enumeration / Values
Wireframe/HLR
Int
swDocumentColorWireFrame
Shading
Int
swDocumentColorShading
Int
swDocumentColorHidden
Int
swDocumentColorFeatBend
Int
swDocumentColorFeatBoss
Int
swDocumentColorFeatCavity
Int
swDocumentColorFeatChamfer
Int
swDocumentColorFeatCut
Int
swDocumentColorFeatLoftCut
Cut-Surface
Int
swDocumentColorFeatSurfCut
Cut-Sweep
Int
swDocumentColorFeatSweepCut
Weld Bead
Int
swDocumentColorFeatWeldBead
Extrude
Int
swDocumentColorFeatExtrude
Int
swDocumentColorFeatFillet
Int
swDocumentColorFeatHole
Library Feature
Int
swDocumentColorFeatLibrary
Loft
Int
swDocumentColorFeatLoft
MidSurface
Int
swDocumentColorFeatMidSurface
Pattern
Int
swDocumentColorFeatPattern
Surface
Int
swDocumentColorFeatRefSurface
Revolution
Int
swDocumentColorFeatRevolution
Shell
Int
swDocumentColorFeatShell
Derived Part
Int
swDocumentColorFeatDerivedPart
Sweep
Int
swDocumentColorFeatSweep
Thicken
Int
swDocumentColorFeatThicken
Rib
Int
swDocumentColorFeatRib
Dome
Int
swDocumentColorFeatDome
Hidden
Bend
Boss
Cavity
Chamfer
Cut
Cut-Loft
Fillet
Do
Hole
120
API Fundamentals
Lesson 3
Int
swDocumentColorFeatForm
Shape Feature
Int
swDocumentColorFeatShape
Replace Face
Int
swDocumentColorFeatReplaceFace
Structural Member
Int
swDocumentColorFeatStructuralMember
Gusset
Int
swDocumentColorFeatGusset
End cap
Int
swDocumentColorFeatEndCap
Wrap
Int
swDocumentColorFeatWrap
Toggle
swColorsWireframeHLRShadedSame
Toggle
swIgnoreFeatureColors
Setting
Type
Enumeration / Values
Density
Double
swMaterialPropertyDensity
Int
swMaterialPropertyAreaHatchFillStyle
swAreaHatchFillStyle_e
String
swMaterialPropertyCrosshatchPattern
Use the pattern strings listed in the combo
box for this document property.
Double
swMaterialPropertyCrosshatchScale
Double
swMaterialPropertyCrosshatchAngle
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Form feature
Do
Material Properties
121
Lesson 3
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Image Quality
Setting
Type
Enumeration / Values
Int
swImageQualityShaded
Deviation
Double
swImageQualityShadedDeviation
Toggle
swImageQualityUseHighQualityEdgeSize
Toggle
swImageQualityApplyToAllReferencedPartDoc
Toggle
swImageQualitySaveTesselationWithPartDoc
Int
swImageQualityWireframe
Range 0 - 100
Setting
Type
Enumeration / Values
Transparency
Int
swPlaneDisplayTransparency
Range = 0 - 100
Show Intersections
Toggle
swPlaneDisplayShowIntersections
Do
Plane Display
122
API Fundamentals
Exercise 6:
Change Multiple System Options
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Exercise 6:
Change Multiple
System Options
Objective
APIs Used
SldWorks.SetUserPreferenceToggle
SldWorks.SetUserPreferenceIntegerValue
SldWorks.SetUserPreferenceStringValue
Procedure
1.
2.
3.
4.
Do
Skills Learned
123
Exercise 6:
API Fundamentals
Solution
Option Explicit
Dim swApp As SldWorks.SldWorks
Dim value As String
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Sub main()
Set swApp = Application.SldWorks
value = "D:\Temp"
swApp.SetUserPreferenceToggle swThumbnailGraphics, True
swApp.SetUserPreferenceIntegerValue _
swEdgesHiddenEdgeDisplay, swEdgesHiddenEdgeDisplayDashed
swApp.SetUserPreferenceIntegerValue _
swEdgesInContextEditTransparencyType, _
swInContextEditTransparencyForce
swApp.SetUserPreferenceIntegerValue _
swEdgesInContextEditTransparency, 50
swApp.SetUserPreferenceStringValue swBackupDirectory, value
End Sub
124
API Fundamentals
Exercise 7:
Change Multiple Document Properties
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Exercise 7:
Change Multiple
Document
Properties
Objective
APIs Used
SldWorks.SetUserPreferenceDoubleValue
SldWorks.SetUserPreferenceIntegerValue
SldWorks.SetUserPreferenceStringValue
Procedure
1.
2.
3.
4.
Do
Skills Learned
125
Exercise 7:
API Fundamentals
Solution
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
swModel.SetUserPreferenceIntegerValue _
swDetailingDimensionStandard, swDetailingStandardANSI
swModel.SetUserPreferenceDoubleValue _
swDetailingArrowHeight, 0.15 * 0.0254
swModel.SetUserPreferenceDoubleValue _
swDetailingArrowWidth, 0.42 * 0.0254
swModel.SetUserPreferenceDoubleValue _
swDetailingArrowLength, 1.5 * 0.0254
swModel.SetUserPreferenceIntegerValue swUnitsLinear, swINCHES
swModel.SetUserPreferenceIntegerValue _
swUnitsLinearDecimalPlaces, 3
End Sub
126
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
API Fundamentals
Do
Lesson 4
Automating Part Design
Learn how to enable and use contour selection with the API.
127
Lesson 4
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
128
API Fundamentals
Lesson 4
Automating Part Design
Case Study:
Automation
Tool for Parts
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Material
(aluminum or brass)
Profile
(rectangular or circular)
Machine operation
(extrusion, extrusion
with contour selection,
or revolution).
Edit macro.
Do
Note
129
Lesson 4
API Fundamentals
Setting Material
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
130
API Fundamentals
Lesson 4
Automating Part Design
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Creating the
Sketch Rectangle
1. Create rectangle
2. Create offset
3. Add axis
ModelDoc2:: AddDimension2,
AddVerticalDimension2 and
AddHorizontalDimension2 are
used 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, and
dimension the sketch.
Selection on
Creation
When you use the API to create any thing in a SolidWorks document, it
will automatically be selected. In the next section of code notice that
the first time a sketched line is created, the method call
ModelDoc2::AddDimension2 immediately follows. By design, the API
will automatically select and highlight each sketch entity when it is
created. Because of this, no selection code needs to be written to add
the dimension to the sketched line.
Do
Adding
Dimensions
Note
131
Lesson 4
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
swModel.InsertSketch2 False
If optRectangular.Value = True Then
txtRadius.enabled = False
Dim Height As Double
Dim Width As Double
Height = CDbl(txtHeight.text) / 1000
Width = CDbl(txtWidth.text) / 1000
'Turn off dimension dialogs
swApp.SetUserPreferenceToggle swInputDimValonCreate, False
'Create the first line in the profile
swModel.CreateLine2 0.05, 0.05, 0, 0.05, 0.05 + Height, 0
'Add a dimension to the selected entity
swModel.AddDimension2 0, 0.05 + Height / 2, 0
swModel.CreateLine2 0.05, 0.05 + Height, 0, 0.05 + Width, _
0.05 + Height, 0
swModel.CreateLine2 0.05 + Width, 0.05 + Height, 0, _
0.05 + Width, 0.05, 0
swModel.CreateLine2 0.05 + Width, 0.05, 0, 0.05, 0.05, 0
swModel.AddDimension2 0.05 + Width / 2, 0, 0
swModel.ClearSelection
'Select the origin
swModel.Extension.SelectByID2 "", "EXTSKETCHPOINT", _
0, 0, 0, False, 0, Nothing, 0
'Select an end point on the profile
swModel.Extension.SelectByID2 "", "SKETCHPOINT", _
0.05, 0.05, 0, True, 0, Nothing, 0
'Add a vertical dimension
swModel.AddVerticalDimension2 0, 0.025, 0
swModel.ClearSelection
'Select the origin
swModel.Extension.SelectByID2 "", "EXTSKETCHPOINT", _
0, 0, 0, False, 0, Nothing, 0
'Select an end point on the profile
swModel.Extension.SelectByID2 "", "SKETCHPOINT", _
0.05, 0.05, 0, True, 0, Nothing, 0
'Add a horizontal dimension to fully constrain the sketch
swModel.AddHorizontalDimension2 0.025, 0, 0
swModel.ClearSelection
'Select all four profile edges
swModel.Extension.SelectByID2 "Line1", "SKETCHSEGMENT", _
0, 0, 0, False, 0, Nothing, 0
swModel.Extension.SelectByID2 "Line2", "SKETCHSEGMENT", _
0, 0, 0, True, 0, Nothing, 0
swModel.Extension.SelectByID2 "Line3", "SKETCHSEGMENT", _
0, 0, 0, True, 0, Nothing, 0
swModel.Extension.SelectByID2 "Line4", "SKETCHSEGMENT", _
0, 0, 0, True, 0, Nothing, 0
'Create the offset sketch profile from the selected edges
swModel.SketchOffset2 0.002, 0, 1
swModel.ViewZoomtofit2
Else
End if
swModel.CreateLine2 _
(0, 0, 0, 0, 0.05, 0).ConstructionGeometry = True
swModel.ViewZoomtofit2
132
API Fundamentals
Lesson 4
Automating Part Design
Creating the
Sketch Circle
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
1. Create circle
2. Create offset
Creating the construction line is the same for the rectangle or the circle.
Therefore, this call can fall outside the IF..Then statement.
Else
Dim Radius As Double
Radius = CDbl(txtRadius.text) / 1000
swModel.CreateCircleByRadius2 _
0.05 + Radius, 0.05 + Radius, 0, Radius
swModel.SketchOffset2 0.002, 0, 1
swModel.ViewZoomtofit2
End If
swModel.CreateLine2 _
(0, 0, 0, 0, 0.05, 0).ConstructionGeometry = True
swModel.ViewZoomtofit2
Do
Creating Extruded
Features
133
Lesson 4
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
MACHINE OPERATION
Dim swFeatMgr As SldWorks.FeatureManager
If optExtrude.Value = True Then
Dim Depth As Double
Depth = CDbl(txtDepth.text) / 1000
Set swFeatMgr = swModel.FeatureManager
swFeatMgr.FeatureExtrusion True, False, True, 0, 0, Depth, _
0, False, False, False, False, 0, 0, 0, 0, 0, 0, _
False, False, False
swModel.ViewZoomtofit2
End If
Enabling Contour
Selection for the
Extrusion
Do
134
API Fundamentals
Lesson 4
Automating Part Design
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
MACHINE OPERATION
Dim swFeatMgr As SldWorks.FeatureManager
If optExtrude.Value = True Then
Dim Depth As Double
Depth = CDbl(txtDepth.text) / 1000
Set swFeatMgr = swModel.FeatureManager
If optRectangular.Value = True Then
If chkContour1.Value = True Then
swModel.SelectionManager.EnableContourSelection = 1
swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _
0.05, 0.05, 0, True, 4, Nothing, 0
End If
If chkContour2.Value = True Then
swModel.SelectionManager.EnableContourSelection = 1
swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _
0.05 - 0.002, 0.05, 0, True, 4, Nothing, 0
End If
Else
If chkContour1.Value = True Then
swModel.SelectionManager.EnableContourSelection = 1
swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _
0.05 + Radius, 0.05, 0, True, 4, Nothing, 0
End If
If chkContour2.Value = True Then
swModel.SelectionManager.EnableContourSelection = 1
swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _
0.05 + Radius, 0.05 - 0.002, 0, True, 4, Nothing, 0
End If
End If
swFeatMgr.FeatureExtrusion True, False, True, 0, 0, Depth, _
0, False, False, False, False, 0, 0, 0, 0, 0, 0, _
False, False, False
swModel.SelectionManager.EnableContourSelection = 0
swModel.ViewZoomtofit2
End If
Do
Creating Revolved
Features
135
Lesson 4
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
MACHINE OPERATION
Dim swFeatMgr As SldWorks.FeatureManager
If optExtrude.Value = True Then
Dim Depth As Double
Depth = CDbl(txtDepth.text) / 1000
Set swFeatMgr = swModel.FeatureManager
If optRectangular.Value = True Then
If chkContour1.Value = True Then
swModel.SelectionManager.EnableContourSelection = 1
swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _
0.05, 0.05, 0, True, 4, Nothing, 0
End If
If chkContour2.Value = True Then
swModel.SelectionManager.EnableContourSelection = 1
swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _
0.05 - 0.002, 0.05, 0, True, 4, Nothing, 0
End If
Else
If chkContour1.Value = True Then
swModel.SelectionManager.EnableContourSelection = 1
swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _
0.05 + Radius, 0.05, 0, True, 4, Nothing, 0
End If
If chkContour2.Value = True Then
swModel.SelectionManager.EnableContourSelection = 1
swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _
0.05 + Radius, 0.05 - 0.002, 0, True, 4, Nothing, 0
End If
End If
swFeatMgr.FeatureExtrusion True, False, True, 0, 0, Depth, _
0, False, False, False, False, 0, 0, 0, 0, 0, 0, _
False, False, False
swModel.SelectionManager.EnableContourSelection = 0
swModel.ViewZoomtofit2
Else
Dim Angle As Double
Angle = CDbl(txtAngle.text * 3.14 / 180)
Set swFeatMgr = swModel.FeatureManager
swFeatMgr.FeatureRevolve Angle, True, 0, 0, 0, True, _
False, True
End If
136
Test the various options and combinations on the user form. Return to
VBA when finished.
API Fundamentals
Lesson 4
Automating Part Design
Use the tables on the next few pages as a quick reference for
identifying which methods are used for sketching, feature and viewing
commands.
Standard Commands
PrintDirect
PrintOut
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
NewDocument
OpenDoc6
LoadFile2
Rebuild
EditRebuild3
ForceRebuild3
Save3
SaveAs4
SaveBMP
Note
ShowNamedView2 "*Front", 1
ShowNamedView2 "*Top", 5
ShowNamedView2 "*Back", 2
ShowNamedView2 "*Bottom", 6
ShowNamedView2 "*Left", 3
ShowNamedView2 "*Isometric", 7
ShowNamedView2 "*Right", 4
ShowNamedView2 "*Trimetric", 8
ShowNamedView2 "*Dimetric", 9
View Commands
ViewDisplayWireframe
ViewOrientationUndo
ViewDisplayHiddengreyed
Do
TranslateBy
ViewZoomtofit2
ViewDisplayHiddenremoved
ViewZoomTo2
HlrQuality = 1
ZoomByFactor
HlrQuality = 0
ViewZoomToSelection
ViewDisplayShaded
RotateAboutCenter
AddPerspective
137
Lesson 4
API Fundamentals
Sketch Commands
Insert3DSketch2
GridOptions
SketchModifyFlip
SketchModifyRotate
SketchModifyScale
SketchModifyTranslate
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
SelectByID2
SelectByRay
InsertSketch2
AutoSolveToggle
SketchUseEdge2
CreateArc2
Sketch3DIntersections
CreateTangentArc2
InsertProjectedSketch2
Create3PointArc
SketchMirror
CreateCircle2
CreateCircleByRadius2
SketchFillet2
CreateEllipse2
CreateEllipticalArc2
SketchChamfer
SketchParabola
SketchOffset2
SketchSpline
CreateSpline
Insert3DSplineCurve
MakeStyledCurves
SketchPolygon
SketchTrim, 1
SketchRectangle
SketchTrim, 2
Do
CreateLine2
138
SketchRectangleAtAnyAngle
SplitOpenSegment
SplitClosedSegment
CreatePoint2
CreateLinearSketchStepAndRepeat
CreateCenterLine
CreateLine2.ConstructionGeometry
CreateCircularSketchStepAndRepeat
InsertSketchText
InsertSketchPicture
API Fundamentals
Lesson 4
Automating Part Design
Features Commands
InsertDome
FeatureRevolve
FeatureRevolveThin
InsertRip
FeatureCut
FeatureCutThin
EditUnsuppress2
FeatureRevolveCut
FeatureRevolveThinCut
EditUnsuppressDependent2
InsertProtrusionSwept
InsertCutSwept
EditSuppress2
InsertProtrusionBlend
InsertCutBlend
FeatureLinearPattern
FeatureFillet
FeatureCirularPattern
FeatureChamfer
FeatureChamferType
MirrorFeature
InsertRib2
InsertRip
Scale
SplitBody
InsertFeatureShell
InsertFeatureShellAddThickness
InsertCombineFeature
InsertMfDraft2
InsertDeleteBody
SimpleHole2
InsertMoveCopyBody
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
FeatureExtrusion
FeatureExtrusionThin
FeatureBoss
GetConstraints
SketchAddConstraints
Autodimension
Do
AddDimension2
AddHorizontalDimension2
AddVerticalDimension2
InsertCoordinateSystem
InsertAxis2
139
Lesson 4
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
140
API Fundamentals
Exercise 8:
Automating the Part Creation Process
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Exercise 8:
Automating the
Part Creation
Process
Objective
To design your own part automation tool using the techniques and
methods from the case study. The forms are prebuilt, but missing
controls. Add these controls, and capture the user-entered values before
launching the machine command.
The tool should set the material to Steel (density = 7.8 grams/cm3), and
sketch a profile (L bracket) with adjustable height and width. It should
also allow the user to extrude or revolve the profile as a thin feature
(with adjustable depth or angle).
Skills Learned
I
I
Do
APIs Used
Procedure
ModelDoc2.SetUserPreferenceDoubleValue
ModelDoc2.SetUserPreferenceStringValue
SldWorks.SetUserPreferenceToggle
ModelDoc2.CreateLine2
ModelDoc2.ViewZoomtofit2
ModelDoc2.AddDimension2
FeatureManager.FeatureExtrusionThin
FeatureManager.FeatureRevolveThin
1.
2.
3.
4.
5.
141
Exercise 8:
API Fundamentals
Solution
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
142
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
API Fundamentals
Do
Lesson 5
Assembly Automation
143
Lesson 5
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Assembly Automation
144
API Fundamentals
Lesson 5
Assembly Automation
Do
Note
This macro is designed to explore the various API calls associated with
adding components to an assembly. It demonstrates positioning,
mating, face traversal, creating object collections and the use of safe
entities.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Case Study:
Automation
Tool for
Assemblies
145
Lesson 5
API Fundamentals
Assembly Automation
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
I
I
I
I
I
I
Do
Tip
146
API Fundamentals
Lesson 5
Assembly Automation
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
I
I
Answer
Do
Question
147
Lesson 5
API Fundamentals
Assembly Automation
Transforms
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Creating
MathTransforms
MathUtility::CreateTransform
Return:
Input:
retval
ArrayData
Do
The
Transformation
Matrix
Tip
148
API Fundamentals
Lesson 5
Assembly Automation
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Activating
Documents
SldWorks::ActivateDoc2
Return:
Input:
Input:
Output:
retval
Name
Silent
TRUE
Errors
Important!
Remember to turn this behavior off when the code completes. If this is
not done, the end user of the program will not see any of documents
that they open manually after the program runs.
Do
Invisible
Documents
149
Lesson 5
API Fundamentals
Assembly Automation
SldWorks::DocumentVisible
retval = SldWorks.DocumentVisible (visible, type)
Return:
void
Input:
visible
True
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Input:
type
Open component.
Establishing the
Curve and Edge
Collections
Do
Object Collections
This sub program traverses all the loops on the selected face. If the loop
is an inner loop then it returns an array of all of the edges belonging to
that loop. Then one by one, it checks each edge to see if it is a complete
circle. If it is, it then adds the edge object and it's corresponding curve
object to their appropriate collections.
These objects are used later to reselect faces for mating the control
knob, and to determine the position in the assembly that the knob
components will be added.
150
API Fundamentals
Lesson 5
Assembly Automation
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
Establishing the
Face Collection
The edge and curve collections are now established. A collection must
also be created to maintain pointers to the cylindrical faces that are
bounded by the circular edges. These faces are also needed later on to
help establish the concentric mate needed to mate the control button
concentrically to the hole in the chassis.
151
Lesson 5
API Fundamentals
Assembly Automation
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
I
I
I
I
I
I
Getting Adjacent
Faces
Edge::GetTwoAdjacentFaces
Output:
Face1
Output:
Face2
Do
152
API Fundamentals
Lesson 5
Assembly Automation
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Else
Set swTempSurf = swSurface2
Set swEntity = swFaces(1)
End If
If Not swTempSurf Is Nothing Then
'When the cylindrical Face is found....
Dim swSafeFace As SldWorks.entity
Set swSafeFace = swEntity.GetSafeEntity
SafeCylindricalFaceCollection.Add swSafeFace
End If
Next i
End Sub
Establishing the
Points Collection
Getting Curve
Parameters
Curve::CircleParams
retval = Curve.CircleParams ( )
Return:
retval
Do
When the center point is retrieved from the circular edge, it needs to be
multiplied by the target components transform (the chassis). If the
components origin is not aligned with the assemblys origin, the new
component will be placed at the wrong position in the assembly instead
of where the chassis component is actually located in the assembly.
Important!
When building the collection of center points, use the MathPoint object
from the MathUtility class. This object has a method for multiplying
the point location by the transform of the target component in the
assembly.
Remember that the points that are retrieved from the center location of
the circular edges are not in assembly space. These edges belong to the
chassis part model. The center points of these edges are relative to the
models origin, not the assembly origin.
153
Lesson 5
API Fundamentals
Assembly Automation
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
I
I
I
I
I
I
I
154
API Fundamentals
Lesson 5
Assembly Automation
Adding
Components
AssemblyDoc::AddComponent4
retval = AssemblyDoc.AddComponent2 (CompName, X, Y, Z)
retval
Input:
CompName
Input
Input:
Input:
Input:
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Return:
ConfigName
X
Adding Mates
AssemblyDoc::AddMate
swMateCOINCIDENT
swMateCONCENTRIC
swMatePERPENDICULAR
swMatePARALLEL
swMateTANGENT
swMateDISTANCE
swMateANGLE
swMateUNKNOWN
Align
swMateAlignALIGNED
swMateAlignANTI_ALIGNED
swMateAlignCLOSEST
Flip
TRUE
Input:
Dist
Input:
Angle
Input:
Input:
Do
Input:
155
Lesson 5
API Fundamentals
Assembly Automation
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
Review the following code in the Finalize sub program. This code
cleans up all the variables and resets the document visibility setting. By
setting the collections to nothing, this code can be run on another
selected face in the assembly without having to restart the macro.
Public Sub Finalize()
swApp.DocumentVisible True, swDocPART
Set swAssy = Nothing
Set CircularCurveCollection = Nothing
Set CircularEdgeCollection = Nothing
Set SafeCylindricalFaceCollection = Nothing
Set swModel = Nothing
Set PointCollection = Nothing
Set swSelFace = Nothing
Set swSelMgr = Nothing
Set swApp = Nothing
Me.Hide
End Sub
156
API Fundamentals
Exercise 9:
Adding Components
Exercise 9:
Adding
Components
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Correct
positions
Incorrect
component
positions
Objective
Skills Learned
Procedure
Debugging transforms.
Do
4. Debug the macro and step through the code line by line to
understand it.
5. Delete control knobs when finished and return to macro.
6. Comment out the following lines:
Set swMathPoint = swMathPoint.MultiplyTransform _
(swCompTransform)
swAssy.AddMate swMateCOINCIDENT, 0, False, 0, 0
swAssy.AddMate swMateCONCENTRIC, 1, False, 0, 0
7. Save the macro and debug it again to see why the transformations
are important when adding components to an assembly.
157
Exercise 9:
API Fundamentals
Adding Components
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Solution
Do
158
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
API Fundamentals
Lesson 6
Drawing Automation
Do
159
Lesson 6
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Drawing Automation
160
API Fundamentals
Lesson 6
Drawing Automation
Case Study:
Automating
Drawing
Creation
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
With Cut
Without Cut
Do
Use the intrinsic VBA MsgBox function to prompt the user for the
projection type.
Dim Response As Integer
Dim ThirdAngle As Boolean
Sub main()
Response = MsgBox("Create third angle projection?", vbYesNo)
If Response = vbYes Then
ThirdAngle = True
Else
ThirdAngle = False
End If
161
Lesson 6
API Fundamentals
Drawing Automation
The first two values get passed to the method used to create a new
drawing document.
The second two values are used when creating new sheets on the
drawing.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
swApp As SldWorks.SldWorks
swModel As SldWorks.ModelDoc2
Response As Integer
ThirdAngle As Boolean
Sub main()
Response = MsgBox("Create third angle projection?", vbYesNo)
If Response = vbYes Then
ThirdAngle = True
Else
ThirdAngle = False
End If
swApp As SldWorks.SldWorks
swModel As SldWorks.ModelDoc2
Response As Integer
ThirdAngle As Boolean
swDraw As SldWorks.DrawingDoc
Do
Sub main()
Response = MsgBox("Create third angle projection?", vbYesNo)
If Response = vbYes Then
ThirdAngle = True
Else
ThirdAngle = False
End If
Note
162
API Fundamentals
Lesson 6
Drawing Automation
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Getting
Configuration
Names
ModelDoc2::GetConfigurationNames
retval = ModelDoc2.GetConfigurationNames ( )
Return:
retval
Do
Add variables that store the assembly configuration names. Then add
code to set up a loop that traverses them.
Dim ConfigNamesArray As Variant
Dim ConfigName As Variant
Dim i As Long
Sub main()
Response = MsgBox("Create third angle projection?", vbYesNo)
If Response = vbYes Then
ThirdAngle = True
Else
ThirdAngle = False
End If
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swDraw = swApp.NewDocument(TemplateName, PaperSize, _
0#, 0#)
ConfigNamesArray = swModel.GetConfigurationNames
For i = 0 To UBound(ConfigNamesArray)
ConfigName = ConfigNamesArray(i)
Next i
End Sub
163
Lesson 6
API Fundamentals
Drawing Automation
Creating Sheets
DrawingDoc::NewSheet3
retval = DrawingDoc.NewSheet3 (Name, PaperSize, TemplateIn, Scale1, Scale2,
FirstAngle, TemplateName, Width, Height, PropertyViewName)
Return:
retval
TRUE
Input:
Name
PaperSize
swDwgPaperAsize
swDwgPaperAsizeVertical
swDwgPaperBsize
swDwgPaperCsize
swDwgPaperDsize
swDwgPaperEsize
swDwgPaperA4size
swDwgPaperA4sizeVertical
swDwgPaperA3size
swDwgPaperA2size
swDwgPaperA1size
swDwgPaperA0size
swDwgPapersUserDefined
TemplateIn
swDwgTemplateAsize
swDwgTemplateAsizeVertical
swDwgTemplateBsize
swDwgTemplateCsize
swDwgTemplateDsize
swDwgTemplateEsize
swDwgTemplateA4size
swDwgTemplateA4sizeVertical
swDwgTemplateA3size
swDwgTemplateA2size
swDwgTemplateA1size
swDwgTemplateA0size
swDwgTemplateCustom
swDwgTemplateNone
Scale1
Scale numerator.
Scale2
Scale denominator.
Input:
Input:
Do
Input:
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Input:
Input:
FirstAngle
TRUE
Input:
TemplateName
Input:
Width
Input:
Height
Input:
PropertyViewName
164
API Fundamentals
Lesson 6
Drawing Automation
Add some more variables that are used for creating the new sheets on
the drawing.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
swApp As SldWorks.SldWorks
swModel As SldWorks.ModelDoc2
Response As Integer
ThirdAngle As Boolean
swDraw As SldWorks.DrawingDoc
ConfigNamesArray As Variant
ConfigName As Variant
i As Long
retval As Boolean
For i = 0 To UBound(ConfigNamesArray)
ConfigName = ConfigNamesArray(i)
retval = swDraw.NewSheet3(ConfigName, TemplateSize, _
PaperSize, ScaleNum, ScaleDenom, Not ThirdAngle, "", _
0#, 0#, "")
Next i
End Sub
Notice that new tabs are created for each new drawing sheet.
Do
165
Lesson 6
API Fundamentals
Drawing Automation
Creating Views
DrawingDoc::Create1stAngleViews2
retval = DrawingDoc.Create1stAngleViews2 (modelName)
DrawingDoc::Create3rdAngleViews2
Return:
Input:
Tip
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
TRUE
modelName
There are two API methods that could be used to pass the name of the
document to the first parameter of this method. ModelDoc2::GetTitle,
and ModelDoc2::GetFullPathName. The latter is the better choice.
Depending on what operating system this macro runs,
ModelDoc2::GetTitle may not always return the extension part of the
file name. If the extension part of the file name is not found,
DrawingDoc::Create1stAngleViews2 will fail.
Do
166
Sub main()
Response = MsgBox("Create third angle projection?", vbYesNo)
If Response = vbYes Then
ThirdAngle = True
Else
ThirdAngle = False
End If
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swDraw = swApp.NewDocument(TemplateName, PaperSize, _
0#, 0#)
ConfigNamesArray = swModel.GetConfigurationNames
For i = 0 To UBound(ConfigNamesArray)
ConfigName = ConfigNamesArray(i)
retval = swDraw.NewSheet3(ConfigName, TemplateSize, _
PaperSize, ScaleNum, ScaleDenom, Not ThirdAngle, "", _
0#, 0#, "")
If ThirdAngle = True Then
retval = swDraw.Create3rdAngleViews2(swModel.GetPathName)
Else
retval = swDraw.Create1stAngleViews2(swModel.GetPathName)
End If
Next i
End Sub
API Fundamentals
Lesson 6
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Drawing Automation
Inserting
Annotations
DrawingDoc::InsertModelAnnotations3
Return:
Input:
Input
option
types
allViews
Do
Input:
Variant
Input:
duplicateDims
Input
hiddenFeatureDims
Input
usePlacementInSketch
Input
167
Lesson 6
API Fundamentals
Drawing Automation
Add the code to insert the dimensions and annotations from the
underlying assembly model.
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Sub main()
Response = MsgBox("Create third angle projection?", vbYesNo)
If Response = vbYes Then
ThirdAngle = True
Else
ThirdAngle = False
End If
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swDraw = swApp.NewDocument(TemplateName, PaperSize, _
0#, 0#)
ConfigNamesArray = swModel.GetConfigurationNames
For i = 0 To UBound(ConfigNamesArray)
ConfigName = ConfigNamesArray(i)
retval = swDraw.NewSheet3(ConfigName, TemplateSize, _
PaperSize, ScaleNum, ScaleDenom, Not ThirdAngle, "", _
0#, 0#, "")
If ThirdAngle = True Then
retval = swDraw.Create3rdAngleViews2(swModel.GetPathName)
Else
retval = swDraw.Create1stAngleViews2(swModel.GetPathName)
End If
swDraw.InsertModelAnnotations3 0, _
SwConst.swInsertDimensionsMarkedForDrawing + _
SwConst.swInsertNotes, True, True, True, False
Next i
End Sub
168
API Fundamentals
Lesson 6
Drawing Automation
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Traversing
Drawing Views
Do
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Dim
swApp As SldWorks.SldWorks
swModel As SldWorks.ModelDoc2
Response As Integer
ThirdAngle As Boolean
swDraw As SldWorks.DrawingDoc
ConfigNamesArray As Variant
ConfigName As Variant
i As Long
retval As Boolean
swView As SldWorks.view
Sub main()
Response = MsgBox("Create third angle projection?", vbYesNo)
If Response = vbYes Then
ThirdAngle = True
Else
ThirdAngle = False
End If
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swDraw = swApp.NewDocument(TemplateName, PaperSize, _
0#, 0#)
ConfigNamesArray = swModel.GetConfigurationNames
For i = 0 To UBound(ConfigNamesArray)
ConfigName = ConfigNamesArray(i)
retval = swDraw.NewSheet3(ConfigName, TemplateSize, _
PaperSize, ScaleNum, ScaleDenom, Not ThirdAngle, "", _
0#, 0#, "")
If ThirdAngle = True Then
retval = swDraw.Create3rdAngleViews2(swModel.GetPathName)
Else
retval = swDraw.Create1stAngleViews2(swModel.GetPathName)
End If
retval = swDraw.InsertModelAnnotations(0, False, _
swConst.swInsertDimensions + swConst.swInsertNotes, _
True)
Set swView = swDraw.GetFirstView
Do While Not swView Is Nothing
swView.ReferencedConfiguration = ConfigName
Set swView = swView.GetNextView
Loop
swDraw.ForceRebuild
Next i
End Sub
169
Lesson 6
API Fundamentals
Drawing Automation
Saving Drawings
in Different
Formats
ModelDoc2::SaveAs4
Return:
Input:
Input
Input
Output
Output
Note
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Name
Version
Options
Errors
Warnings
In the preceding table, the last two parameters are Output parameters.
These output parameters are used to trouble shoot the code if this
method fails. When using output parameters, the variables used to
catch their values must be declared before calling the method. If they
are not declared, the program will return a Type-mismatch error when
this method is called.
Do
swApp As SldWorks.SldWorks
swModel As SldWorks.ModelDoc2
Response As Integer
ThirdAngle As Boolean
swDraw As SldWorks.DrawingDoc
ConfigNamesArray As Variant
ConfigName As Variant
i As Long
retval As Boolean
170
API Fundamentals
Lesson 6
Drawing Automation
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
For i = 0 To UBound(ConfigNamesArray)
ConfigName = ConfigNamesArray(i)
retval = swDraw.NewSheet3(ConfigName, TemplateSize, _
PaperSize, ScaleNum, ScaleDenom, Not ThirdAngle, "", _
0#, 0#, "")
If ThirdAngle = True Then
retval = swDraw.Create3rdAngleViews2(swModel.GetPathName)
Else
retval = swDraw.Create1stAngleViews2(swModel.GetPathName)
End If
retval = swDraw.InsertModelAnnotations(0, False, _
swConst.swInsertDimensions + swConst.swInsertNotes, _
True)
Set swView = swDraw.GetFirstView
Do While Not swView Is Nothing
swView.ReferencedConfiguration = ConfigName
Set swView = swView.GetNextView
Loop
swDraw.ForceRebuild
swDraw.SaveAs4 SaveAsPath & ConfigName & ".DXF", _
0, 0, errors, warnings
swDraw.SaveAs4 SaveAsPath & ConfigName & ".DWG", _
0, 0, errors, warnings
swDraw.SaveAs4 SaveAsPath & ConfigName & ".JPG", _
0, 0, errors, warnings
swDraw.SaveAs4 SaveAsPath & ConfigName & ".TIF", _
0, 0, errors, warnings
Next i
Do
Also navigate to the export directory and open the files that were saved
with the SaveAs4 method.
Configuration = Cut
Configuration = No Cut
Running the macro creates the new drawing sheets for each configuration.
171
Lesson 6
API Fundamentals
Drawing Automation
Drawing Commands
CreateAuxiliaryViewAt3
CreateDetailViewAt3
CreateBreakoutSection
CreateSectionView
UpdateViewDisplayGeometry
CreateSectionViewAt4
InsertHatchedFace
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Create1stAngleViews
Create3rdAngleViews
CreateDrawViewFromModelView
Annotation Commands
CreateText2
InsertNote
InsertCenterMark2
InsertSurfaceFinishSymbol2
InsertCenterLine
NewGtol
AddHoleCallout2
InsertBOMBalloon2
InsertCosmeticThread
ShowCosmeticThread
HideCosmeticThread
InsertDatumTargetSymbol
InsertStackedBalloon
InsertWeldSymbol
InsertMultiJogLeader
InsertBlock
InsertDowelSymbol
InsertModelAnnotations
InsertModelDimensions
Do
Layer Commands
CreateLayer
ChangeComponentLayer
SetCurrentLayer
HideEdge
SetLineWidth
ShowEdge
SetLineStyle
172
API Fundamentals
Exercise 10:
Drawing Automation
Exercise 10:
Drawing
Automation
Objective
Write a drawing
automation macro using
the techniques and
methods from the case
study.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Skills Learned
Do
APIs Used
SldWorks.NewDocument
ModelDoc2.GetConfigurationNames
DrawingDoc.NewSheet3
DrawingDoc.Create1stAngleViews2
DrawingDoc.Create3rdAngleViews2
DrawingDoc.CreateDrawViewFromModelView
DrawingDoc.ViewDisplayShaded
DrawingDoc.InsertModelAnnoatations
DrawingDoc.GetFirstView
View.ReferencedConfiguration
DrawingDoc.GetNextView
DrawingDoc.ForceRebuild
---- Challenge #1 ---DrawDoc.ActivateSheet
DrawDoc.GetCurrentSheet
Sheet.SetName
---- Challenge #2 ---ModelDoc2.SaveAs4
Procedure
1.
2.
3.
4.
Open AutomationDrawings.sldasm.
Open AutomationDrawings.swp.
Use the APIs listed above to automate the drawing creation.
Save and run macro.
173
Exercise 10:
API Fundamentals
Drawing Automation
Solution
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Sub main()
Response = MsgBox("Create third angle projection?", vbYesNo)
If Response = vbYes Then
ThirdAngle = True
Else
ThirdAngle = False
End If
Do
174
API Fundamentals
Exercise 10:
Drawing Automation
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
swDraw.SaveAs4 SaveAsPath
errors, warnings
swDraw.SaveAs4 SaveAsPath
errors, warnings
swDraw.SaveAs4 SaveAsPath
errors, warnings
swDraw.SaveAs4 SaveAsPath
errors, warnings
Next i
End Sub
175
Exercise 10:
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Drawing Automation
176
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
API Fundamentals
Do
Lesson 7
Selection and Traversal
Techniques
Traverse features.
Traverse geometry.
177
Lesson 7
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
178
API Fundamentals
Lesson 7
Selection and Traversal Techniques
Case Study:
Programming
With a Selected
Object
This macro
demonstrates how to
access and modify the
data specific to
certain features in a
part file.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
179
Lesson 7
API Fundamentals
SelectionManager
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Accessing the
Selection Manager
ModelDoc2::SelectionManager
SelectionMgr = ModelDoc2.SelectionManager
Output:
SelectionMgr
Counting Selected
Objects
SelectionMgr::GetSelectedObjectCount
retval = SelectionMgr.GetSelectedObjectCount ( )
Return:
retval
Do
180
API Fundamentals
Lesson 7
Selection and Traversal Techniques
Accessing
Selected Objects
SelectionMgr::GetSelectedObject5
retval = SelectionMgr.GetSelectedObject5 (AtIndex)
retval
Input:
AtIndex
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Return:
SelectionMgr::GetSelectObjectCount
Getting Selected
Object Types
SelectionMgr::GetSelectedObjectType2
Note: If the object returned is a feature, use Feature::GetTypeName for determining the feature
type.
Return:
Input:
retval
AtIndex
Getting Feature
Type Names
Feature::GetTypeName
retval = Feature.GetTypeName ( )
retval
Do
Return:
181
Lesson 7
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Feature Data
Objects
Accessing the
Feature Data
Object
Feature::GetDefinition
retval = Feature.GetDefintion ( )
Return:
retval
Do
Accessing
Selections
To allow access to the entities used to create the feature, use the
FeatureData::AccessSelections method from any of the FeatureData
types. Because this method puts the model into a rollback state, use it
only when you need to access the entity selections used to create the
feature. It is not needed to change simple exposed properties on a
FeatureData object.
ExtrudeFeatureData2::AccessSelections
accessGained = ExtrudeFeatureData2.AccessSelections (TopDoc, Component)
Return:
accessGained
TRUE
FALSE
Input:
TopDoc
Top-level document.
Input:
Component
182
API Fundamentals
Lesson 7
Selection and Traversal Techniques
Releasing
Selections
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
ExtrudeFeatureData2::ReleaseSelectionAccess
void ExtrudeFeatureData2.ReleaseSelectionAccess ( )
Return:
void
No return value.
Do
Modifying Feature
Data Properties
183
Lesson 7
API Fundamentals
Feature::ModifyDefinition
retval = Feature.ModifyDefinition (Definition, TopDoc, Component)
Return:
retval
TRUE
Input:
Input:
Input:
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
not.
Definition
TopDoc
Top-level document.
Component
Add the following code entries to modify the depth of the extruded
feature.
Do
184
Factor = CInt(txtDepth.Text)
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swSelMgr = swModel.SelectionManager
count = swSelMgr.GetSelectedObjectCount
If count > 1 Then
swApp.SendMsgToUser2 "Please select only Extrude1.", _
swMbWarning, swMbOk
Me.Hide
Exit Sub
End If
Set Feature = swSelMgr.GetSelectedObject5(count)
If Not Feature.GetTypeName = swTnExtrusion Then
swApp.SendMsgToUser2 "Please select the Extrude1.", _
swMbWarning, swMbOk
Exit Sub
End If
Set ExtrudeFeatureData = Feature.GetDefinition
Depth = ExtrudeFeatureData.GetDepth(True)
ExtrudeFeatureData.SetDepth True, Depth * Factor
retval = Feature.ModifyDefinition _
(ExtrudeFeatureData, swModel, Nothing)
End Sub
API Fundamentals
Lesson 7
Selection and Traversal Techniques
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Enter 5 in the
multiplication factor
text box and click the
Generate button.
The SolidWorks
BREP Model
Do
185
Lesson 7
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
The Face2 object is a topology object. All of the Face2 object members
return data about the topology of this object and nothing about the
actual sizes of the surface that the face surrounds. To get the actual
geometrical data from the face, a programmer would call the accessor
Face2::GetSurface to return a pointer to the underlying surface. The
programmer could then use a method such as
Surface::GetBSurfaceParams or Surface::EvaluateAtPoint to discover
the actual shape of this geometrical object.
The objects in the diagram are listed in the order in which a
programmer would have to connect to them. A programmer would first
have to connect to a Body pointer before they could connect to a Face
pointer. The Body object has an accessor method called
Body::GetFirstFace that would return a Face pointer to the first face
encountered on the body. The Face pointer has an accessor method
called Face::GetNextFace that returns a pointer to the next face on the
body. Combining these methods in a loop structure would allow the
programmer to traverse all the faces on a body. This technique could be
used on the other BREP objects as well.
Tip
Keep in mind that there are accessors on several of these BREP objects
that will allow a programmer to side step some of the traversing. For
instance, to traverse to the edges of a face, a programmer does not have
to get a pointer to every object above it in the diagram before they can
finally work with an edge pointer. The Face2 object has an accessor
method named Face2::GetEdges. This method will return a list of all
the edges on the face. Although all the objects above the edge object
have a special purpose, there are times where it would not be necessary
to access all these objects just to get a pointer to the edge of a face.
Do
Traversing
Topology and
Geometry
186
API Fundamentals
Lesson 7
Selection and Traversal Techniques
Case Study:
Body and Face
Traversal
This next macro traverses all the faces of a part (single or multibody)
and modifies the color properties on each face. It does not require the
user to select a face in order to run. Face traversal techniques are
important in many areas of API programming, including:
I
I
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
I
I
Do
187
Lesson 7
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Returning a List of
Body Pointers
PartDoc::GetBodies2
Return:
Input:
BodyType
VisibleOnly
TRUE
Do
Input:
retval
188
API Fundamentals
Lesson 7
Selection and Traversal Techniques
swApp As SldWorks.SldWorks
swModel As SldWorks.ModelDoc2
swPart As SldWorks.PartDoc
retval As Variant
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Sub main()
Set swApp = Application.SldWorks
If Not swApp Is Nothing Then
Set swModel = swApp.ActiveDoc
If Not swModel Is Nothing Then
Set swPart = swModel
If Not swPart Is Nothing Then
retval = swPart.GetBodies2(swConst.swSolidBody, True)
End If
Set swPart = Nothing
End If
Set swModel = Nothing
End If
Set swApp = Nothing
End Sub
Dim
Dim
Dim
Dim
Dim
Dim
Do
swApp As SldWorks.SldWorks
swModel As SldWorks.ModelDoc2
swPart As SldWorks.PartDoc
retval As Variant
i As Integer
swFace As SldWorks.face2
Sub main()
Set swApp = Application.SldWorks
If Not swApp Is Nothing Then
Set swModel = swApp.ActiveDoc
If Not swModel Is Nothing Then
Set swPart = swModel
If Not swPart Is Nothing Then
retval = swPart.GetBodies2(swSolidBody, True)
For i = 0 To UBound(retval)
Set swFace = retval(i).GetFirstFace
Do While Not swFace Is Nothing
Loop
Next i
End If
Set swPart = Nothing
End If
Set swModel = Nothing
End If
Set swApp = Nothing
End Sub
189
Lesson 7
API Fundamentals
Face Material
Properties
Face2::MaterialPropertyValues
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Output:
MaterialPropertyValues
Red
Green
Blue
Ambient
Diffuse
Specular
Shininess
Transparency
Emission
Do
Dim
Dim
Dim
Dim
Dim
Dim
Dim
190
API Fundamentals
Lesson 7
Selection and Traversal Techniques
Then add the code to pass the array to the current face.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Sub main()
Set swApp = Application.SldWorks
If Not swApp Is Nothing Then
Set swModel = swApp.ActiveDoc
If Not swModel Is Nothing Then
Set swPart = swModel
If Not swPart Is Nothing Then
retval = swPart.GetBodies2(swConst.swSolidBody, True)
For i = 0 To UBound(retval)
Set swFace = retval(i).GetFirstFace
matProps(0) = 1
matProps(1) = 0
matProps(2) = 0
matProps(3) = 1
matProps(4) = 1
matProps(5) = 0.3
matProps(6) = 0.3
matProps(7) = 0
matProps(8) = 0
Do While Not swFace Is Nothing
swFace.MaterialPropertyValues = ((matProps))
Loop
Next i
End If
Set swPart = Nothing
End If
Set swModel = Nothing
End If
Set swApp = Nothing
End Sub
Notice when passing the material property values to the face in the
code above, that the variant value matProps is enclosed in double
parentheses. When passing an array in VBA to a SolidWorks method, it
should be enclosed in double parentheses. If not, an exception could be
thrown.
Important!
Do
191
Lesson 7
API Fundamentals
Case Study:
Feature
Manager
Traversal
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
This macro traverses the FeatureManager design tree and retrieves each
features screen and type name. The code sets each features
suppression and user interface visibility states. It also highlights how to
traverse each feature from the top of the feature manager to the bottom.
Finally it demonstrates how to obtain a feature from a specific
FeatureManager position.
Do
Traversing the
FeatureManager
from the Top
To traverse the FeatureManager tree from the top, set up a loop. Before
entering the loop, use the method ModelDoc2::FirstFeature to return a
pointer to the first feature in the FeatureManager design tree.
ModelDoc2:FirstFeature
retval = ModelDoc2.FirstFeature ( )
Return:
192
retval
API Fundamentals
Lesson 7
Selection and Traversal Techniques
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Return:
Sub main()
Set swApp = Application.SldWorks
If Not swApp Is Nothing Then
Set swModel = swApp.ActiveDoc
If Not swModel Is Nothing Then
Set swFeature = swModel.FirstFeature
While Not swFeature Is Nothing
Set swFeature = swFeature.GetNextFeature
Wend
End If
Set swModel = Nothing
End If
Set swApp = Nothing
End Sub
Tip
When possible, use type names rather than screen names. This ensures
that the program will function for different localized versions of
SolidWorks (where features may have different screen names). The
type names for these versions, can not be modified.
Do
Displaying Feature
Names and Types
swApp As SldWorks.SldWorks
swModel As SldWorks.ModelDoc2
swFeature As SldWorks.feature
FeatName As String
FeatType As String
193
Lesson 7
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Sub main()
Set swApp = Application.SldWorks
If Not swApp Is Nothing Then
Set swModel = swApp.ActiveDoc
If Not swModel Is Nothing Then
Set swFeature = swModel.FirstFeature
While Not swFeature Is Nothing
FeatName = swFeature.Name
FeatType = swFeature.GetTypeName
MsgBox "Feature screen name = " & FeatName & vbCrLf & _
"Feature type name = " & FeatType
Set swFeature = swFeature.GetNextFeature
Wend
End If
Set swModel = Nothing
End If
Set swApp = Nothing
End Sub
Notice that sketch names are returned before their parent features. The
Feature traversal returns the features in the chronological order that
they were created in the model. Therefore Sketch1 would be displayed
to the user before the Extrude1 feature.
Do
Note
Setting Feature
Suppression
Feature::SetSuppression
suppressSet = Feature.SetSuppression (suppressState)
Return:
suppressSet
TRUE
FALSE
Input:
194
suppressState
swSuppressFeature
swUnSuppressFeature
swUnSuppressDependent
API Fundamentals
Lesson 7
Selection and Traversal Techniques
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
195
Lesson 7
API Fundamentals
Setting Feature UI
State
Feature::SetUIState
Feature.SetUIState (StateType, Flag)
Input:
StateType
swIsHiddenInFeatureMgr
Input:
Flag
TRUE
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Edit the code to hide all of the features in the FeatureManager design
tree.
Do
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Dim
swApp As SldWorks.SldWorks
swModel As SldWorks.ModelDoc2
swFeature As SldWorks.feature
FeatName As String
FeatType As String
swSubFeature As SldWorks.feature
SubFeatName As String
SubFeatType As String
Sub main()
Set swApp = Application.SldWorks
If Not swApp Is Nothing Then
Set swModel = swApp.ActiveDoc
If Not swModel Is Nothing Then
Set swFeature = swModel.FirstFeature
While Not swFeature Is Nothing
swFeature.SetUIState swConst.swIsHiddenInFeatureMgr, _
True
Set swFeature = swFeature.GetNextFeature
Wend
swModel.ForceRebuild
End If
Set swModel = Nothing
End If
Set swApp = Nothing
End Sub
196
API Fundamentals
Lesson 7
Selection and Traversal Techniques
Obtaining a
Feature by
FeatureManager
Position
ModelDoc2::FeatureByPositionReverse
Return:
Input:
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
PositionFromEnd
11 Modify code.
Sub main()
Set swApp = Application.SldWorks
If Not swApp Is Nothing Then
Set swModel = swApp.ActiveDoc
If Not swModel Is Nothing Then
Set swFeature = swModel.FeatureByPositionReverse(2)
FeatName = swFeature.Name
FeatType = swFeature.GetTypeName
MsgBox "Feature screen name = " & FeatName & vbCrLf & _
"Feature type name = " & FeatType
Set swModel = Nothing
End if
Set swApp = Nothing
End If
End Sub
Do
13 Exit macro.
197
Lesson 7
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
198
API Fundamentals
Exercise 11:
Handling Preselection 1
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Exercise 11:
Handling
Preselection 1
Objective
Skills Learned
Do
APIs Used
Procedure
ModelDoc2.SelectionManager
SelectionMgr.GetSelectedObjectType2
SelectionMgr.GetSelectedObject5
Face2.GetSurface
1.
2.
3.
4.
Open bottomcase.sldprt.
Open DistanceBetweenFaces.swp.
Use the APIs listed above to handle the preselection.
Save and run macro.
199
Exercise 11:
API Fundamentals
Handling Preselection 1
Solution
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Sub main()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swSelMgr As SldWorks.SelectionMgr
Dim SelType1 As Long
Dim SelType2 As Long
Dim swFace1 As SldWorks.face2
Dim swFace2 As SldWorks.face2
Dim swSurf1 As SldWorks.surface
Dim swSurf2 As SldWorks.surface
Dim varSelPt1 As Variant
Dim varSelPt2 As Variant
Dim varClosePt1 As Variant
Dim varClosePt2 As Variant
Dim Dist1 As Double
Dim Dist2 As Double
Dim bRet As Boolean
Do
200
API Fundamentals
Exercise 12:
Handling Preselection 2
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Exercise 12:
Handling
Preselection 2
Objective
Skills Learned
ModelDoc2.SelectionManager
SelectionMgr.GetSelectedObjectCount
SelectionMgr.GetSelectedObjectType2
SelectionMgr.GetSelectedObject5
Edge.GetCurve
Procedure
1.
2.
3.
4.
Do
APIs Used
Open bottomcase.sldprt.
Open MultipleEdgeLength.swp.
Use the APIs listed above to handle the preselection.
Save and run macro.
201
Exercise 12:
API Fundamentals
Handling Preselection 2
Sub main()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swPart As SldWorks.PartDoc
Dim swSelMgr As SldWorks.SelectionMgr
Dim swSelObj As Object
Dim swEdge As SldWorks.Edge
Dim swCurve As SldWorks.Curve
Dim varCurveParams As Variant
Dim SelType As Long
Dim SelCount As Long
Dim Length As Double
Dim bRet As Boolean
Dim i As Long
Dim retval As Double
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Solution
For i = 1 To SelCount
SelType = swSelMgr.GetSelectedObjectType(i)
If swSelEDGES = SelType Then
Set swSelObj = swSelMgr.GetSelectedObject5(i)
Set swEdge = swSelObj
Set swCurve = swEdge.GetCurve
varCurveParams = swEdge.GetCurveParams2
retval = swCurve.GetLength(varCurveParams(6), _
varCurveParams(7))
Length = Length + retval
End If
Next i
Do
202
API Fundamentals
Exercise 13:
Traversing the FeatureManager
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Exercise 13:
Traversing the
FeatureManager
To learn how to traverse a part and all its features, identify a specific
feature type and compare a parameter to a constant value. This macro
shows how to a check fillet radius against a minimum value (5 mm).
APIs Used
PartDoc.FirstFeature
Feature.GetTypeName
Feature.GetDefinition
SimpleFilletFeatureData2.DefaultRadius
Feature.Select
SimpleFilletFeatureData2.FilletItemsCount
SimpleFilletFeatureData2.AccessSelections
Feature.ReleaseSelectionAccess
Feature.GetNextFeature
Do
Objective
Procedure
1.
2.
3.
4.
Open bottomcase.sldprt.
Open CheckFillet.swp.
Use the APIs listed above to handle the traversal.
Save and run macro.
203
Exercise 13:
API Fundamentals
Solution
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Sub main()
Dim swApp As SldWorks.SldWorks
Dim swPart As PartDoc
Dim swFeat As feature
Dim FilletData As Object
Dim FilletItem As Object
Dim FeatTypeName As String
Dim FilletCount As Long
Dim i As Long
Dim Radius As Double
Dim retval As Boolean
Dim SelFeat As Boolean
204
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
API Fundamentals
Lesson 8
Adding Custom Properties
and Attributes
Do
205
Lesson 8
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
206
API Fundamentals
Lesson 8
Adding Custom Properties and Attributes
Case Study:
Custom
Properties
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
End Sub
207
Lesson 8
API Fundamentals
Adding Custom
Properties to a
SolidWorks
Document
ModelDoc2::AddCustomInfo3
Return:
Input:
Input:
Input:
Input:
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
TRUE
Configuration
FieldName
FieldType
swCustomInfoUnknown
swCustomInfoText
swCustomInfoDate
swCustomInfoNumber
swCustomInfoYesOrNo
FieldValue
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
swModel.AddCustomInfo3 , MyTest, swCustomInfoText, _
This is a test.
End Sub
The property list displays the new property name, type and value.
Do
208
API Fundamentals
Lesson 8
Adding Custom Properties and Attributes
Setting and
Getting Custom
Property Values
ModelDoc2::CustomInfo2
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Remarks: File custom property information is stored in the document file. It may be general to
the file, in which case there is a single value whatever the models configuration. It may also be
configuration specific, in which case a different value may be set for each configuration.
To access a general custom property information, the configuration argument should be set as
an empty string.
Output:
value
Input:
Configuration
FieldName
Input:
Do
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
swModel.AddCustomInfo3 , MyTest, swCustomInfoText, _
This is a test.
Retrieve the value of a custom property called MyTest
value = swModel.CustomInfo2("", "MyTest")
swApp.SendMsgToUser value
Change the value of a custom property called MyTest
value = Test has now changed!
swModel.CustomInfo2("", "MyTest") = value
swApp.SendMsgToUser swModel.CustomInfo2(, MyTest)
End Sub
Original Setting
Modified Setting
209
Lesson 8
API Fundamentals
Getting Custom
Property Names
ModelDoc2::GetCustomInfoNames2
retval = ModelDoc2.GetCustomInfoNames2 (Configuration)
Input:
retval
Configuration
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Return:
Getting the
Custom Property
Count
ModelDoc2::GetCustomInfoCount2
Output:
count
Input:
Configuration
Modify code.
Change the code to add multiple properties and then return their names
to the user.
Do
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
swModel.AddCustomInfo3 "", "MyProp1",
swModel.AddCustomInfo3 "", "MyProp2",
swModel.AddCustomInfo3 "", "MyProp3",
swModel.AddCustomInfo3 "", "MyProp4",
swCustomInfoNumber,
swCustomInfoNumber,
swCustomInfoNumber,
swCustomInfoNumber,
"1"
"2"
"3"
"4"
210
API Fundamentals
Lesson 8
Adding Custom Properties and Attributes
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Case Study:
Configurations
With Custom
Properties
Do
Note
After running the macro, a user can examine the configuration specific
custom properties as shown in the diagram above.
Because the geometry of the model is different for each configuration,
the values of the properties will also be different for each configuration.
211
Lesson 8
API Fundamentals
Open part.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Open macro.
The code returns the list of configuration names and displays them to
the user.
Do
212
API Fundamentals
Lesson 8
Adding Custom Properties and Attributes
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Returning Mass
Properties From a
SolidWorks Model
To return the mass properties from a model with the SolidWorks API,
Use the ModelDoc2::Extension::GetMassProperties method. The mass
properties are returned from this method in an array of doubles. The
mass properties will be gathered from the model and four of these
values (density, mass, volume and area) will be added to configuration
specific custom properties on the model.
ModelDocExtension::GetMassProperties
Do
Output
Input
Accuracy
0 = as is
1 = default
2 = maximum
Output:
status
213
Lesson 8
API Fundamentals
Add the following code to return the mass properties from the model
and store them in configuration specific custom properties.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
swModel.AddCustomInfo3 retval(i), _
"Volume - " & retval(i), _
swConst.swCustomInfoText, _
Format(massprops(3) * 1000 * 1000, "###0.000000")
swModel.AddCustomInfo3 retval(i), _
"Area - " & retval(i), _
swConst.swCustomInfoText, _
Format(massprops(4) * 100 * 100, "###0.000000")
Next
End Sub
Do
Note
214
API Fundamentals
Lesson 8
Adding Custom Properties and Attributes
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
2.70 g/cm3
Mass:
96.20 g
Volume:
35.63 cm3
Area:
405.63 cm2
Configuration: 3 Hole
Density:
2.70 g/cm3
Mass:
95.99 g
Volume:
35.55 cm3
Area:
405.08 cm2
Configuration: 4 Hole
Density:
2.70 g/cm3
Mass:
95.78 g
Do
Volume:
35.47 cm3
Area:
404.51 cm2
215
Lesson 8
API Fundamentals
The first tab of the file properties dialog in SolidWorks displays the
summary information. The API can be used to get or set this
information also. To view this page, from the SolidWorks File menu
click Properties... and then click the Summary tab on the dialog.
Adding Summary
Information
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Case Study:
File Summary
Information
ModelDoc2::SummaryInfo
Return:
Input:
value
FieldId
The following code connects to the model and changes various fields
on the Summary Information page.
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim text As String
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
swModel.SummaryInfo(swConst.swSumInfoTitle) = _
"API Fundamentals"
text = swModel.SummaryInfo(swConst.swSumInfoTitle)
Do
swModel.SummaryInfo(swConst.swSumInfoSubject) = _
"Adding custom file summary information"
text = swModel.SummaryInfo(swConst.swSumInfoSubject)
swModel.SummaryInfo(swConst.swSumInfoAuthor) = _
"SolidWorks Training"
text = swModel.SummaryInfo(swConst.swSumInfoAuthor)
swModel.SummaryInfo(swConst.swSumInfoKeywords) = ""
text = swModel.SummaryInfo(swConst.swSumInfoKeywords)
swModel.SummaryInfo(swConst.swSumInfoComment) = _
"Use the ModelDoc2::SummaryInfo method to add summary _
information."
text = swModel.SummaryInfo(swConst.swSumInfoComment)
End Sub
216
API Fundamentals
Lesson 8
Adding Custom Properties and Attributes
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
The Summary Information tab reflects the changes made by the macro.
Do
Case Study:
Document
Attributes
217
Lesson 8
API Fundamentals
Important!
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Naming Attributes
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
End Sub
The Attribute
Objects
AttributeDef Object
Do
(swAttDef)
There are three SolidWorks objects used when creating and working
with custom attributes. These objects are highlighted in the tables
below.
The AttributeDef object (attribute definition), creates a container for
storing custom data. This object is used to describe the names of
each parameter in the attribute, their data type, and their default
values. To create a new AttributeDef object use the
SldWorks::DefineAttribute method.
Dim swAttDef As SldWorks.attributeDef
Set swAttDef = swApp.DefineAttribute (UniqueName)
AttributeDef Methods
.AddParameter (NameIn, Type, DefaultValue, Options)
.Register
.CreateInstance3 (Doc, Comp, Ent, NameIn, Options, CfgOption)
218
API Fundamentals
Lesson 8
Adding Custom Properties and Attributes
Attribute Object
(swAttr)
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Attribute Methods
.GetParameter (NameIn)
.GetName
.GetEntity
.GetBody
.Delete
Parameter Object
(swParam)
Parameter Methods
.GetName
.GetType
Do
The next steps of the case study define an attribute and register with it
with SolidWorks.
219
Lesson 8
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
The second parameter is set to Nothing. This means that the attribute is
created on the model document.
Dim swAttDef As SldWorks.attributeDef
Dim swAtt As SldWorks.Attribute
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swAttDef = swApp.DefineAttribute("pubMyDocAttributeDef")
swAttDef.AddParameter "MyFirstParameter", _
swConst.swParamTypeDouble, 10, 0
swAttDef.AddParameter "MySecondParameter", _
swConst.swParamTypeDouble, 20, 0
swAttDef.Register
Set swAtt = swAttDef.CreateInstance5(swModel, Nothing, _
"MyDocAttribute", 0, SwConst.swAllConfiguration)
End Sub
Note
Do
220
API Fundamentals
Lesson 8
Adding Custom Properties and Attributes
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Case Study:
Face Attributes
Exit macro.
Do
I
I
I
I
Feed Rate
Speed Rate
XPosition
YPosition
ZPosition
Hole Depth
Hole Diameter
221
Lesson 8
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
Important!
222
API Fundamentals
Lesson 8
Adding Custom Properties and Attributes
Finding the
Cylindrical Faces
and Attaching
Attributes
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Show the user form again and double-click on the button labeled
Generate Machining Info.
Do
223
Lesson 8
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
224
API Fundamentals
Lesson 8
Adding Custom Properties and Attributes
Displaying
Callouts in the
Model View
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Callout Object
(swCallOut)
Callout Members
.Label
.Target Style
.TextBox
Do
bRet = swAttParam.SetDoubleValue2(1.3, _
swConst.swAllConfiguration, "")
Dim swSelMgr As SldWorks.SelectionMgr
Set swSelMgr = swModel.SelectionManager
Dim swCallout As SldWorks.Callout
Set swCallout = swSelMgr.CreateCallout
swCallout.TargetStyle = _
swConst.swCalloutTargetStyle_e. _
swCalloutTargetStyle_Arrow
swCallout.Label = "MyFaceAttr" & j & _
" Feed=.002" & " Speed=250" & _
" X=" & Round(cylParams(0) / 0.0254, 2)
" Y=" & Round(cylParams(1) / 0.0254, 2)
" Z=" & Round(cylParams(2) / 0.0254, 2)
" DrillDia.=" & (cylParams(6) / 0.0254)
swFace.Select3 True, 0, swCallout
Set swAtt = Nothing
&
&
&
*
_
_
_
2
225
Lesson 8
API Fundamentals
All of the code for the Generate Machining Info button is now
established. No more code will be added to the project. However, the
Generate CNC Code button click event has code that will be reviewed.
The code in this event handler is used to format the CNC code. The part
of the code that the next step will focus on is gathering the parameter
values from the existing attributes on the model.
Types of Attribute
Traversal
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Tip
Display the user form in VBA and double-click on the button labeled
Generate CNC Code.
Do
Understand how the attributes are traversed and how the data is
extracted from the parameters.
Private Sub cmdGenerateCNCCode_Click()
Dim FirstPass As Boolean
FirstPass = True
Dim i As Integer
i = 0
swModel.ClearSelection2 (True)
Dim swFeature As SldWorks.feature
Set swFeature = swModel.FirstFeature
While Not swFeature Is Nothing
If swFeature.GetTypeName = "Attribute" Then
swFeature.Select2 True, 0
Set swAtt = swFeature.GetSpecificFeature
226
API Fundamentals
Lesson 8
Adding Custom Properties and Attributes
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
227
Lesson 8
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Examine the CNC code added to the list box on the user form.
Do
Take some time and debug the macro. Use break points, and step
through the button events line by line to gain a thorough understanding
of this project.
228
API Fundamentals
Lesson 8
Adding Custom Properties and Attributes
A Final Word
about Attributes
In these case studies, the attributes that were created are visible in the
FeatureManager design tree. In most cases programmers will want to
hide attributes from the users of their programs. The
AttributeDef::CreateInstance5 method allows the programmer to hide
the attribute by passing 1 to the fourth parameter of this method.
AttributeDef::CreateInstance5
Return:
Input:
Input
Input
Input
Input
retval
ownerDoc
ownerObj
nameIn
options
configurationOption
Do
Tip
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
229
Lesson 8
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
230
API Fundamentals
Exercise 14:
Adding Mass Properties as Custom Properties
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Exercise 14:
Adding Mass
Properties as
Custom
Properties
Objective
Skills Learned
Do
APIs Used
Procedure
Handling configurations.
ModelDoc2.GetConfigurationNames
ModelDoc2.ShowConfiguration2
ModelDoc2.SetUserPreferenceIntegerValue
ModelDoc2.SetUserPreferenceStringValue
ModelDoc2.GetMassProperties
ModelDoc2.AddCustomInfo3
1.
2.
3.
4.
Open latchpin.sldprt.
Create a new macro named CustPropsMassProps.swp.
Use the APIs listed above to automate custom properties.
Save and run macro.
231
Exercise 14:
API Fundamentals
Solution
Option Explicit
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim retval() As String
Dim i As Integer
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
retval = swModel.GetConfigurationNames()
For i = 0 To UBound(retval)
swModel.ShowConfiguration2 retval(i)
swModel.SetUserPreferenceIntegerValue _
swConst.swUnitsLinear, swConst.swCM
Do
swModel.AddCustomInfo3 retval(i), _
"Density - " & retval(i), _
swConst.swCustomInfoText, _
Format(density / 1000, "###0.000000")
232
swModel.AddCustomInfo3 retval(i), _
"Volume - " & retval(i), _
swConst.swCustomInfoText, _
Format(massprops(3) * 1000 * 1000, "###0.000000")
Next
End Sub
API Fundamentals
Exercise 15:
Adding Attributes to Edges
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Exercise 15:
Adding
Attributes to
Edges
Objective
To traverse all the faces and edges of a part, looking for all the line type
curves. Use the method Curve::IsLine to determine the curve type.
If it is a line:
I
I
I
I
I
Skills Learned
I
I
I
I
Do
Traversing bodies.
Checking curve types.
Returning the length of a curve
Adding attribute information.
Adding callouts.
APIs Used
SldWorks.DefineAttribute
SldWorks.AddParameter
SldWorks.Register
PartDoc.GetBodies2
Body2.GetFirstFace
Body2.GetEdges
Edge.GetCurve
Curve.IsLine
AttributeDef.CreateInstance3
SelectionMgr.CreateCallout
Procedure
1. Open latchpin.sldprt.
2. Open the macro EdgeAttributes.swp.
3. Use the APIs listed above to automate adding edge attributes.
233
Exercise 15:
API Fundamentals
Option Explicit
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swPart As SldWorks.PartDoc
Dim swAttDef As SldWorks.attributeDef
Dim swAtt As SldWorks.Attribute
Dim swAttParam As SldWorks.Parameter
Dim retval As Variant
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim swFace As SldWorks.face2
Dim bRet As Boolean
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Solution
Do
234
API Fundamentals
Exercise 15:
Adding Attributes to Edges
linelength = i_curve.GetLength2(curveParams(6), _
curveParams(7))
linelength = Round(linelength, 5)
bRet = swAttParam.SetDoubleValue2(linelength,_
swConst.swAllConfiguration, "")
Dim swSelMgr As SelectionMgr
Set swSelMgr = swModel.SelectionManager
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
235
Exercise 15:
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
236
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
API Fundamentals
Lesson 9
The SolidWorks API SDK
Do
237
Lesson 9
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
238
API Fundamentals
Lesson 9
The SolidWorks API SDK
To use the SDK, download and run the setup program. Once it is
installed, the SolidWorks add-in wizards are available in Visual
Studio.NET or Visual Studio 6.0 depending on what programming
application options the user chooses.
Important!
This lesson will use Visual Studio.NET to create the add-ins since it is
the current development environment supported by Microsoft.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Open a web browser and navigate to the API Support download page.
It is located at the following URL:
http://www.solidworks.com/pages/services/APIDownloads.html
Do
On the API Support download page, click on the first link titled
SolidWorks API SDK 2006
239
Lesson 9
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Note
This dialog may vary depending on which Zip utility is installed on the
machine that the SDK is being setup on.
Continue with installation.
Click Next.
Do
240
API Fundamentals
Lesson 9
The SolidWorks API SDK
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
241
Lesson 9
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Important!
If the wrong versions of the add-in wizards are installed, they will not
work properly.
Do
242
API Fundamentals
Lesson 9
The SolidWorks API SDK
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
11 Click Next.
12 Click Install.
13 Installation Progress.
Do
243
Lesson 9
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Case Study:
Creating a
VB.NET Add-In.
C
Open Visual Studio.Net. Click File, New, Project... from the menu.
From the Project Types list box, choose the Visual Basic Projects
folder. Select SolidWorks VB.NET Addin from the Templates list.
Do
244
API Fundamentals
Lesson 9
The SolidWorks API SDK
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
The wizard creates a project with all the necessary code needed to
connect to SolidWorks. Several other helper classes have also been
created to manage event handling between the add-in and SolidWorks.
As an added bonus, all of the skeleton code needed to create and
implement a custom PropertyManager page is added.
245
Lesson 9
API Fundamentals
From the Visual Studio Build menu, click Build Solution. The project
should successfully compile.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
References
Do
Important!
246
If the wizard fails to create any of the references to any of the projects
required type libraries, follow steps 5 through 10 to manually create
them. If the project successfully compiled, then skip to step 11 to
continue with the case study.
API Fundamentals
Lesson 9
The SolidWorks API SDK
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
247
Lesson 9
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Important!
Do
248
API Fundamentals
Lesson 9
The SolidWorks API SDK
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Comparing Addin
DLLs and StandAlone Executables
There are two types of applications that can be created to interact with
SolidWorks.
I
I
Do
Note
249
Lesson 9
API Fundamentals
Loading and
Running an Add-in
Application
Tip
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
Important!
250
API Fundamentals
Lesson 9
The SolidWorks API SDK
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Tip
Do
251
Lesson 9
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Create Cube.
Do
Click OK.
Case Study:
Creating a C#
Add-in
252
17 Close SolidWorks.
API Fundamentals
Lesson 9
The SolidWorks API SDK
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
Important!
253
Lesson 9
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Create a Cube.
Do
254
API Fundamentals
Lesson 9
The SolidWorks API SDK
Case Study:
C++ Add-Ins
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
255
Lesson 9
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
On the left side of the wizard page, click the Options link.
Do
Leave the Threading options and the Interface check box set to their
default values.
256
API Fundamentals
Lesson 9
The SolidWorks API SDK
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Click Finish.
To get the C++ project to compile, The compiler needs to know where
the SolidWorks type libraries for the API are stored on the
development computer. A path will be added to the project properties
to tell the compiler where these type libraries exist.
Do
Compiling a C++
Add-In
257
Lesson 9
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
Click OK.
Note
258
This add-in wizard will try to set this path property automatically. If
this path does not match where SolidWorks is installed, the path
property will need to be redirected to where SolidWorks is located on
the development computer.
API Fundamentals
Lesson 9
The SolidWorks API SDK
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Once the project has successfully compiled, the add-in can be loaded
into SolidWorks. When the project compiled, a DLL was created in the
\Debug directory of your project. This file can be directly opened by
SolidWorks. In the diagram below, the DLL is named
SwAddin1.dll.
Do
This will enable all of the menu items that the add-in has created.
259
Lesson 9
API Fundamentals
menu.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Notice also that a toolbar was created by this add-in. Click any of the
buttons. Each time you click a button, another instance of Notepad is
created.
13 Close SolidWorks.
Do
Debugging the
C++ Add-in
260
API Fundamentals
Lesson 9
The SolidWorks API SDK
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
The source code file is opened and the cursor is set on the first line of
this method.
Do
Click in the margin next to the method call to create a break point.
261
Lesson 9
API Fundamentals
17 Start debugging.
Note
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Enter the path for where the SldWorks.exe file resides on the
development computer.
Do
262
API Fundamentals
Lesson 9
The SolidWorks API SDK
Choosing a
Programming
Language
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
There are no exercises for this lesson. The remaining lessons will
continue using VB.NET as the programming language.
263
Lesson 9
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
264
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
API Fundamentals
Lesson 10
Customizing the SolidWorks
User Interface
Do
265
Lesson 10
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
266
API Fundamentals
Lesson 10
Customizing the SolidWorks User Interface
Case Study:
Customizing
the UI With
VB.NET
Note
*PropertyManager pages
*Menus and sub-menus
*Toolbars
*Pop-up menus
*FeatureManager pages
Model views
Status bar
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
The * in the list is an indication that these items can only be properly
implemented in an add-in application. These items are not suited for
stand-alone applications.
Do
Click OK.
267
Lesson 10
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
This file contains the class definition of this projects add-in object.
Do
268
API Fundamentals
Lesson 10
Customizing the SolidWorks User Interface
Start SolidWorks.
From the File menu, click Open....
Change the Files of type filter to Add-Ins (*.dll).
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Navigate to the \Debug directory where the compiler created the DLL
for this project.
Double-click the file named CustomSwAddin.dll to load the
add-in.
Do
Close SolidWorks.
269
Lesson 10
API Fundamentals
Debugging the
DLL
Now that the DLL has been compiled and loaded into SolidWorks, the
programming project is ready to be set up for debugging. Debugging in
Visual Basic.NET is very similar to debugging a macro in VBA.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
270
API Fundamentals
Lesson 10
Customizing the SolidWorks User Interface
Scroll down in the source code file and find the region named
ISwAddIn Implementation
Expand the code in the region by clicking on the + sign next to it.
There are two functions in this region. The function names are
ConnectToSW and DisconnectFromSW.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
When SolidWorks starts, the add-in will automatically load, and the
code stops executing at the break point.
Debugger
Keyboard
Shortcuts
Note
Use the F10 key to step through the code line by line.
Use the F11 key to step into sub programs or functions.
Use the F5 key to continue running the code until another
breakpoint is encountered.
271
Lesson 10
API Fundamentals
13 Continue debugging.
Press F10 to step through several lines of code in the ConnectToSW
function.
Step to the End
Function
statement.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Doing this will end the current SolidWorks session and return focus to
Visual Studio.
Do
Understanding
The Add-in
Code
Note
272
Many comments have been added to the code diagrams in this case
study. The add-in wizard does not generate these automatically.
API Fundamentals
Lesson 10
Customizing the SolidWorks User Interface
There are several Imports statements at the top of this source code file.
VB.NET uses the Imports statement to tell the compiler to include the
namespace name of a reference that was included in the project. This
eliminates the need to prefix any objects used in the source code with
the name of the namespace that they are defined in. This project
imports four different namespace names. These four namespaces are
described in the following table.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Importing
Namespaces
Namespace Name
Description
Imports SldWorks
Imports SwPublished
Imports SwConst
Imports
System.Runtime.InteropServices
Using the Imports statement can eliminate a lot of typing done by the
programmer. If the project Imports the SldWorks namespace, the
following line of code:
Dim swModel As SldWorks.ModelDoc2
Notice the namespace name has been eliminated. The namespace prefix
can be eliminated for every object declared from this namespace.
Do
The majority of the functionality in this project is built into the add-in
class definition. The add-in class is used to implement the functionality
of the SwAddin object defined in the SwPublished type library.
SolidWorks can only load DLLs that expose an object that implements
the functionality of the SwAddIn object. The object in this project that
exposes the SwAddIn functionality is named CustomSwAddin.
273
Lesson 10
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
The code in this diagram is the projects namespace declaration and the
add-in objects declaration. The last line is the Implements statement.
The Implements statement forces the CustomSWAddin class to
implement all of the methods exposed on the SwAddin interface.
Understanding the
GUID
When SolidWorks loads this add-in, it will take the GUID that is
defined at the add-ins class declaration, and add it to the list of
SolidWorks add-ins in the registry.
SolidWorks will use this GUID to identify this add-in and load it
automatically anytime SolidWorks is started.
Do
274
SolidWorks will not load an add-in unless the add-in DLL exposes
these two methods named ConnectToSW and DisconnectFromSW.
When the DLL is loaded, SolidWorks queries the interface of the
add-in and checks to see if these methods exist. If they do, SolidWorks
will load the add-in, If they are not found, SolidWorks rejects the
illegitimate DLL.
API Fundamentals
Lesson 10
Customizing the SolidWorks User Interface
Connecting to
Solidworks
SwAddin::ConnectToSW
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Output:
IsConnected
TRUE
Input:
ThisSW
Cookie
Add-in ID.
Input:
Do
275
Lesson 10
API Fundamentals
Bidirectional
Communication
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
In the simplest scenario, one custom add-in is loaded that creates one
custom menu item in SolidWorks. When ever that menu item is clicked
by the end user, SolidWorks will have to send a message back to the
add-in so that the code in the callback function for that menu runs.
For more information on callback functions, see Setting Up Callbacks
on page 279.
Things get more complicated when there is more than one add-in
loaded that creates SolidWorks menu items. SolidWorks has to keep
track of which add-in creates which menus so that it can call the proper
callback function in the correct add-in when a menu is clicked by the
end user.
The next diagram shows the cookie being created in SolidWorks and
then being passed to the loading add-in. A pointer to SolidWorks is also
passed to the add-in. The add-in stores these values in global variables,
and then hands back the cookie to SolidWorks. Simultaneously, the
add-in passes a pointer to itself back to SolidWorks.
Do
Setting Callback
Information
SldWorks.SetAddinCallbackInfo
Status = SldWorks.SetAddinCallbackInfo ( ModuleHandle, AddinCallbacks, Cookie )
Output:
Status
TRUE
Input:
ModuleHandle
Input:
AddinCallbacks
Input:
Cookie
Add-in ID.
276
API Fundamentals
Lesson 10
Customizing the SolidWorks User Interface
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
The add-ins object pointer and the cookie are passed back to
SolidWorks to establish bidirectional communication.
These functions are used to add menus, toolbars, event handlers, and to
create a custom PropertyManager page.
The last line of code is returning a boolean value stating that the
function succeeded.
21 Go to definition.
Do
Custom Menus
SldWorks::AddMenu
retval = SldWorks.AddMenu ( docType, menu, position )
Output:
retval
TRUE
Input:
docType
Input:
menu
Input:
position
277
Lesson 10
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
The second parameter is the menu name. It is the string that appears in
SolidWorks on the newly added menu.
The last parameter is the position where you want the menu item to
display on the SolidWorks menu. Count the number of menu names
from the left of the screen to figure out what number corresponds to the
position where the menu is to be added.
Note
Do
Menu positions:
3
1 2
4
278
This first menu is set up only if their are no documents open in the
current SolidWorks session.
API Fundamentals
Lesson 10
Customizing the SolidWorks User Interface
Custom Menu
Items
SldWorks::AddMenuItem2
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Output:
IsMenuItemAdded
TRUE
Input:
DocumentType
Cookie
Add-in ID.
MenuItem
Menu string
("menuItem@subMenuString@menuString").
Position
MenuCallback
MenuEnableMethod
HintString
Input:
Input:
Input:
Input:
Input:
Input:
Do
Setting Up
Callbacks
When a custom menu item is clicked by the end user, SolidWorks calls
the appropriate callback method exposed by the DLL to handle the
event.
279
Lesson 10
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
The rest of the code in this module sets up the menus for all of the other
document types.
Do
All of the callback functions for the menus and toolbars are listed in
this region of the source code.
280
API Fundamentals
Lesson 10
Customizing the SolidWorks User Interface
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
The code in this function executes when the end user clicks the
Create Cube menu item in SolidWorks. When the user clicks the menu
item, a new part is created. A cube is then sketched and extruded.
Do
Creating and
Adding Custom
Toolbars to an
Add-in
281
Lesson 10
API Fundamentals
To view the custom toolbar images in this project, double-click the file
ToolbarLarge.bmp or ToolbarSmall.bmp in the
Solution Explorer. The image will appear in the Image Editor.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Tip
Creating the
Toolbar Bitmaps
Single Button
Multiple Buttons
16
pixels
16
16 pixels
16 x Number of Buttons
Multiple Buttons
Do
Single Button
24
pixels
24
24 pixels
Toolbar Index
282
24 x Number of Buttons
API Fundamentals
Lesson 10
Customizing the SolidWorks User Interface
Adding Toolbar
Bitmaps to a
VB.NET Solution
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
ToolTip
Do
Note
283
Lesson 10
API Fundamentals
The Bitmap
Handler Class
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
284
API Fundamentals
Lesson 10
Note
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
Adding Toolbars
You may be wondering why this code is re-creating the bitmap on the
hard disk. This method eliminates the problem of managing the exact
location of the bitmap on the target machine when the add-in is
distributed.
Notice that the first input parameter is the cookie. By passing the
cookie to this method, SolidWorks can keep track of which add-in
created this toolbar. Also notice the output parameter for this method.
The toolbar ID will be used when adding toolbar commands to a
toolbar. Because an add-in can create many toolbars, the toolbar ID
will be used to identify what toolbar a toolbar command is going to be
associated with.
285
Lesson 10
API Fundamentals
SldWorks::AddToolbar4
NewToolBarID = SldWorks.AddToolbar4 ( Cookie, Title, smallBitmapImage,
largeBitmapImage, MenuPositionForToolbar, DocumentType )
NewToolBarID
Input:
Cookie
Add-in ID.
Input:
Input:
Input:
Input:
Input:
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Output:
Title
smallBitmapImage
largeBitmapImage
MenuPositionForToolbar
DocumentType
Do
286
API Fundamentals
Lesson 10
Customizing the SolidWorks User Interface
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Note
Adding Toolbar
Commands
SldWorks::AddToolbarCommand2
Output:
IsToolbarCommandAdded
TRUE
Input:
Cookie
Add-in ID.
ToolbarID
ToolbarIndex
ButtonCallback
ButtonEnableMethod
ToolTip
HintString
Input:
Input:
Input:
Input:
Input:
Input:
Do
Note
287
Lesson 10
API Fundamentals
Tip
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
288
API Fundamentals
Lesson 10
Customizing the SolidWorks User Interface
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
A message box displays the ID of the toolbar button that was pressed.
Property Pages
PropertyPage
Members
Two interfaces of the SwPublished type library are used when creating
a custom PropertyManager page with the API.
I
Do
PropertyManagerPage2
PropertyManagerPage2Handler2
The add-ins UserPMPPage class has two members that are used to
respectively represent these interfaces:
I
I
ppage
handler
Also, any of the controls that are created on this page are members of
this class.
The following is a diagram of the classes and interfaces that the add-in
wizard uses when creating a custom PropertyManager page.
Property Pages
289
Lesson 10
API Fundamentals
UserPMPage
Add-In
SldWorks
Add-In
SldWorks
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
ppage
Group1
Group2
Option1
Option2
Option3
Checkbox1
List1
Selection1
Num1
Combo1
handler
PropertyManager
Page2Handler2
Do
PropertyManager
Page2
290
Property Pages
API Fundamentals
Lesson 10
Customizing the SolidWorks User Interface
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
SldWorks::CreatePropertyManagerPage
Output:
retval
Input:
title
Options
Options as defined in
swPropertyManagerPageOptions_e.
handler
errors
Input:
Input:
Output:
PropertyManagerPage2::Show
retval = PropertyManagerPage2.Show ( )
Output:
retval
Do
CustomSwAddin::AddPMP method.
The code for the AddPMP function is displayed in the code editor.
Property Pages
291
Lesson 10
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
This function passes the add-in and the SolidWorks pointer to the
PropertyManager page and stores them in variables. It then calls two
other functions used to create the page, and add controls to it.
Do
Property Page
Groups and
Controls
292
API Fundamentals
Lesson 10
Customizing the SolidWorks User Interface
Adding Group
Boxes
PropertyManagerPage2::AddGroupBox
retval = PropertyManagerPage2.AddGroupBox ( Id, Caption, Options )
Input:
Input:
Input:
retval
Id
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Output:
Caption
Options
Do
After three local variables are declared, two group boxes are
constructed using the PropertyManagerPage2::AddGroupBox method
293
Lesson 10
API Fundamentals
method.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Add the following code which uses the group box ID to determine
which group box on the PropertyManager page was expanded.
Adding Controls
PropertyManagerPageGroup::AddControl
Output:
retval
Input:
Id
ControlType
Caption
LeftAlign
Input:
Input:
Do
Input:
Input:
Options
Input:
Tip
294
API Fundamentals
Lesson 10
Customizing the SolidWorks User Interface
The following table is a list of the different types of controls that can be
added to PropertyManager pages.
PropertyManager Controls Types and Properties
Button
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
GroupBox
.Caption
Checkbox
.Caption, .Checked
Combobox
Listbox
Label
.Caption
.Style
NumberBox
.SetRange
.Value
Option
.Checked
.Style
.GetSelectionFocus
.SetSelectionFilters
.SetSelectionFocus
.Callout
.Height
.Mark
.SetCalloutLabel
.SetSelectionColor
.SingleEntityOnly
.Style
TextBox
.Text
Do
SelectionBox
BitmapButton
.Checked
.IsCheckable
.SetBitmaps
.SetBitmapsByName
.SetStandardBitmaps
Checkable
BitmapButton
Tip
295
Lesson 10
API Fundamentals
method.
Scroll down to examine the code for adding the controls to the group
boxes.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
In the following diagram, several control options are set and the
PropertyManagerPageGroup::AddControl method is used to add a
check box control to the group box.
Do
296
API Fundamentals
Lesson 10
Customizing the SolidWorks User Interface
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Tip
Do
Adding Picture
Labels to Controls
297
Lesson 10
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Important!
Notice that the variables for the controls on this page have the scope of
the entire UserPMPPage class. If control variables do not have the
scope of the class, the event handlers will not work correctly.
Do
Add the following variable to define the new number box control ID.
298
API Fundamentals
Lesson 10
Customizing the SolidWorks User Interface
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Add the code to create the number box with a picture label.
Removing
Menus and
Toolbars
SwAddin::DisconnectFromSW
IsDisconnected = SwAddin.DisconnectFromSW ( )
Output:
IsDisconnected
TRUE
not.
SldWorks::RemoveMenu
Do
Output:
retval
TRUE
Input:
DocType
Input:
MenuItemString
Input:
CallbackFcnAndModule
299
Lesson 10
API Fundamentals
Output:
Status
TRUE
Input:
Input:
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
not.
Cookie
Add-in ID.
ToolbarID
Toolbar ID.
CustomSwAddin::DisconnectFromSW method.
Do
The code in this function removes all of the menus that were created for
each SolidWorks document type.
Tip
300
API Fundamentals
Lesson 10
Customizing the SolidWorks User Interface
CustomSWAddin::RemoveToolbar method.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
301
Lesson 10
API Fundamentals
55 Click an option.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
The following topics review areas also available when customizing the
SolidWorks user interface.
Custom Status
Bars
To set the text in the SolidWorks status bar, get an interface pointer to
the SldWorks::Frame object. Then, call Frame::GetStatusBarPane to
connect to the StatusBarPane object. Finally, call StatusBarPane::Text
to set the text for the pane.
Do
Other Areas of
Customization
302
API Fundamentals
Lesson 10
Customizing the SolidWorks User Interface
Custom Pop-up
Menus
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
Custom
ModelView
Windows
303
Lesson 10
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
304
API Fundamentals
Exercise 16:
Implement a New Menu
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Exercise 16:
Implement a
New Menu
Objective
Create a new custom menu item. Implement the menu item and its
callback method. The menu should appear on all document types, and
also when there are no active documents.
APIs Used
SldWorks::AddMenu
SldWorks::AddMenuItem2
1.
2.
3.
4.
5.
6.
Do
Procedure
305
Exercise 16:
API Fundamentals
The following lines of code were added to the AddMenus sub program
to add the menus.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Solution
Do
306
API Fundamentals
Exercise 17:
Implement Toolbar Buttons
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Exercise 17:
Implement
Toolbar Buttons
Objective
Use the same project created in the last exercise to implement the
toolbar buttons on the custom toolbar.
Implement the callbacks for the toolbar buttons.
APIs Used
ModelDoc2::ViewRotateplusx
ModelDoc2::ViewRotateplusy
ModelDoc2::ViewRotateplusz
Do
Procedure
307
Exercise 17:
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Solution
308
API Fundamentals
Exercise 18:
Implement Controls on a Property Manager Page
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Exercise 18:
Implement
Controls on a
Property
Manager Page
Objective
Use the same wizard generated project to learn how to create and
implement controls on a custom PropertyManager page. Understand
how the PropertyManagerPage2 and the
PropertyManagerPageHandler2 objects interact with each other.
APIs Used
PropertyManagerPage2::AddGroupBox
PropertyManagerPage2::AddControl
1.
2.
3.
4.
5.
Do
Procedure
309
Exercise 18:
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Solution
Do
310
API Fundamentals
Exercise 18:
Implement Controls on a Property Manager Page
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
311
Exercise 18:
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
312
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
API Fundamentals
Lesson 11
Notifications
Do
313
Lesson 11
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Notifications
314
API Fundamentals
Lesson 11
Notifications
Notifications
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
I
I
I
I
I
I
I
Notifications in
VBA
Do
Selecting one of the notifications from the procedure pull down menu
causes a skeleton handler function to be added to the code. Code can be
added to this handler to make it functional.
Notifications
315
Lesson 11
API Fundamentals
Notifications
Note
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Case Study:
Simple
Notification
notifications.swp.
Do
316
API Fundamentals
Lesson 11
Notifications
Choose a procedure.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
The code for the notification handler is appended to the source code.
Do
317
Lesson 11
API Fundamentals
Notifications
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Exit SolidWorks.
Do
Case Study:
Using
Notifications in
.NET
318
API Fundamentals
Lesson 11
Notifications
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Variables.
Do
The iSwApp variable has been declared using the WithEvents keyword.
319
Lesson 11
API Fundamentals
Notifications
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
The first line of code in this sub program calls a function that attaches
the notifications to the SolidWorks application object.
Do
320
API Fundamentals
Lesson 11
Notifications
The AddressOf
Keyword
Note
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
The AddHandler
Keyword
Do
From the SolidWorks File menu, click New... and create a new part
document. The delegate function is triggered and displays the
messages.
321
Lesson 11
API Fundamentals
Notifications
On the add-in wizard options page, all of the Addin Events options
were selected.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
I
I
I
PartEventHandler
AssemblyEventHandler
DrawingEventHandler
DocView
Finally, a base class for all of the document level event handlers is
created.
I
322
DocumentEventHandler
API Fundamentals
Lesson 11
Notifications
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
The Document
Event Handler
Class
Do
Hash Tables
Hash tables are high-performance containers that quickly add, find and
remove key-value pairs (similar to an array.) Because the hash table has
high performance data retrieval capabilities, it is the best choice for
managing the openDocs and the openModelViews event handler
objects.
When a new DocumentEventHandler object is instantiated, it is added
to another hash table, named openDocs, which is a member of the addin class. This hash table member manages all of the
DocumentEventHandler objects that are created by the add-in. This
member is declared in the #Region "Local Variables of the
add-in class.
323
Lesson 11
API Fundamentals
Notifications
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Attaching the
DocumentEvent
Handlers
There are two occurrences where an add-in will create document event
handlers.
I
Do
This ensures that from the time the add-in loads, until the time it is
unloaded, all documents in the SolidWorks session will have a
document level event handler object created and attached to it.
DotNetNotifications::AttachEventHandlers function.
After the SolidWorks application event handlers are attached,
notifications are attached to all open documents.
The following code traverses the open SolidWorks documents and
attaches event handlers to them.
324
API Fundamentals
Lesson 11
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Notifications
Do
325
Lesson 11
API Fundamentals
Notifications
Polymorphism
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Inheritance
PartEventHandler
AssemblyEventHandler
DrawingEventHandler
Init
AttachEventHandlers
DetachEventHandlers
Note
Do
326
API Fundamentals
Lesson 11
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Notifications
Do
327
Lesson 11
API Fundamentals
Notifications
The next part of this case study examines the three classes derived from
the DocumentEventHandler class.
I
I
I
PartEventHandler
AssemblyEventHandler
DrawingEventHandler
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
16 Add code
Do
328
API Fundamentals
Lesson 11
Notifications
window.
This class declares an AssemblyDoc variable with the WithEvents
keyword.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
18 Add code
Do
329
Lesson 11
API Fundamentals
Notifications
window.
This class declares a DrawingDoc variable with the WithEvents
keyword.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
20 Add code
Do
The DocView
Class
330
API Fundamentals
Lesson 11
Notifications
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
22 Add code.
its message.
Do
Note
331
Lesson 11
API Fundamentals
Notifications
its message.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
its message.
Do
332
API Fundamentals
Lesson 11
Notifications
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
If you switch to the assembly document and select anything in it, the
AssemblyDoc_NewSelectionNotify message will be displayed.
Try this also with the drawing document. The
DrawingDoc_NewSelectionNotify message will be displayed.
Do
Detaching the
Document and
Model View Event
Handlers
333
Lesson 11
API Fundamentals
Notifications
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
334
API Fundamentals
Lesson 11
Notifications
Note
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
35 Continue debugging.
Continue pressing the F10 until you reach the DetachEventHandlers
Do
method.
335
Lesson 11
API Fundamentals
Notifications
DetachModelViewEventHandler function.
The event handlers are now removed from the model view.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Press F11 to step into this helper method that removes the model view
event handler objects from the hash table.
37 Continue debugging.
Use the F10 key to step through this function.
Any model view pointer that was created for this document is removed
from the hash table. In this case there is only one.
When the End Function keyword is encountered, press the F10 three
more times to return to the originating DisconnectModelViews method
call.
table.
Do
Continue pressing the F10 key to exit this function and return to the
PartEventHandler::DetachEventHandlers function
336
API Fundamentals
Lesson 11
Notifications
39 Continue Debugging.
Use the F10 key again to move to the DetachModelEventHandler
function call.
At this point all of the model view event handlers are removed and so
are the openModelViews hash table entries.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
This method removes the document event handler from the add-ins
openDocs hash table.
Press the F5 key to continue debugging the code. All of the methods to
remove any handlers from the closed document have been called.
Detaching the
SolidWorks Event
Handlers
41 Insert a breakpoint.
Do
337
Lesson 11
API Fundamentals
Notifications
42 Continue Debugging.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
This sub program is used to remove all of the event handlers from the
closing instance of SolidWorks.
The highlighted code is the function used to remove the application
level notifications.
Press F11 to step into this function.
Do
44 Continue debugging.
Use the F10 key to step through this code and return to the originating
338
API Fundamentals
Lesson 11
Notifications
45 Complete debugging.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
This code traverses the openDocs hash table member and removes any
document event handlers from the hash table.
Every time the loop encounters a document, it explicitly calls the
DocumentEventHandler::DetachEventHandlers method.
Do
339
Lesson 11
API Fundamentals
Notifications
Interfaces That
Support
Notifications
The following tables are a list of the SolidWorks API interfaces that
support notifications.
SldWorks Events
Post-notifies the user program when the active window has
changed. This "window change" may be between windows of the same
document or between windows of different documents.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
ActiveDocChangeNotify
BeginTranslationNotify
DestroyNotify
DocumentConversionNotify
DocumentLoadNotify
EndTranslationNotify
FileNewNotify
Post-notifies the user program when a new file has been created.
FileNewNotify2
Post-notifies the user program when a new file has been created.
FileOpenNotify
FileOpenNotify2
FileOpenPostNotify
FileOpenPreNotify
LightSheetCreateNotify
This event will be fired when a lighting sheet has been created.
NonNativeFileOpenNotify
OnIdleNotify
PromptForFilenameNotify
PropertySheetCreateNotify
ReferenceNotFoundNotify
Do
ActiveModelDocChangeNotify
340
API Fundamentals
Lesson 11
Notifications
PartDoc Events
Pre-notifies the client program when the configuration has
been changed
ActiveConfigChangePostNotify
AddCustomPropertyNotify
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
ActiveConfigChangeNotify
Notifies the client that an Item has been added to the part
document.
BodyVisibleChangeNotify
ChangeCustomPropertyNotify
DeleteCustomPropertyNotify
DeleteItemNotify
Notifies the client when an item has been deleted from the
part document.
DeleteSelectionPreNotify
DestroyNotify
DimensionChangeNotify
DynamicHighlightNotify
FeatureEditPreNotify
FeatureManagerTreeRebuildNotify
FeatureSketchEditPreNotify
FileReloadCancelNotify
Notifies the client when the file reload has been canceled
by the user of the part document.
Do
AddItemNotify
FileReloadNotify
FileReloadPreNotify
FileSaveAsNotify
FileSaveAsNotify2
FileSaveNotify
FileSavePostCancelNotify
FileSavePostNotify
LightingDialogCreateNotify
LoadFromStorageNotify
341
Lesson 11
API Fundamentals
Notifications
PartDoc Events
Post-notifies the user program when it is safe to load data
from third-party storage
ModifyNotify
NewSelectionNotify
RegenNotify
RegenPostNotify
RegenPostNotify2
RenameItemNotify
SaveToStorageNotify
SaveToStorageStoreNotify
ViewNewNotify
ViewNewNotify2
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
LoadFromStorageStoreNotify
342
API Fundamentals
Lesson 11
Notifications
AssemblyDoc Events
Pre-notifies the client program when the configuration is
changed.
ActiveConfigChangePostNotify
AddCustomPropertyNotify
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
ActiveConfigChangeNotify
Notifies the client that an Item has been added to the part
document.
BeginInContextEditNotify
BodyVisibleChangeNotify
ChangeCustomPropertyNotify
ComponentMoveNotify
ComponentStateChangedNotify
ComponentStateChangedNotify2
ComponentVisibleChangeNotify
DeleteCustomPropertyNotify
DeleteItemNotify
Notifies the client when an item has been deleted from the
part document.
DeleteSelectionPreNotify
DestroyNotify
EndInContextEditNotify
FeatureEditPreNotify
Do
AddItemNotify
FeatureManagerTreeRebuildNotify
FeatureSketchEditPreNotify
FileDropNotify
FileDropPreNotify
FileReloadNotify
FileReloadPreNotify
FileSaveAsNotify
FileSaveAsNotify2
343
Lesson 11
API Fundamentals
Notifications
AssemblyDoc Events
Notifies the client when a file is saved.
FileSavePostNotify
InterferenceNotify
LightingDialogCreateNotify
LoadFromStorageNotify
LoadFromStorageStoreNotify
ModifyNotify
NewSelectionNotify
RegenNotify
RegenPostNotify
RenameItemNotify
SaveToStorageNotify
SaveToStorageStoreNotify
ViewNewNotify
ViewNewNotify2
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
FileSaveNotify
DrawingDoc Events
ActiveConfigChangePostNotify
Do
ActiveConfigChangeNotify
AddCustomPropertyNotify
AddItemNotify
Notifies the client that an Item has been added to the part
document.
ChangeCustomPropertyNotify
DeleteCustomPropertyNotify
DeleteItemNotify
Notifies the client when an item has been deleted from the
part document.
DeleteSelectionPreNotify
344
API Fundamentals
Lesson 11
Notifications
DrawingDoc Events
Notifies the client that the part document is being
destroyed.
EndInContextEditNotify
FeatureManagerTreeRebuildNotify
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
DestroyNotify
FileReloadPreNotify
FileSaveAsNotify
FileSaveAsNotify2
FileSaveNotify
FileSavePostNotify
LoadFromStorageNotify
LoadFromStorageStoreNotify
ModifyNotify
NewSelectionNotify
RegenNotify
RegenPostNotify
RenameItemNotify
SaveToStorageNotify
SaveToStorageStoreNotify
ViewNewNotify
ViewNewNotify2
Do
FileReloadNotify
ModelView Events
BufferSwapNotify
DestroyNotify
DestroyNotify2
RepaintNotify
RepaintPostNotify
ViewChangeNotify
345
Lesson 11
API Fundamentals
Notifications
FeatMgrView Events
Post-notifies the user program once a FeatureManager design
tree view is activated and returns the view handle.
DeactivateNotify
DestroyNotify
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
ActivateNotify
SWPropertySheet Events
HelpNotify
Do
DestroyNotify
346
API Fundamentals
Exercise 19:
Handling Events Using the Add-in Wizard
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Exercise 19:
Handling
Events Using
the Add-in
Wizard
Objective
Do
Procedure
347
Exercise 19:
API Fundamentals
Solution
Navigate to the AttachSWEvents function and add the code to attach the
event handler.
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
348
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
API Fundamentals
Appendix
Batch Conversion 1
Batch Conversion 2
Assembly Traversal
Do
349
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Macro Feature
Module:
CounterBore
Do
350
Sub main()
Dim MacroUI As New CMacroFeaturePropPage
MacroUI.PropPageMenuCallback
End Sub
Macro Feature
API Fundamentals
Module:
MacroFeature
Functions
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
Dim
Dim
Dim
Dim
Dim
Macro Feature
swCicularFace As SldWorks.face2
SelObjects As Variant
SelObjectTypes As Variant
SelMarks As Variant
SelDrViews As Variant
swMacroFeatureData.GetSelections2 _
SelObjects, SelObjectTypes, SelMarks, SelDrViews
Set swCircularFace = SelObjects(0)
Dim swSurface As SldWorks.Surface
Set swSurface = swCircularFace.GetSurface
Dim Edges As Variant
Edges = swCircularFace.GetEdges
Dim swCurve As SldWorks.Curve
Set swCurve = Edges(0).GetCurve
Dim CircleParams As Variant
CircleParams = swCurve.CircleParams
Dim FaceODRadius As Double
FaceODRadius = CircleParams(6)
Dim FaceNormal As Variant
FaceNormal = swCircularFace.Normal
Dim TparamValues(9) As Double
TparamValues(0) = CircleParams(0)
TparamValues(1) = CircleParams(1)
TparamValues(2) = CircleParams(2)
TparamValues(3) = -FaceNormal(0)
TparamValues(4) = -FaceNormal(1)
TparamValues(5) = -FaceNormal(2)
TparamValues(6) = MyParamValues(0) * 0.0254
TparamValues(7) = MyParamValues(1) * 0.0254
TparamValues(8) = 0
TparamValues(9) = 0
351
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
dboxDimArray(0) = TparamValues(0)
dboxDimArray(1) = TparamValues(1)
dboxDimArray(2) = TparamValues(2)
dboxDimArray(3) = TparamValues(3)
dboxDimArray(4) = TparamValues(4)
dboxDimArray(5) = TparamValues(5)
dboxDimArray(6) = TparamValues(6) / 2
dboxDimArray(7) = TparamValues(7)
boxDimArray = dboxDimArray
Dim swModeler As SldWorks.Modeler
Set swModeler = app.GetModeler
Dim TempCylOut As SldWorks.body2
Set TempCylOut = swModeler.CreateBodyFromCyl(boxDimArray)
TempCylOut.Display swPart, RGB(1, 0, 0)
Set PartBody = swMacroFeatureData.editBody
Dim ResultBodiesPerm As Variant
ResultBodiesPerm = PartBody.Operations2 _
(SWBODYCUT, TempCylOut, errorCode)
swmRegenCBore = True
End Function
Do
MacroUI.swMacroFeatureData.GetParameters _
MyParamNames, MyParamTypes, MyParamValues
MacroUI.m_dDiameter = MyParamValues(0)
MacroUI.m_dDepth = MyParamValues(1)
MacroUI.PropPageMenuCallback
End Function
352
Macro Feature
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Batch
Conversion 1
Do
Dim
Dim
Dim
Dim
Dim
Dim
Batch Conversion 1
FileName As String
NoteText As String
TextCount As Long
errors As Long
warnings As Long
i As Long
353
API Fundamentals
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
354
Batch Conversion 1
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Batch
Conversion 2
Sub main()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swDraw As SldWorks.DrawingDoc
Dim swNote As SldWorks.note
Dim swTextFormat As SldWorks.textFormat
Do
Dim
Dim
Dim
Dim
Dim
Batch Conversion 2
FileName As String
NoteText As String
errors As Long
warnings As Long
i As Long
355
API Fundamentals
Assembly
Traversal
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Sub main()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swAssy As SldWorks.AssemblyDoc
Dim swConf As SldWorks.configuration
Dim swRootComp As SldWorks.Component2
Dim nStart As Single
Dim bRet As Boolean
Do
356
Assembly Traversal
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
For i = 0 To nLevel - 1
sPadStr = sPadStr + " "
Next i
Assembly Traversal
vChildComp = swComp.GetChildren
For i = 0 To UBound(vChildComp)
Set swChildComp = vChildComp(i)
Debug.Print sPadStr & "+" & swChildComp.Name2 & " <" & _
swChildComp.ReferencedConfiguration & ">"
TraverseComponentFeatures swChildComp, nLevel
TraverseComponent swChildComp, nLevel + 1
Next i
End Sub
357
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Custom Model
View
Option Explicit
Do
358
API Fundamentals
As SldWorks.SldWorks
As SldWorks.ModelDoc2
As SldWorks.ModelDocExtension
As SldWorks.ModelViewManager
As Variant
As Variant
As Double
As Boolean
As OWC.Spreadsheet
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Sub main()
UserForm1.Show
End Sub
Do
359
API Fundamentals
= materialProps(0) * 255
= materialProps(1) * 255
= materialProps(2) * 255
= materialProps(3)
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
'column 2
xl.Range("B1").Select
xl.ActiveCell.Formula
xl.Range("B2").Select
xl.ActiveCell.Formula
xl.Range("B3").Select
xl.ActiveCell.Formula
xl.Range("B4").Select
xl.ActiveCell.Formula
xl.Range("B5").Select
xl.ActiveCell.Formula
xl.Range("B6").Select
xl.ActiveCell.Formula
xl.Range("B7").Select
xl.ActiveCell.Formula
xl.Range("B8").Select
xl.ActiveCell.Formula
xl.Range("B9").Select
xl.ActiveCell.Formula
= materialProps(4)
= materialProps(5)
= materialProps(6)
= materialProps(7)
= materialProps(8)
xl.Columns("2").Select
'xl.Selection.Font.Bold = True
xl.Selection.Font.Name = "Arial"
xl.Selection.Font.Size = 12
xl.Selection.ColumnWidth = 60#
xl.Selection.HAlignment = 1
Do
'column 3
xl.Range("C1").Select
xl.ActiveCell.Formula = "Density"
xl.Range("C3").Select
xl.ActiveCell.Formula
xl.Range("C4").Select
xl.ActiveCell.Formula
xl.Range("C5").Select
xl.ActiveCell.Formula
xl.Range("C6").Select
xl.ActiveCell.Formula
xl.Range("C7").Select
xl.ActiveCell.Formula
xl.Range("C8").Select
xl.ActiveCell.Formula
= "CenterOfMassX"
= "CenterOfMassY"
= "CenterOfMassZ"
= "Volume"
= "Surface Area"
= "Mass"
xl.Columns("3").Select
xl.Selection.Font.Bold = True
xl.Selection.Font.Name = "Arial"
xl.Selection.Font.Size = 12
xl.Selection.ColumnWidth = 140#
xl.Selection.HAlignment = 3
360
API Fundamentals
'column 4
= massProps(0) * 100
= massProps(1) * 100
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
xl.Range("D1").Select
xl.ActiveCell.Formula
'Density (grams/cm^3)
xl.Range("D3").Select
xl.ActiveCell.Formula
'CenterOfMassX (cm)
xl.Range("D4").Select
xl.ActiveCell.Formula
'CenterOfMassY (cm)
xl.Range("D5").Select
xl.ActiveCell.Formula
'CenterOfMassZ (cm)
xl.Range("D6").Select
xl.ActiveCell.Formula
'Volume (cm^3)
xl.Range("D7").Select
xl.ActiveCell.Formula
'Surface Area (cm^2)
xl.Range("D8").Select
xl.ActiveCell.Formula
xl.Range("D9").Select
= massProps(2) * 100
xl.Columns("4").Select
'xl.Selection.Font.Bold = True
xl.Selection.Font.Name = "Arial"
xl.Selection.Font.Size = 12
xl.Selection.ColumnWidth = 60#
xl.Selection.HAlignment = 1
Do
'column 5
xl.Range("E1").Select
xl.ActiveCell.Formula = "grams/cubic cm"
xl.Range("E3").Select
xl.ActiveCell.Formula
xl.Range("E4").Select
xl.ActiveCell.Formula
xl.Range("E5").Select
xl.ActiveCell.Formula
xl.Range("E6").Select
xl.ActiveCell.Formula
xl.Range("E7").Select
xl.ActiveCell.Formula
xl.Range("E8").Select
xl.ActiveCell.Formula
= "cm"
= "cm"
= "cm"
= "cubic cm"
= "square cm"
= "grams"
xl.Columns("5").Select
xl.Selection.Font.Bold = True
xl.Selection.Font.Name = "Arial"
xl.Selection.Font.Size = 12
xl.Selection.ColumnWidth = 60#
xl.Selection.HAlignment = 1
End Sub
361
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
API Fundamentals
362
API Fundamentals
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Index
Do
A
Accessors 55
AccessSelections 182
ActivateDoc2 47, 149
ActiveDoc 47, 55
AddComponent2 64, 66, 155
AddControl 294
AddCustomInfo3 55, 71, 208
AddDimension2 131
AddGroupBox 293
AddHandler 321
AddHorizontalDimension2 131
Add-in 249
Add-in applications 249
adding
code to controls 30, 52, 57, 65, 129
130, 132136
controls to a form 29, 57, 65
custom properties 207, 211
face attributes 221
forms to a macro 29
user interaction code to controls 33
Add-Ins
setting callback information 276
AddMate 64, 155
AddMenu 277
AddMenuItem2 279
AddMenuPopupItem2 303
AddParameter 218
AddPMP 291
AddressOf 321
AddToolbar4 285
AddToolbarCommand2 282, 287
AddVerticalDimenion2 131
API SDK 239
Application objects 47
Application.SldWorks 47
ArrangeWindows 47
ArrayData 156
Assembly Traversal 356
AssemblyDoc Events 343
AssemblyDoc Object 64
AssemblyEventHandler 329
AttachEventHandlers 320
AttachModelDocEventHandler 325
AttachSWEvents 320
Attribute Object 219, 225
AttributeDef Object 218
Index
B
Batch Conversions 353, 355
binding
early vs. late 49
BitmapHandler 284
button commands
annotations 172
drawing 172
features 139
layer 172
line format 172
reference geometry 139
sketch 138
sketch relations 139
sketch tools 138
standard 137
standard view 137
view 137
C
C# 252
C# Add-In Wizard 252
C++ add-in application 255
callback 279
choosing data types 6
CircleParams 153
Class Module - VBA 316
Class View 284
CloseDoc 47
Collections 151154
Compiling a C# Application 254
Compiling a C++ Addin 257
ConnectModelViews 327
ConnectToSW 275
ConstructionGeometry 131
Contour Selection 134
cookie 276
Create1stAngleViews2 166
Create3rdAngleViews2 166
CreateCallout 225
CreateCircle2 55
CreateCircleByRadius2 133
CreateFileFromResourceString 284
CreateInstance3 218
CreateLayer 76
CreateLine2 131
CreateNewBody 64
CreateNewWindow 47, 69
CreatePage 292
CreatePoint 154
CreatePropertyManagerPage 291
CreateTransform 148
creating a macro 15
Custom FeatureManager Tabs 303
Custom Menus
adding 277
Custom Menus Items 279
Custom ModelView Windows 303
Custom Pop-up Menus 303
Custom Properties 207, 211
Custom Status Bars 302
Custom Toolbars
adding commands 287
adding toolbars 285
resource editor 283
toolbar index 282
tooltips 283
CustomInfo2 209
customizing the Macro toolbar 18
D
data types 6
debug build 250
declaring variables 5, 20
DestroyNotify 333
DetachEventHandlers 334
Detaching Event Handlers 333
DIM statement 5, 20
DisconnectFromSW 299
DisplayStatusBar 47, 53
Document Attributes 217
DocumentEventHandler 323
DocumentLoadNotify 324
DocumentVisible 47, 150
DocView 330
DrawingDoc Events 344
DrawingDoc Object 64
DrawingEventHandler 330
E
early binding 49
EditFormat 67
editing a macro 15, 19
EditRebuild3 55
EditRollback 64, 66
EnableContourSelection 134
ExitApp 47
F
Face Attributes 221
363
API Fundamentals
InsertNewPart 64
InsertNote 55, 59
InsertSketch2 55, 58
IntelliSense 49
IsCircle 151
IsOuter 151
ISwAddin Implementation 274
L
late binding 49
LoadFile2 47, 69
ReleaseSelectionAccess 183
RemoveMenu 299
RemoveToolbar2 300
Resource Editor 283
RevisionNumber 47, 53
S
Safe entities 147
SaveAs4 55
SDK 239
SelectByID 56
SelectionManager 146, 180
SendMsgToUser 47
SetAddinCallbackInfo 276
SetAddToDB 129
SetDoubleValue 219
SetPictureLabelByName 297
SetStandardPictureLabel 297
SetStringValue 219
SetSuppression 194
SetToolbarVisibility 55, 70
SetUIState 196
SetUserPreference 83
SetUserPreferenceDoubleValue 86
SetUserPreferenceIntegerValue 85
SetUserPreferenceStringValue 87
SetUserPreferenceToggle 83
Show 291
SketchOffset2 131
SketchRectangle 131
SldWorks Events 340
SldWorks Object 47
SldWorks_FileNewNotify2 321
SolidWorks 2005 Type Library 48
SolidWorks COM AddIn 255
SolidWorks VB.NET Add-In 244
SolidWorksExplorer 47, 53
Stand-alone applications 249
StatusBarPane 302
SummaryInfo 216
swApp 47
swAssy 64
swAttDef 218
swAttr 219, 225
swDocASSEMBLY 64
swDocDRAWING 64
swDocPART 64
swDraw 64
swMateCOINCIDENT 156
swMateCONCENTRIC 156
swModel 55
swModelExt 56
swParam 219
swPart 64
SWPropertySheet Events 346
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
Do
G
GetBodies2 188
GetConfigurationNames 163
GetCurve 151
GetCustomInfoCount2 210
GetCustomInfoNames2 210
GetDefinition 182
GetDoubleValue 219
GetEdges 151
GetEntity 219
GetFirstFace 189
GetFirstLoop 151
GetFirstView 64
GetMassProperties 56
GetMathUtility 146
GetName 219, 225
GetNextFace 191
GetNextFeature 193
GetParameter 219, 225
GetSelectedObject3 181
GetSelectedObjectCount 180
GetSelectedObjectType2 181
GetStatusBarPane 302
GetStringValue 219
GetSurface 152
GetTitle 146
GetTwoAdjacentFaces 152
GetType 64, 219
GetTypeName 181, 194
GetUserPreference 83
GUID 274
H
Hash tables 323
help file
Contents tab 9
examples 9
Index tab 9
objects 9
Release Notes 9
Search tab 9
I
Image Editor 282
Inheritance 326
InsertCavity4 74
InsertFamilyTableNew 55, 58
InsertFeatureShell 55
InsertModelAnnotations 64, 167, 170
364
M
Macro Feature 350
Macro toolbar 15
macros
creating 15
editing 15
playing 15
recording 15
recording tips 8
MaterialPropertyValues 64, 190
MathPoint 154
MathUtility Object 146
MirrorPart 64, 73
ModelDoc Extension Object 56
ModelDoc2 Object 55
ModelView Events 345
ModifyDefinition 184
MultiplyTransform 154
N
NewDocument 47, 55, 58
NewSheet3 64, 164
Notifications 315
Notifications in .NET 318
O
OpenDoc6 47, 55, 69
Option Explicit 5
P
Parameter Object 219
PartDoc Events 341
PartDoc Object 64
PartEventHandler 328
playing a macro 15
PMPageHandler 290
Polymorphism 326
Preselection 179
PrintOut 56
Property Pages 289
PropertyManager Page2 290
PropertyManager Page2Handler2 290
Q
QuitDoc 47
R
recording a macro 15
references 246
Register 218
registry 251
release build 250
T
TargetStyle 225
tips for recording a macro 8
Toolbar Bitmaps 282
Toolbars 281
ToolsCheckInterference2 64
Transforms 148
traversal
Index
API Fundamentals
Index
assembly 356
face 185
FeatureManager 192
U
units 6
UserForm 29
UserPMPPage 290
using data types 6
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
V
variables 5
ViewZoomtofit2 55
Visual Basic for Applications
(VBA) 19
Do
W
WithEvents 315
Index
365
Do
no Pr
t c e-R
op e
y o lea
r d se
ist
rib
ut
e
API Fundamentals
366
Index