Sie sind auf Seite 1von 376

SolidWorks 2006

API Fundamentals

SolidWorks Corporation
300 Baker Avenue
Concord, Massachusetts 01742

1995-2005, SolidWorks Corporation


300 Baker Avenue
Concord, Massachusetts 01742 USA
All Rights Reserved
U.S. Patents 5,815,154; 6,219,049; 6,219,055;
6,603,486; 6,611,725; and 6,844,877 and certain
other foreign patents, including EP 1,116,190 and JP
3,517,643. U.S. and foreign patents pending.
SolidWorks Corporation is a Dassault Systemes
S.A. (Nasdaq:DASTY) company.
The information and the software discussed in this
document are subject to change without notice and
should not be considered commitments by
SolidWorks Corporation.
No material may be reproduced or transmitted in any
form or by any means, electronic or mechanical, for
any purpose without the express written permission
of SolidWorks Corporation.
The software discussed in this document is furnished
under a license and may be used or copied only in
accordance with the terms of this license. All
warranties given by SolidWorks Corporation as to
the software and documentation are set forth in the
SolidWorks Corporation License and Subscription
Service Agreement, and nothing stated in, or implied
by, this document or its contents shall be considered
or deemed a modification or amendment of such
warranties.
SolidWorks, PDMWorks, and 3D PartStream.NET,
and the eDrawings logo are registered trademarks of
SolidWorks Corporation.
SolidWorks 2006 is a product name of SolidWorks
Corporation.
COSMOSXpress, DWGeditor, DWGgateway,
eDrawings, Feature Palette, PhotoWorks, and
XchangeWorks are trademarks, 3D ContentCentral
is a service mark, and FeatureManager is a jointly
owned registered trademark of SolidWorks
Corporation.
COSMOS, COSMOSWorks, COSMOSMotion, and
COSMOSFloWorks are trademarks of Structural
Research and Analysis Corporation.
FeatureWorks is a registered trademark of
Geometric Software Solutions Co. Limited.
ACIS is a registered trademark of Spatial
Corporation.
GLOBEtrotter and FLEXlm are registered
trademarks of Globetrotter Software, Inc.
Other brand or product names are trademarks or
registered trademarks of their respective holders.

Document Number: PMT0077-ENG

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

API Fundamentals

Table of Contents

Introduction
About This Course . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Course Design Philosophy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Using this Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Windows XP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Conventions Used in this Book . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
About the CD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
File Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Option Explicit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Choosing Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
API Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
SolidWorks Constants Type Library . . . . . . . . . . . . . . . . . . . . . . . 7
Macro Recording Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
SolidWorks 2006 API Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
API Object Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Understanding API Interface Member Descriptions . . . . . . . . . . 10

API Fundamentals

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
User Preferences - System Options . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Setting Checkboxes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Setting Textboxes with Integers . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Setting Textboxes with Doubles . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Setting Textboxes with String Values . . . . . . . . . . . . . . . . . . . . . 87
Setting Listboxes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Setting Radio Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Setting Slider Bars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
User Preferences - Document Properties . . . . . . . . . . . . . . . . . . . . . . 90
Locating the Correct APIs and Enumeration Values . . . . . . . . . . . . . 91
UserPreference Tables For System Options . . . . . . . . . . . . . . . . . . . . 92
UserPreference Tables For Document Properties . . . . . . . . . . . . . . . 111
Exercise 6: Change Multiple System Options . . . . . . . . . . . . . . . . . 123
Exercise 7: Change Multiple Document Properties . . . . . . . . . . . . . 125
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

Establishing the Face Collection. . . . . . . . . . . . . . . . . . . . . . . . . 151


Getting Adjacent Faces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
Establishing the Points Collection . . . . . . . . . . . . . . . . . . . . . . . 153
Getting Curve Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Adding and Mating the Knobs to the Chassis. . . . . . . . . . . . . . . 154
Adding Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Adding Mates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Exercise 9: Adding Components . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Lesson 6:
Drawing Automation
Case Study: Automating Drawing Creation . . . . . . . . . . . . . . . . . . . 161
Getting Configuration Names. . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Creating Sheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
Creating Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
Inserting Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
Traversing Drawing Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
Saving Drawings in Different Formats. . . . . . . . . . . . . . . . . . . . 170
Drawing Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Annotation Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Layer Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Line Format Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Exercise 10: Drawing Automation . . . . . . . . . . . . . . . . . . . . . . . . . . 173
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

Case Study: Feature Manager Traversal . . . . . . . . . . . . . . . . . . . . . . 192


Traversing the FeatureManager from the Top . . . . . . . . . . . . . . 192
Displaying Feature Names and Types . . . . . . . . . . . . . . . . . . . . 193
Setting Feature Suppression . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
Setting Feature UI State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
Obtaining a Feature by FeatureManager Position . . . . . . . . . . . 197
Exercise 11: Handling Preselection 1 . . . . . . . . . . . . . . . . . . . . . . . . 199
Exercise 12: Handling Preselection 2 . . . . . . . . . . . . . . . . . . . . . . . . 201
Exercise 13: Traversing the FeatureManager . . . . . . . . . . . . . . . . . . 203
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

Case Study: C++ Add-Ins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255


Compiling a C++ Add-In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Loading the C++ Add-In. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
Debugging the C++ Add-in . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
Choosing a Programming Language. . . . . . . . . . . . . . . . . . . . . . . . . 263
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

Other Areas of Customization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302


Custom Status Bars. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Custom Pop-up Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
Custom ModelView Windows . . . . . . . . . . . . . . . . . . . . . . . . . . 303
Exercise 16: Implement a New Menu. . . . . . . . . . . . . . . . . . . . . . . . 305
Exercise 17: Implement Toolbar Buttons . . . . . . . . . . . . . . . . . . . . . 307
Exercise 18: Implement Controls on a Property Manager Page . . . . 309
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
Appendix
Macro Feature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
Batch Conversion 1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
Batch Conversion 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
Assembly Traversal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
Custom Model View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358

vii

API Fundamentals

viii

API Fundamentals

Introduction

API Fundamentals
Introduction

API Fundamentals
Introduction

About This
Course

The goal of this course is to introduce you to the SolidWorks 2006


Application Programming Interface (API). The API is used to automate
redundant and lengthy design tasks using SolidWorks. It is also used to
create complete engineering applications that run inside or outside of
the SolidWorks application. Everything a user leverages through the
SolidWorks user interface can be automated by programming it
through the API. The SolidWorks API is so robust and feature rich that
it is impractical to cover every detail and still have the course be a
reasonable length. Therefore, the focus of this course is on the
fundamental skills and concepts central to successfully building
automation tools. Once you have developed a good foundation in basic
skills, you can use the on-line help to collect information on more
functionality available in the API.

Prerequisites

Students attending this course are expected to have:


I
I
I
I

Mechanical design experience.


Completed the course SolidWorks Essentials: Parts, Assemblies,
and Drawings.
Experience with the Windows operating system.
Experience with Visual Basic.

Course Design
Philosophy

This course is designed around a process or task based approach to


training. Rather than focus on individual features and functions, a
process-based training course emphasizes the process and procedures
you follow to complete a particular task. By utilizing case studies to
illustrate these processes, you learn the necessary objects and functions
in the context of completing a programming task.

Using this Book

This training manual is intended to be used in a classroom environment


under the guidance of an experienced SolidWorks API instructor. It is
not intended to be a self-paced tutorial. The examples and case studies
are designed to be demonstrated live by an instructor.

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.

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.

About This Course

API Fundamentals
Introduction

Conventions Used
in this Book

This manual uses the following typographic conventions:


Convention
Bold Sans Serif

SolidWorks commands and options appear in


this style. For example, View, Toolbars
means choose the Toolbars option from the
View menu.

Typewriter

Feature names and file names appear in this


style. For example, Macro1.swp.

Lucida Console

Sample code appears in this style. Colors of


the text have special meaning. Gray is used to
identify code that has already been entered.
Black and Blue indicates code to be entered.
Red indicates code to be removed. Green
indicates code to be commented. These color
conventions follow those of Microsoft
Visual Basic.

17 Do this step

About the CD

Meaning

Double lines precede and follow sections of


the procedures. This provides separation
between the steps of the procedure and large
blocks of explanatory text. The steps
themselves are numbered in sans serif bold.

Bound inside the rear


cover is a CD containing
copies of the parts,
assemblies, drawings,
templates, macros and
projects that are used
throughout this course.
They are organized by
lesson in two folders:
Case Study and
Exercises.
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.

About This Course

API Fundamentals
Introduction

Getting Started

There are a few things a programmer should note before recording a


macro in SolidWorks or writing an application in Visual Basic that
connects to SolidWorks.

File Types

In SolidWorks 2006, the macro files we will create are of type:


SW VBA Macros (*.swp)
In Visual Basic.Net these files may be necessary:
Solution Files (*.sln)
Source Code Files (*.vb)
.NET Assembly / Dynamic-Link Library (*.dll)

Option Explicit

It is strongly recommended that you use the Option Explicit


statement in Visual Basic development. By doing this, the Visual Basic
compiler forces you to declare of all variables before use.

In Visual Basic.NET this option can be turned on globally from the


Tools, Options... then use the Projects, VB Defaults dialog box.
Variables

Variables are used to store temporary values during the execution of an


application. Variables are made up of two parts: Name and Data Type.
Essentially, a variable is a place holder in memory for an unknown
value. Declaring a variable tells the program about it in advance. You
declare a variable with the Dim statement, supplying a name for the
variable:
Dim variablename [As data type]
The optional, As data type, clause in the Dim statement allows you to
define the data type or object type of the variable. It is good practice to
define the type when you declare it. This will make the runtime set
aside the required amount of memory ahead of time instead of having
to dynamically resolve the amount of memory needed at run time. If
you let the runtime decide, it may allocate larger chunks of memory
then what is really required.

Getting Started

API Fundamentals
Introduction

Choosing Data
Types

Visual Basic supports these standard types of data:


- holds characters. To make sure a variable is of this type, use
($) after the variable name.

String

Integer -

holds numeric values between -32,768 and +32,767. To


make sure a variable is of this type, use (%) after the variable name.
Integer - holds numeric values between -2,147,483,648 and
+2,147,483,648. To make sure a variable is of this type, use (&) after
the variable name.

Long

Precision - holds numeric values with decimal points, accurate


to seven digits. To make sure a variable is of this type, use (!) after the
variable name.

Single

Precision - holds numeric values with decimal points, accurate


to sixteen digits. To make sure a variable is of this type, use (#) after
the variable name.

Double

Decimal -

supports up to 29 significant digits and can represent values


up to 7.9228 x 1028. It is particularly suitable for calculations, such as
financial, that require a large number of digits but cannot tolerate
rounding errors.
- holds date and time values between Jan 1, 1000 to midnight on
December 31, 9999. To make sure a variable is of this type, surround
assigned date with (# #)

Date

Byte

- holds integer values between 0 and 255

Boolean -

holds values that are either True or False

Variant -

holds values of all data types

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

reference assigned to it.


The Dim statement declares, or dimensions, a variable name to hold
onto a given type.
Dim
Dim
Dim
Dim

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

SolidWorks
Constants Type
Library

For SolidWorks API development, you should include the


SolidWorks 2006 Constant type library to each project. This type
library provides definitions used with SolidWorks API methods. The
constants are passed to methods instead of the number values they
represent. This ensures that when you install a new version of
SolidWorks, the code will work the same as it did in the last release.
The number values can change from release to release. The constant
values will not change, they will only be appended to.
If you record a macro using the VBA environment in SolidWorks the
type library will be automatically included. To check this, edit a macro
recorded in SolidWorks 2006, and choose Tools, References... from
the menu. The References dialog box will show you the type libraries
that are included in your project. Notice that there are two SolidWorks
type libraries used in each project.
We will discuss the SldWorks 2006 Type Library in more detail in
Chapter 2.

Note

Getting Started

Consider the case when a programmer forgets to include the


SolidWorks constants type library in their macro or project. If the code
tries to use a non-existent enumeration value from the constants type
library, and Option Explicit was not used, the Visual Basic runtime
silently initializes the enumeration values to 0 or empty. This scenario
could really confuse the programmer as to why the code was not
behaving the way the programmer intended. If Option Explicit was
used, and the constants type library was missing from the project, the
compiler would warn the programmer that the enumeration value does
not exist. Immediately the programmer would realize that the
SolidWorks constants type library was missing from the project.

API Fundamentals
Introduction

Macro
Recording Tips

Recording a macro is a great starting point for capturing basic


functionality. However, be aware that not all API functionality is
recorded.
I

I
I

Use the macro recorder as a tool for building larger applications


from small applications. Record a few steps at a time. Many
recordings can be placed into a single routine.
Plan the steps before recording a macro.
Limit the number of view changes you make while recording. All
view changes get added to the recorded macro. Opt for multiple
recordings instead of a single recording, if necessary.
If you need to change views while recording, remove extraneous
code entries after the recording is completed, such as:
Part.ActiveView().RotateAboutCenter

Remove unnecessary ClearSelection calls if there is a call to


SelectByID or SelectByMark immediately after. Any SelectByID or
AndSelectByID calls that appear just before a ClearSelection call is
extraneous. Calls just after are not.

SolidWorks 2006
API Help

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

Interface is the term used to describe the COM mechanism used to


wrap the actual class object that is used in SolidWorks. SolidWorks
software was designed using object-oriented programming techniques.
Under the hood of SolidWorks is a vast object model that represents
every aspect of the software. To expose an API to programmers using
other languages, COM programming allows SolidWorks to expose
functionality of actual SolidWorks objects to the outside world. COM
programming is beyond the scope of this book, however you should
understand that the API is made up of a group of interfaces that are
organized into an interface object model. Commonly you will refer to
an interface as an object, these terms are synonymous. Remember that
you are really working with interface pointers to the objects that they
represent in SolidWorks.

Macro Recording Tips

API Fundamentals
Introduction

Contents

The Contents tab of the API help file contains the following sections:

SolidWorks 2006 API Release Notes - This part of the help file has

information on new functionality released in SolidWorks 2006.


Included in this section are new interfaces, methods, properties and
events in the API object model.
Programmers Guide - Useful information on getting started in Visual
Basic, and programming topics such as adding macros to a menu,
notifications, units, return values, and using safe arrays.
Examples - Code examples ranging from creating compound notes to
getting curve spline points.
APIs - A complete documentation of the all interfaces and their

methods, properties, and events supported in the SolidWorks API.


Obsolete APIs - This part of the help file has information on APIs that
are obsolete in SolidWorks 2006.

Index

The Index tab of the API help file


allows you to quickly locate API
topics through its alphabetically
ordered list of keywords.

Search

The Search tab of the API help


file allows you to search for
keywords on every page of the
API help file.

Macro Recording Tips

API Fundamentals
Introduction

Understanding API
Interface Member
Descriptions

1
2

3
4
5
6

1. API Member Name - Used to describe the API interface member. It


is written with a general syntax name for clarity (Object::Member).
The object name in this case is SldWorks. The double colons
indicate where to place an access operator (a period). The member
name (a method in this case) is ArrangeWindows, which cannot be
changed.
2. API Interface Diagram and Member Links- Diagrams to show
where the currently selected API interface fits into the SolidWorks
object model.
3. API Description - This is an explanation of the API interface or the
selected members functionality.
4. Syntax (OLE Automation) - This section describes the OLE
syntax for using this interface object member. (commonly used by
VB programmers.)

10

Macro Recording Tips

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

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:

This call, retval = SldWorks.NewPart is written in VBA:


Dim swPart As Object
Set swPart = swApp.NewPart

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.
swModel.CreateLine2(0,0,0,1, 0,0).ConstructionLine = true

Macro Recording Tips

11

API Fundamentals
Introduction

6. Input - Describes how to declare those parameters (if the API


member requires parameters). In this case, (long) style tells us that a
parameter called style must be declared as type long in order for the
API to work properly. In Visual Basic, the declaration is written
above our API call.
Dim style As Long
style = 1
swApp.ArrangeWindows (style)

Or, we could remove the dim statement and simply put 1:


swApp.ArrangeWindows 1

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.
9. Remarks - Contains notes to the programmer about using the
member. Before using any member spend time reading this section
if there is information available.

12

Macro Recording Tips

API Fundamentals

Lesson 1
Using the Macro Recorder

Upon successful completion of this lesson, you will be able to:


I

Understand what a macro is, and how a macro can be used to


automate SolidWorks.

Identify each button on the Macro toolbar.

Record your first macro and edit the code using Microsoft Visual
Basic for Applications.

Customize a Macro toolbar button to run your macro.

Understand how the macro begins a procedure and connects to


SolidWorks.

Improve macro recorder default code.

Debug a macro.

Add forms and controls that allow a user to interact with the macro.

13

Lesson 1
Using the Macro Recorder

14

API Fundamentals

API Fundamentals

Lesson 1
Using the Macro Recorder

Macro
Recording

You can record operations performed with the SolidWorks user


interface and replay them using SolidWorks macros. A macro contains
calls to the Application Programming Interface (API) that are
equivalent to operations performed in the user interface. A macro can
record mouse clicks, menu choices and keystrokes.

Macro Toolbar

The Macro toolbar contains shortcuts to the


macro recording commands. You can also
access these commands from the Tools,
Macro menu.
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

allows the user to begin or pause macro recording.

New
performs three steps: First, it launches the New Macro dialog
box where the user enters a valid name for the macro.

Next, the macro file is populated with standard lines of programming


code to connect to SolidWorks.
Finally, the VBA editor opens the macro file for the user to begin
programming.
launches the Edit Macro dialog box for selecting the macro to
Edit
view or modify.
allows the user to customize a button on the Macro toolbar.
Custom
An image is selected, a file path to a macro is set, and the custom
button is dragged onto the Macro toolbar for use.

Macro Recording

15

Lesson 1

API Fundamentals

Using the Macro Recorder

Start SolidWorks and create a new part.

For this part, use millimeters as the default units.


2

View the Macro toolbar.


From the View menu, choose Toolbars, Macro.

Click Record

Select the Front plane.

Click Sketch

Click Circle

.
.

Use an approximate radius of 40 millimeters, then enter the exact value


of 40 mm in the PropertyManager.

16

Macro Toolbar

API Fundamentals

Lesson 1
Using the Macro Recorder

Click Extruded Boss/Base

Drag the extrude path approximately 15 millimeters, then enter the


exact value of 15 mm in the PropertyManager. Click OK.

8
9

Click Stop

Save the macro.

In the Save As dialog, save the macro as Macro1.swp.


10 Delete all features.

Remove the extruded base and sketch created previously.


11 Click Play

Select Macro1.swp from the previous step.

Macro Toolbar

17

Lesson 1

API Fundamentals

Using the Macro Recorder

Automation Review

Lets take a look at how much weve automated so far with this simple
macro
Click 1 - Select a plane.
Click 2 - Insert sketch command.
Click 3 - Create circle command.
Click 4 - Center of circle.
Click 5 - Approximate 40 mm radius of circle.
Keyboard Entry 1 - Exact radius: 40 mm.
Click 6 - OK button.
Click 7 - Extruded boss/base button.
Click 8 - Approximate 15 mm depth of extrusion.
Keyboard Entry 2 - Exact depth: 15 mm.
Click 9 - OK button.

Total Clicks: 9
Total Keyboard Entries: 2
All of the users input and time is eliminated simply by running the
macro.
12 Customize the Macro
toolbar.
From the Tools menu,
choose Customize....

On the Commands tab,


highlight the Macro
category.
Drag the Custom
Macro button from the
display dialog and drop
it onto the Macro
toolbar.

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

13 Program a custom button.

When the new button is dropped on a


toolbar, the
Customize Macro Button dialog
appears automatically.
Set the Macro field to launch
Macro1.swp by browsing for the
file. The Method field will update
automatically with available sub
routines in the file.
Keep the default image, and enter
helpful text for the Tooltip and Prompt (optional).
Click OK.
14 Click Custom Macro

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.
15 Visual Basic for Applications editor.
Click the Edit
button from the Macro toolbar.

Select Macro1.swp.

Macro Toolbar

19

Lesson 1

API Fundamentals

Using the Macro Recorder

Understanding
How Macro
Code Works
Variable
Declaration
The macro recorder declares
(or dimensions) a number of
variables by default.
You can comment out or delete
variables not utilized in the
entry point procedure.

Entry Point
Procedure

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:
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
Sub main()

This is the beginning of our


functionality. Every macro
must establish an entry point
procedure.

SolidWorks
Application Object

Set swApp = Application.SldWorks

This line of code will start an


instance of SolidWorks or
connect to a running instance of
SolidWorks. Without it, your
program will not run.

SolidWorks
Document Object

Set Part = swApp.ActiveDoc

In order for us to work within


the application, top-level
document objects are accessed
and made active. This allows
the ability to program
document specific functionality

SolidWorks
API Calls
An API call allows the macro
to perform certain tasks.
This is where we see our
recorded steps taking shape:
- Selecting a plane
- Inserting a sketch
- Creating a circle
- Extruding a feature

Procedure End

20

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 0, 0, 0, 0.043409,-0.003803, 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.01, 0.01, False, False, False, False, 0.017453, _
0.017453, False, False, False, False, 1, 1, 1, 0, 0, False
Part.SelectionManager.EnableContourSelection = 0
End Sub

Understanding How Macro Code Works

API Fundamentals

Lesson 1
Using the Macro Recorder

Understanding
How to Call
Members on
API Interfaces

API members, often referred to as events, properties, methods,


functions or simply APIs, are called to interact with the actual object
members that are exposed by the SolidWorks application.
In order to call members on API objects, a few steps are required.
1. Declare and instantiate the highest level object in the SolidWorks
API. The API represents this object as SldWorks. A macro will use
the default name swApp for this variable declaration.
Dim swApp As Object
Set swApp = Application.SldWorks

2. Declare and instantiate a document object. The following lines of


code declare the variable used to store the documents object
pointer. Then it instantiates this object by calling an accessor
method on the SldWorks object.
Dim Part As Object
Set Part = swApp.ActiveDoc

3. Once the application and document objects are instantiated,


members on those objects are called. To access these members the
object name is written first, separated by a period, and followed by
the full name of the API call:
Part.InsertSketch2 True

Some APIs members require additional parameters such as the


following method call:
Part.CreateCircleByRadius2 0, 0, 0, 0.04

Some APIs require additional objects:


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

Some APIs utilize return values:


Dim boolstatus As Boolean
boolstatus = Part.Extension.SelectByID2("Front Plane", _
"PLANE", 0, 0, 0, False, 0, Nothing, 0)

Understanding How to Call Members on API Interfaces

21

Lesson 1

API Fundamentals

Using the Macro Recorder

Passing
Parameters

As you begin developing productivity tools for SolidWorks it will


become clear that your code will not run properly unless every
parameter within an API call is satisfied. To learn more about specific
API calls we turn to the API help file. Lets explore one of our lengthy
calls, FeatureManager::FeatureExtrusion, which has 20 parameters.

FeatureManager::FeatureExtrusion2
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

Pointer to the feature object.

Input:

sd

TRUE

for single ended, FALSE for double ended.

Input:

flip

TRUE

to flip the direction to cut.

Input:

dir

TRUE

to flip the direction to extrude.

Input:

t1

Termination type for first end from


swEndConditions_e enumeration.
swEndCondBlind
swEndCondThroughAll
swEndCondThroughNext
swEndCondUpToVertex
swEndCondUpToSurface
swEndCondOffsetFromSurface
swEndCondMidPlane
swEndCondUpToBody

Input:

t2

Termination type for second end from


swEndConditions_e enumeration.
(see above)

Input:

d1

Depth of extrusion for first end in meters.

Input:

d2

Depth of extrusion for second end in meters.

Input:

dchk1

allows draft angle in first direction, FALSE does


not allow drafting.

Input:

dchk2

allows draft angle in second direction, FALSE


does not allow drafting.

Input:

ddir1

for first draft angle to be inward, FALSE to be


outward.

Input:

ddir2

for second draft angle to be inward, FALSE to be


outward.

Input:

dang1

Draft angle for first end.

Input:

dang2

Draft angle for second end.

22

TRUE

TRUE

TRUE

TRUE

Passing Parameters

API Fundamentals

Lesson 1
Using the Macro Recorder

Input:

offsetReverse1

If you chose to offset the first end condition from


another face or plane, then TRUE specifies offset in
direction away from the sketch, FALSE specifies offset
from the face or plane in direction toward the sketch.

Input:

offsetReverse2

If you chose to offset the second end condition from


another face or plane, then TRUE specifies offset in
direction away from the sketch, FALSE specifies offset
from the face or plane in direction toward the sketch.

Input:

translateSurface1

When you choose swEndcondOffsetFromSurface as


the termination type for the first end, then TRUE
specifies that the end of the extrusion is a translation
of the reference surface, FALSE specifies to use a true
offset.

Input:

translateSurface2

When you choose swEndcondOffsetFromSurface as


the termination type for the second end, then TRUE
specifies that the end of the extrusion is a translation
of the reference surface, FALSE specifies to use a true
offset.

Input:

merge

TRUE to merge the results in a multibody part, FALSE to

not.
Input:

useFeatScope

TRUE if the feature only affects selected bodies, FALSE


if the feature affects all bodies.

Input:

useAutoSelect

to automatically select all bodies and have the


feature affect those bodies, FALSE to select the bodies
the feature affects
When useAutoSelect is FALSE, the user must select
the bodies that the feature will affect. When using cut
or cavity features that result in multiple bodies, you
cannot select to keep all of the resulting bodies or one
or more selected bodies.

Input:

t0

Start condition from swStartConditions_e


enumeration.

TRUE

swStartSketchPlane
swStartSurface
swStartVertex
swStartOffset

Input:

startOffset

If t0 set to swStartOffset, then specify offset value.

Input:

flipStartOffset

If t0 set to swStartOffset, then TRUE to flip the


direction or FALSE to not.

Passing Parameters

23

Lesson 1

API Fundamentals

Using the Macro Recorder

Cleaning Up
Code

Never be satisfied with results the SolidWorks macro recorder returns.


Always look to improve and clean up your code. Macro code usually
needs to be edited to complete your automation task.
Option Explicit

These comments are not


functional and can be deleted.

'**********************************************************
' Macro1.swb - macro recorded on ##/##/##
'**********************************************************
Dim swApp As Object
Dim Part As Object

This variable is not needed

Dim SelMgr As Object


Dim boolstatus As Boolean

These variables are not needed.


They can be deleted or
commented for later use.

Dim longstatus As Long, longwarnings As Long


Dim Feature As Object
Sub main()
Set swApp = Application.SldWorks
Set Part = swApp.ActiveDoc

This call is unnecessary

Set SelMgr = Part.SelectionManager


boolstatus = Part.Extension.SelectByID2("Front Plane", _
"PLANE", 0, 0, 0, False, 0, Nothing, 0)
Part.InsertSketch2 True
Part.ClearSelection2 True

See Note below.

Part.CreateCircle 0, 0, 0, 0.03394, 0.02555, 0

These calls are unnecessary.

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.015, 0, False, False, False, False, 0.01745, 0.01745, _
False, False, False, False, 1, 1, 1, 0, 0, False

This call is unnecessary.

Part.SelectionManager.EnableContourSelection = 0
End Sub

Note

The SolidWorks API has thousands of API calls to choose from. Be


aware that it is not necessary to settle for the API calls that the macro
recorded returns. We can use the online API help file in SolidWorks to
search out new, improved or just alternative API calls for our needs.
For this example, there is another way to create a circle (other than the
method that the macro recorder captured.) CreateCircle requires six
parameters: xc, yc, zc, xp, yp, zp. This method creates a circle based on
a center point and a point on the circle. Thats fine, but not exactly what
we performed with the user interface. We clicked the center point and
entered a radius in the PropertyManager. The API help file highlights a
similar call, CreateCircleByRadius2, and only requires these
parameters: xc, yc, zc, radius. This API call is more in line with what
we performed manually and it is perfectly okay to use as a replacement.

24

Cleaning Up Code

API Fundamentals

Lesson 1
Using the Macro Recorder

Tip

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.
ModelDoc2 is the current version of the SolidWorks document pointer.
Although the older versions may continue to show up and be functional
in newer releases of SolidWorks, they are generally left there so that
older software that used those APIs will still work. In many cases older
APIs may have a shorter parameter list and you may feel compelled to
use them because less typing is required.
The method SldWorks.SendMsgToUser, for example, has two versions.
The older version requires one parameter. For testing code it is
convenient to use this method because you dont have to satisfy the
four parameters required by SendMsgToUser2. That may be okay for
your simple utility or for testing, but for production quality code you
should use the latest versions of the APIs. This will eliminate problems
when your program is run on a newer version of SolidWorks.

Commenting Code

Now that weve identified what lines of code to remove or modify, we


can insert comments. To add comments to the code, prefix the
comment with an apostrophe character. The apostrophe tells the
compiler to ignore anything on that line that follows it.
16 Modify the code.

Modify the code and add comments. Also change the code to use
CreateCircleByRadius2 instead of CreateCircle.
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

Using the Macro Recorder

Debugging Code

Although this manual does not go into detail about debugging


techniques for Visual Basic, it is important to use debugging practices
throughout the course. The next few steps are designed to help get you
familiar with how to debug code.
17 Add a breakpoint.

Click in the column to the left of our entry point procedure to add a
breakpoint:
Breakpoint

18 Debug the macro.


Press F5 to start debugging. The macro stops at the breakpoint to allow

the programmer to step through the code.

26

Cleaning Up Code

API Fundamentals

Lesson 1
Using the Macro Recorder

19 Begin stepping into code.


Press F8 to enter the procedure (yellow highlight will move).

20 Press F8.

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

Using the Macro Recorder

22 Press F8.

Note

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.
23 Continue to end of code.
Press F5.

Alternatively, we can continue stepping into the code as before, line by


line, until the end of the procedure.

Adding Forms
to a Macro

To provide a user interface to your


program, add a userform to the
macro.

Where to Find It

I
I

In VBA, click Insert, UserForm.


In VBA, within the Project Explorer window, right-click the
macro and select Insert, UserForm.

The VBA Toolbox is displayed along with the form by default. If it


does not appear click View, Toolbox.

28

Adding Forms to a Macro

API Fundamentals

Lesson 1
Using the Macro Recorder

24 Add a userform to the macro.


In VBA, click Insert, UserForm.
25 Edit the userform properties.

With the userform highlighted, enter the


following property values into the properties
window for this userform object:
UserForm1:
(Name): frmMacro1a
Caption: Cylinders
Startup Position: 2 - CenterScreen
ShowModal: False

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.

Tip

26 Add controls to the form.

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
CommandButton3:
(Name): cmd1m
Caption: 1 m
CommandButton4:
(Name): cmd5m
Caption: 5 m
CommandButton5:
(Name): cmdExit
Caption: Exit

Adding Forms to a Macro

29

Lesson 1

API Fundamentals

Using the Macro Recorder

27 Add a click event to each button.

Double-click each button on the form to set up a button click event


handler for these controls. When you double-click each button, the
VBA environment automatically adds a skeleton event handler to the
source code. The code that you will add to the event handlers will run
when the user clicks the button when your macro is running.
Private Sub cmd100mm_Click()
End Sub
Private Sub cmd500mm_Click()
End Sub
Private Sub cmd1m_Click()
End Sub
Private Sub cmd5m_Click()
End Sub
Private Sub cmdExit_Click()
End Sub

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.
28 Move code from the module to the button events.

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.
Private Sub cmd100mm_Click()
Dim swApp As Object
Dim Part As Object
Dim boolstatus As Boolean
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.1, 0, False, False, False, False, 0.01745,0.01745, _
False, False, False, False, 1, 1, 1, 0, 0, False
End Sub

30

Adding Forms to a Macro

API Fundamentals

Lesson 1
Using the Macro Recorder

Private Sub cmd500mm_Click()


Dim swApp As Object
Dim Part As Object
Dim boolstatus As Boolean
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.5, 0, False, False, False, False, 0.01745, 0.01745, _
False, False, False, False, 1, 1, 1, 0, 0, False
End Sub
Private Sub cmd1m_Click()
Dim swApp As Object
Dim Part As Object
Dim boolstatus As Boolean
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, 1, 0, False, False, False, False, 0.01745, 0.01745, _
False, False, False, False, 1, 1, 1, 0, 0, False
End Sub
Private Sub cmd5m_Click()
Dim swApp As Object
Dim Part As Object
Dim boolstatus As Boolean
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, 5, 0, False, False, False, False, 0.01745, 0.01745, _
False, False, False, False, 1, 1, 1, 0, 0, False
End Sub

Adding Forms to a Macro

31

Lesson 1

API Fundamentals

Using the Macro Recorder

29 Program the Exit button.


Private Sub cmdExit_Click()
End
End Sub

30 Add code to the module.

In order for the userform to appear in SolidWorks, the entry point


procedure on the module needs to show the userform. Enter the
following line of code:
Sub main()
frmMacro1a.Show
End Sub

31 Save and run the macro.

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

32 Exit the macro.


Click the Exit button to end the macro and return to VBA.
33 Add a second userform.
Click Insert, UserForm. Enter the following property values:
UserForm2:
(Name): frmMacro1b
Caption: Custom Cylinder
Startup Position: 2 - CenterScreen
ShowModal: False

32

Adding Forms to a Macro

API Fundamentals

Lesson 1
Using the Macro Recorder

34 Add controls to the second form.

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.
TextBox1:
(Name): txtDiameter
Text: <leave blank>
TextBox2:
(Name): txtDepth
Text: <leave blank>
CommandButton1:
(Name): cmdBuild
Caption: Build
CommandButton2:
(Name): cmdExit
Caption: Exit

35 Add code to each button.

We want each string value in the text boxes to be converted to a double


value for diameter and depth. Make a copy of the working code you
already have from one of the buttons on frmMacro1a and paste into a
click event for cmdBuild on frmMacro1b. Then make the
adjustments to the code:
Private Sub cmdBuild_Click()
Dim swApp As Object
Dim Part As Object
Dim boolstatus As Boolean
Dim diameter As Double
Dim depth As Double
diameter = CDbl(txtDiameter.Text) / 1000
depth = CDbl(txtDepth.Text) / 1000
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, diameter / 2
Part.FeatureManager.FeatureExtrusion2 True, False, False, 0,_
0, depth, 0, False, False, False, False, 0.01745, _
0.01745, False, False, False, False, 1, 1, 1, 0, 0, False
End Sub

Adding Forms to a Macro

33

Lesson 1

API Fundamentals

Using the Macro Recorder

36 Program the Exit button.


Private Sub cmdExit_Click()
End
End Sub

37 Add code to the module.

In order for the userform to appear in SolidWorks, the entry point


procedure on the module needs to show the userform. Enter the
following line of code:
Sub main()
frmMacro1b.Show
End Sub

38 Save and run the macro.

10
50

39 Exit the macro.

34

Adding Forms to a Macro

API Fundamentals

Exercise 1:
Recording a Macro

Exercise 1:
Recording a
Macro

Objective

To familiarize yourself with the starting point of API programming:


the macro recorder. The recorder captures the methods necessary for
interacting with the SolidWorks application. By recording macros, you
are able to automate repetitive tasks in SolidWorks, such as extruding,
revolving, suppressing, and selecting.

Skills Learned

I
I

Recording, saving, and playing a macro.


Customizing the Macro toolbar.

APIs Used

SldWorks.ActiveDoc
ModelDocExtension.SelectByID2
ModelDoc2.InsertSketch2
ModelDoc2.CreateCircle
FeatureManager.FeatureExtrusion2

Procedure

1.
2.
3.
4.
5.
6.
7.
8.
9.

Open a new part file in SolidWorks.


Display the Macro toolbar.
Click Record Macro.
Perform the steps to extrude a cylinder: R20 mm x 80 mm (see
case study).
Click Stop Macro.
Save the macro in a temporary location.
Customize the Macro toolbar to run the macro.
Open a new part file in SolidWorks.
Play custom macro.

35

Exercise 1:

API Fundamentals

Recording a Macro

Solution

Option Explicit
Dim
Dim
Dim
Dim
Dim
Dim

swApp As Object
Part As Object
SelMgr As Object
boolstatus As Boolean
longstatus As Long, longwarnings As Long
Feature As Object

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

Exercise 2:
Adding Macro
Code to a VBA
Button Control

Objective

To edit a SolidWorks macro in VBA and automate the feature creation


process with a simple form.You will use the editing tools in VBA to
paste a recorded macro into the click event of several command buttons
to create a simple automation tool.

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.

APIs Used

SldWorks.ActiveDoc
ModelDocExtension.SelectByID2
ModelDoc2.InsertSketch2
ModelDoc2.CreateCircleByRadius2
FeatureManager.FeatureExtrusion2

Procedure

1.
2.
3.
4.
5.

Open a new part file in SolidWorks.


From the Macro toolbar, click Edit Macro.
Select the macro from the previous exercise.
Insert a userform.
Drag and drop a label and five command button controls onto the
form. Four of the buttons are for different extrusion lengths, and the
fifth is to exit the macro.
6. Cut the code within the entry point procedure from the module and
paste the code into the click event procedures for the extrusion
command buttons. Change the depth of the extrusions for each
button by incrementing them by 10mm.
7. Add code to the fifth button to exit the macro.
8. Modify the entry point procedure to display the userform.
9. Use an alternative method to create the sketch circle.
10. Play the macro from VBA and test to see if the form loads and the
command button works.

37

Exercise 2:

API Fundamentals

Adding Macro Code to a VBA Button Control

Solution

Option Explicit
Sub main()
frmMacro1a.Show
End Sub
--------------------------------------------------------------Option Explicit
Private Sub cmd10mm_Click()
Dim swApp As Object
Dim Part As Object
Dim boolstatus As Boolean
Set swApp = Application.SldWorks
Set Part = swApp.ActiveDoc
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.01, 0, False, False, False, False, 0.01745, _
0.01745, False, False, False, False, 1, 1, 1, 0, 0, False
End Sub
Private Sub cmd20mm_Click()
Dim swApp As Object
Dim Part As Object
Dim boolstatus As Boolean
Set swApp = Application.SldWorks
Set Part = swApp.ActiveDoc
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.02, 0, False, False, False, False, 0.01745, _
0.01745, False, False, False, False, 1, 1, 1, 0, 0, False
End Sub

Private Sub cmd30mm_Click()


Dim swApp As Object
Dim Part As Object
Dim boolstatus As Boolean
Set swApp = Application.SldWorks
Set Part = swApp.ActiveDoc
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.03, 0, False, False, False, False, 0.01745, _
0.01745, False, False, False, False, 1, 1, 1, 0, 0, False
End Sub

38

API Fundamentals

Exercise 2:
Adding Macro Code to a VBA Button Control

Private Sub cmd40mm_Click()


Dim swApp As Object
Dim Part As Object
Dim boolstatus As Boolean
Set swApp = Application.SldWorks
Set Part = swApp.ActiveDoc
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.04, 0, False, False, False, False, 0.01745, _
0.01745, False, False, False, False, 1, 1, 1, 0, 0, False
End Sub

Private Sub cmdExit_Click()


End
End Sub

---------------------------------------------------------------

39

Exercise 3:

API Fundamentals

Adding User Input Fields on a VBA Form

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

Adding textbox controls to a form.


Declaring variables and converting values from a text box.
Debugging code.

APIs Used

SldWorks.ActiveDoc
ModelDocExtension.SelectByID2
ModelDoc2.InsertSketch2
ModelDoc2.CreateCircleByRadius2
FeatureManager.FeatureExtrusion2

Procedure

1.
2.
3.
4.
5.

6.
7.
8.
9.

40

Open a new part file in SolidWorks.


Edit the macro from the previous exercise.
Insert a second userform.
Drag and drop five labels, two textboxes and two command buttons
onto the form.
Cut and paste macro code from one of the buttons on the first form
into the click event procedure for a command button labeled
Build on the second form.
Modify the entry point procedure to display the second form.
Add code that converts values from the text boxes and inserts them
into the methods for creating a circle and extruding a boss.
Add a breakpoint on the click event procedure for Build.
Step through the macro in debug mode. Test to see if the second
form loads and the textboxes and command buttons work.

API Fundamentals

Exercise 3:
Adding User Input Fields on a VBA Form

Solution

Option Explicit
Sub main()
frmMacro1b.Show
End Sub
--------------------------------------------------------------Option Explicit
Dim
Dim
Dim
Dim
Dim

swApp As Object
Part As Object
boolstatus As Boolean
radius As Double
depth As Double

Private Sub cmdBuild_Click()


radius = CDbl(txtRadius.Text) / 1000
depth = CDbl(txtDepth.Text) / 1000
Set swApp = Application.SldWorks
Set Part = swApp.ActiveDoc
boolstatus = Part.Extension.SelectByID2("Front", "Front _
Plane", 0, 0, 0, False, 0, Nothing)
Part.InsertSketch2 True
Part.CreateCircleByRadius2 0, 0, 0, radius
Part.FeatureManager.FeatureExtrusion2 True, False, False, 0,_
0, depth, 0.01, False, False, False, False, 0.01745, _
0.01745, False, False, False, False, 1, 1, 1, 0, 0, False
End Sub
Private Sub cmdExit_Click()
End
End Sub
---------------------------------------------------------------

41

Exercise 3:
Adding User Input Fields on a VBA Form

42

API Fundamentals

API Fundamentals

Lesson 2
The API Object Model

Upon successful completion of this lesson, you will be able to:


I

Recognize the object relationships and organization within the


SolidWorks API Object Model.

Connect your macro to the highest level application object in the


API Object Model: SldWorks.

Use accessors to connect your macro to the other application


objects: ModelDoc2, ModelDocExtension, PartDoc, AssemblyDoc
and DrawingDoc.

Identify common API methods specific to each application object.

Build a working macro with forms and controls that explores the
differences between each application object.

43

Lesson 2
The API Object Model

44

API Fundamentals

API Fundamentals

Lesson 2
The API Object Model

SolidWorks API
Object Model

The following diagram is a general depiction of the SolidWorks API


Object Model. In this lesson, we will begin learning how interface
objects in the API object model are organized and how they are
accessed. There is also a similar diagram in the online API help file.
For simplicity, there are several lower-level objects not shown.

designed to examine the


hierarchy of the
SolidWorks API object
model. You cannot access
API objects that are lower
in the hierarchy unless you
first access objects that are
higher in the object
hierarchy.
Take for instance the
ModelDoc2 interface. To
return an interface pointer
to ModelDoc2, The upper
level SldWorks object must
be connected to and then an
accessor must be called to
retrieve an interface pointer to ModleDoc2.

SolidWorks API Object Model

45

Lesson 2

API Fundamentals

The API Object Model

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
Automatic Type
Casting

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.)
Automatic type casting works in either direction. If an upper level
object called a method that existed on its derived child, the call would
also be successful. ModelDoc2.GetPartBox would be a valid API call
even though GetPartBox is implemented on the derived object
PartDoc.
Visual Basic hides some of the complexities of COM programming
from the inexperienced programmer, and helps them focus on the
programming task at hand rather than the complexities of COM
automation programming.
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

SolidWorks API Object Model

API Fundamentals

Lesson 2
The API Object Model

Application
Objects

SldWorks Object
(swApp)

This lesson introduces an assortment of API calls that connect to


SolidWorks and each document type. To use these API calls, you have
to first connect to a specific application object. The first object well
explore is the top level API interface called SldWorks.
The SldWorks object (declared swApp by the macro recorder), the
highest level object in SolidWorks, provides access to all other
objects exposed in the API. It is also referred to as an interface that
provides a general set of functions that allow application level
operations. Use the following two lines of code to connect to the
SldWorks object:
Dim swApp As SldWorks.SldWorks
Set swApp = Application.SldWorks

The variable, swApp, is arbitrary and is declared using a generic


type, Object, rather than a specific type, SldWorks.SldWorks. This is
discussed in Early vs. Late Binding on page 49. As we progress, it is
better practice to use early binding techniques when programming
with the SolidWorks API.
SldWorks Methods and Properties
.NewDocument (TemplateName, PaperSize, Width, Height)
.RevisionNumber
.DisplayStatusBar (OnOff)
.SolidWorksExplorer
.OpenDoc6 (FileName, Type, Options, Config, Errors, Warnings)
.LoadFile2 (FileName, ArgumentString)
.CreateNewWindow
.ArrangeWindows (Style)
.ActiveDoc
.ActivateDoc2 (Name, Silent, Errors)
.CloseDoc (Name)
.QuitDoc (Name)
.ExitApp
.DocumentVisible (Visible, Type)
.SendMsgToUser2 (Message, icons, buttons)

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

The API Object Model

Create a new macro.


Click the New Macro

button on the Macro toolbar.

Name the macro ObjectModel.swp.


2

Review the default macro code.

The following macro code should appear by default:


Dim swApp As Object
Sub main()
Set swApp = Application.SldWorks
End Sub

SolidWorks 2006
Type Library

Visual Basic programs are enhanced by creating objects with specific


interface types rather than the generic object type. In order to leverage
this, VBA adds a reference to the SolidWorks 2006 Type Library.
To make sure the reference is made, in VBA, click Tools, References
and the option for SolidWorks 2006 Type Library should be checked.

If it is not checked, browse to its location (installed with SolidWorks):


<install directory>\SolidWorks\sldworks.tlb
This file contains the definitions of all of the exposed API interfaces,
and their members that are available for SolidWorks automation. When
the type library is referenced, a drop down list after the dot (.) separator
(behavior known as IntelliSense) will display SolidWorks objects,
properties and methods available to the programmer.

48

Application Objects

API Fundamentals

Lesson 2
The API Object Model

IntelliSense

IntelliSense is a Microsoft technology that allows you to preview your


code choices by displaying class definitions, methods, properties,
parameters and comments as you type your code into the editor.
IntelliSense also minimizes typing because it will automatically
complete lines of code by allowing you to select your methods and
properties from a list.
Dim swApp As SldWorks.sld

Early vs. Late


Binding
Ligao tardia (Late)
vs.
Ligao antecipada (Early)

Binding is a process of matching function calls to the actual methods


and properties supported by the object being used.
To better understand early binding, think of binding in terms of a
librarian looking for a specific chapter in a book. If a librarian goes to
the card catalogue to find the book, the librarian can find out if the book
exists in the library. If the book was found, the librarian would then
have to go to the shelf where that book exists and look up a particular
chapter. If the book is not on that shelf, the card catalogue would have
an error. If the book was found and the chapter was missing from the
book, the book would have an error. In this scenario the librarian would
be equal to the compiler. The compiler looks up an object, and then
creates an indirect pointer to it. After this pointer is created, the
compiler looks at the objects table of contents (known as the v-table)
to see if a certain member exists on it. If the member is not found, the
compiler throws an error to the programmer.
By binding to an object at design time, you get an indirect pointer to the
object. The indirect pointer is created by the compiler and allows the
compiler to verify the objects contents at design time. The
programmer can also see its contents by using Intellisense. Creating
this indirect pointer at design time is known as early binding. To early
bind to an object, you declare it as the specific type of object it is
defined as in the type library it belongs to.
Late binding is what happens when you dont create the indirect pointer
at design time, and rely on the Visual Basic runtime to verify if the
object and its methods and properties exist. To do this, declare object
variables as Object (the generic Visual Basic data type) and allow the
runtime to determine whether or not the object exists in the type library
of the application you are programming for.

Application Objects

49

Lesson 2

API Fundamentals

The API Object Model

The following shows how to bind to objects in a type library:


I

Late Binding

Dim swApp As Object


Dim swModel As Object
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
End Sub
I

Early Binding

Dim swApp As SldWorks.SldWorks


Dim swModel As SldWorks.ModelDoc2
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
End Sub

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.

Tip

Change the macro 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

Test the IntelliSense drop down list.

Begin adding the following code until the IntelliSense appears:


Dim swApp As SldWorks.SldWorks
Sub main()
Set swApp = Application.SldWorks
swApp.setu

50

Application Objects

API Fundamentals

Lesson 2
The API Object Model

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.
5

Add Parameters using Intellisense.

Certain methods, like this one, have parameters. IntelliSense will


display this information right below the line of code and serve as a
guide for adding the parameter list and completing the API call
correctly.
Dim swApp As SldWorks.SldWorks
Sub main()
Set swApp = Application.SldWorks
swApp.SetUserPreferenceDoubleValue

End Sub

Close the macro.

You are finished testing IntelliSense and early binding.

Case Study:
Connecting to
New
Documents

The following steps show how to connect to the running instance of


SolidWorks and use members on this API interface. To save time
during this lesson, we have already completed creating the form and all
of the controls. In the previous chapter you learned how to add a form
and some controls to it to create a user interface for your program. In
this chapter you learn how to use other controls added to the form such
as the check box and the radio button.
1

Open the macro.

Navigate to the Lesson02 folder and open the macro named


ObjectModelBasics.SWP.
Tip

If the form is not visible in the VBA editor,


press Ctrl + R on the keyboard. The
Project Explorer window displays. Doubleclick on frmNewDocs under the Forms folder
to display the form in the editor.

Case Study: Connecting to New Documents

51

Lesson 2

API Fundamentals

The API Object Model

Review the top of the userform and control properties.

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:
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

Add the button click event.

Double-click the command button to set up the button click event


handler.
Private Sub cmdConnect_Click()
End Sub

Connect to the SldWorks object.

Add the following lines of programming code within the event:


Private Sub cmdConnect_Click()
Dim swApp As SldWorks.SldWorks
Set swApp = Application.SldWorks
End Sub

52

Case Study: Connecting to New Documents

API Fundamentals

Lesson 2
The API Object Model

Add SldWorks methods and properties.

Continue adding code within the event for the checkboxes:


Private Sub cmdConnect_Click()
Dim swApp As SldWorks.SldWorks
Set swApp = Application.SldWorks
If chkRevNum.Value = True Then
Dim retval As String
retval = swApp.RevisionNumber
MsgBox "9.0.0 = SolidWorks 2001 " & vbCrLf & _
"10.0.0 = SolidWorks 2001Plus " & vbCrLf & _
"11.0.0 = SolidWorks 2003" & vbCrLf & _
"12.0.0 = SolidWorks 2004 " & vbCrLf & _
"13.0.0 = SolidWorks 2005" & vbCrLf & _
"14.0.0 = SolidWorks 2006" & vbCrLf & _
"" & vbCrLf & _
"You are running " & retval
End If
If chkDispStatBar.Value = True Then
swApp.DisplayStatusBar True
Else
swApp.DisplayStatusBar False
End If
If chkSWExp.Value = True Then
swApp.SolidWorksExplorer
End If
End Sub

Add Code to Sub Main.

Switch back to the ObjectModelBasics1 module. Set up the entry


point procedure as follows:
Sub main()
frmNewDocs.Show
End Sub

Save and run the macro.

Try each of the checkboxes separately to test how SolidWorks behaves.


Follow this order:

Case Study: Connecting to New Documents

53

Lesson 2

API Fundamentals

The API Object Model

Macro Results

54

1.

2.

3.

Stop the macro.

Case Study: Connecting to New Documents

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)
The Topics Found dialog
shown to the right is taken from
the SolidWorks API help file.
It shows the dialog that appears
when you click the Accessors
link for ModelDoc2.

The ModelDoc2 object (swModel) contains functions that are


common to all three document types: parts, assemblies and
drawings. Use one of the following methods below on the SldWorks
object (also known as accessors) to connect to the ModelDoc object:

This is the dialog that allows us


to understand which methods
are available for successfully
connecting to objects further
down the Object Model.

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)

ModelDoc2 Methods and Properties


.InsertSketch2 (UpdateEditRebuild)
.InsertFamilyTableNew
.InsertNote
.SetToolbarVisibility (Toolbar, Visible)
.AddCustomInfo3 (Config, FieldName, FieldType, FieldValue)
.CreateCircle2 ( Xc, Yc, Zc, Xp, Xp, Xp )
.EditRebuild3
.FeatureManager
.InsertFeatureShell (Thickness, Outward)
.SaveAs4 (Name, Version, Options, Errors, Warnings)
.ViewZoomtofit2

Case Study: Connecting to New Documents

55

Lesson 2

API Fundamentals

The API Object Model

Over the years, enhancements to SolidWorks has increased the amount


of methods on the ModelDoc2 object to capacity (1,024). There is now
an extension object that serves as a interface for new methods, it is
called ModelDocExtension.
ModelDoc Extension Use the ModelDoc2 property, Extension, to connect to the
ModelDocExtension object:
Object
(swModelExt)
option 1 - get a pointer to the ModelDocExtension object
Dim swModelExt As SldWorks.ModelDocExtension
Set swModelExt = swModel.Extension
swModelExt.SelectByID2 (....)
swModelExt.GetMassProperties (....)

option 2 - call the Extension object directly from ModelDoc2


as a property without the need for ModelDocExtension pointer
Dim swModel As SldWorks.ModelDoc2
Set swModel = swApp.ActiveDoc
swModel.Extension.SelectByID2 (....)
swModel.Extension.GetMassProperties (....)

ModelDocExtension Methods and Properties


.SelectByID2 (Name, Type, X, Y, Z, Append, Mark, Callout,
SelectOption)
.GetMassProperties (Accuracy, Status)
The return value for this method is a 0-based array of 13
doubles as follows:
returnvalue0
returnvalue1
returnvalue2
returnvalue3
returnvalue4
returnvalue5
returnvalue6
returnvalue7
returnvalue8
returnvalue9
returnvalue10
returnvalue11
returnvalue12

=
=
=
=
=
=
=
=
=
=
=
=
=

CenterOfMassX
CenterOfMassY
CenterOfMassZ
Volume
Area
Mass
MomXX
MomYY
MomZZ
MomXY
MomZX
MomYZ
Accuracy

.void = ModelDocExtension.SetMaterialPropertyValues
( material_property_values, config_opt, config_names )

The following steps demonstrate how to use the accessor method


SldWorks::NewDocument to create new instances of the ModelDoc2
interface pointer and call several of its methods.
56

Case Study: Connecting to New Documents

API Fundamentals

Lesson 2
The API Object Model

Review the controls that create new documents.

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
CheckBox6:
(Name): chkNote
Caption: InsertNote
CommandButton2:
(Name): cmdNewModel
Caption: Connect to Model

10 Add the button click event.

Double-click the second command button to set up the event handler.


Private Sub cmdNewModel_Click()
End Sub

Case Study: Connecting to New Documents

57

Lesson 2

API Fundamentals

The API Object Model

11 Connect to SldWorks and create a new document.

Add the following lines of programming code:


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
Dim swModel As SldWorks.ModelDoc2
Set swModel = swApp.NewDocument(filedir + _
"APIPart.prtdot",0, 0#, 0#)
End Sub

12 Add code to create different document types.

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
Dim swModel As SldWorks.ModelDoc2
' Determine which option is selected
' and connect to the ModelDoc2 object
If optPart.Value = True Then
Set swModel = swApp.NewDocument(filedir + _
"APIPart.prtdot",0, 0#, 0#)
End If
If optAssy.Value = True Then
Set swModel = swApp.NewDocument(filedir + _
"APIAssembly.asmdot", 0, 0#, 0#)
End If
If optDraw.Value = True Then
Set swModel = swApp.NewDocument(filedir + _
"APIDrawing.drwdot", 0, 0#, 0#)
End If

13 Add ModelDoc2 methods and properties.

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

Case Study: Connecting to New Documents

API Fundamentals

Lesson 2
The API Object Model

If chkNote.Value = True Then


Dim swNote As Sldworks.Note
Dim swAnnotation As Sldworks.Annotation
Dim text As String
text = "Sample Note"
Set swNote = swModel.InsertNote(text)
Set swAnnotation = swNote.GetAnnotation
swAnnotation.SetPosition 0.01, 0.01, 0
End If
End Sub

14 Save and run the macro.

Try each of the option buttons first:


+
+
+

New document

Case Study: Connecting to New Documents

59

Lesson 2

API Fundamentals

The API Object Model

Next, try inserting a sketch in a part document and an assembly


document:
+

New sketch

Next, try inserting a design table in both a part and assembly document:
+

New design table

60

Case Study: Connecting to New Documents

API Fundamentals

Lesson 2
The API Object Model

Finally, try inserting a note in all three document types:


+

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 )

Case Study: Connecting to New Documents

61

Lesson 2

API Fundamentals

The API Object Model

15 Stop the macro.

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:
Private Function preparedrawingView(ByRef swApp As _
SldWorks.SldWorks, ByRef swModel As ModelDoc2) As _
SldWorks.View
Dim drawname As String
Dim errors As Long
Dim warnings As Long
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

Notice that Visual Basic automatically type casts the ModelDoc2


object to a DrawingDoc object and allows you to call the method
CreateDrawViewFromModelView directly from the ModelDoc2
object. CreateDrawViewFromModelView is a method on the
DrawingDoc interface. Another thing to note is that as you type, you
will not see this method using IntelliSense.
17 Insert new code to call the new function.

Insert these additional condition statements for FocusLocked and


InsertFamilyTableNew to call the new function from the previous step:
Dim swView As SldWorks.View
If chkSketch.Value = True Then
If optDraw.Value = True Then
Set swView = preparedrawingView(swApp, swModel)
swView.FocusLocked = True
Else
swModel.InsertSketch2 True
End If
End If
If chkFamilyTable.Value = True Then
If optDraw.Value = True Then
Set swView = preparedrawingView(swApp, swModel)
swModel.SelectByID swView.Name, "DRAWINGVIEW", 0, 0, 0
swModel.InsertFamilyTableNew
Else
swModel.InsertFamilyTableNew
End If
End If

62

Case Study: Connecting to New Documents

API Fundamentals

Lesson 2
The API Object Model

18 Save and run the macro.

Now our macro should prepare a sample drawing appropriately before


trying to insert a sketch or design table:
+

Sketch mode is
now active in view

Design table is
inserted into view

19 Stop the macro.

Click the close icon in the upper right corner of the form.

Case Study: Connecting to New Documents

63

Lesson 2

API Fundamentals

The API Object Model

Now lets look at all three specific Document object types: PartDoc,
AssemblyDoc and DrawingDoc.
PartDoc Object
(swPart)

AssemblyDoc
Object
(swAssy)

DrawingDoc Object
(swDraw)

Document objects are derived from ModelDoc2, therefore, they have


access to all of the functions residing on the ModelDoc2 object.
To connect to a document object use one of the ModelDoc2
accessors and perform a simple error check to validate the file type.
Dim
Dim
Dim
Dim

swModel As SldWorks.ModelDoc2
swPart As SldWorks.PartDoc
swAssy As SldWorks.AssemblyDoc
swDraw As SldWorks.DrawingDoc

Set swModel = swApp.ActiveDoc


If (swModel.GetType = swDocPART) Then
Set swPart = swModel
End If
If (swModel.GetType = swDocASSEMBLY) Then
Set swAssy = swModel
End If
If (swModel.GetType = swDocDRAWING) Then
Set swDraw = swModel
End If
If swModel Is Nothing Then
swApp.SendMsgToUser "Open a part, assembly or drawing!"
End If

PartDoc Methods and Properties


.EditRollback
.MaterialPropertyValues
.CreateNewBody
.MirrorPart

AssemblyDoc Methods and Properties


.AddComponent2 (CompName, X, Y, Z)
.AddMate (MateType, Align, Flip, Distance, Angle)
.InsertNewPart
.ToolsCheckInterference2 (NoComp, LstComp, CoInt, Comp, Face)

DrawingDoc Methods and Properties


.GetFirstView
.InsertModelAnnotations (Option, AllTypes, Types, AllViews)
.NewSheet3 (Name, Size, In, S1, S2, FA, TplName, W, H, PropV)

64

Case Study: Connecting to New Documents

API Fundamentals

Lesson 2
The API Object Model

20 Review the controls for the specific document types.

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:
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
CommandButton5:
(Name): cmdDraw
Caption: New Drawing
CheckBox9:
(Name): chkFormat
Caption: EditFormat

21 Add a click event to each button.

Double-click the new command buttons to set up each click event.


Private Sub cmdPart_Click()
End Sub
Private Sub cmdAssy_Click()
End Sub
Private Sub cmdDraw_Click()
End Sub

Case Study: Connecting to New Documents

65

Lesson 2

API Fundamentals

The API Object Model

22 Connect to the SldWorks object.

Add the following lines of programming code within each event:


Private Sub
Dim swApp
Set swApp
End Sub
Private Sub
Dim swApp
Set swApp
End Sub
Private Sub
Dim swApp
Set swApp
End Sub

cmdPart_Click()
As SldWorks.SldWorks
= Application.SldWorks
cmdAssy_Click()
As SldWorks.SldWorks
= Application.SldWorks
cmdDraw_Click()
As SldWorks.SldWorks
= Application.SldWorks

23 Connect to the PartDoc object and call a specific method.

Add the following code:


Private Sub cmdPart_Click()
Dim swApp As SldWorks.SldWorks
Set swApp = Application.SldWorks
Dim swModel As SldWorks.ModelDoc2
Set swModel = swApp.NewDocument(filedir + "APIPart.prtdot", _
0, 0#, 0#)
Dim swPart As SldWorks.PartDoc
Set swPart = swModel
swModel.InsertSketch2 True
swModel.SketchRectangle 0, 0, 0, 0.1, 0.1, 0, 1
swModel.FeatureManager.FeatureExtrusion2 True, False, False,_
0, 0, 0.1, 0.01, False, False, False, False, _
0.01745329251994,0.01745329251994, False, False, False, _
False, 1, 1, 1, 0, 0, False
If chkRollback.value = True Then
swPart.EditRollback
End If
End Sub

24 Connect to the AssemblyDoc object and call a specific method.

Add the following code:


Private Sub cmdAssy_Click()
Dim swApp As SldWorks.SldWorks
Set swApp = Application.SldWorks
Dim fileerror As Long
Dim filewarning As Long
swApp.OpenDoc6 filedir + "Sample.sldprt", swDocPART, _
swOpenDocOptions_ViewOnly, "", fileerror, filewarning
Dim swModel As SldWorks.ModelDoc2
Set swModel = swApp.NewDocument(filedir + _
"APIAssembly.asmdot", 0, 0#, 0#)
Dim swAssy As SldWorks.AssemblyDoc
Set swAssy = swModel
If chkComponent.value = True Then
swAssy.AddComponent2 filedir + "Sample.sldprt", 0, 0, 0
swModel.FeatureManager.UpdateFeatureTree
End If
End Sub

66

Case Study: Connecting to New Documents

API Fundamentals

Lesson 2
The API Object Model

25 Connect to the DrawingDoc object and call a specific method.

Add the following code:


Private Sub cmdDraw_Click()
Dim swApp As SldWorks.SldWorks
Set swApp = Application.SldWorks
Dim swDraw As SldWorks.DrawingDoc
Set swDraw = swApp.NewDocument(filedir + _
"APIDrawing.drwdot",0, 0#, 0#)
If chkFormat.value = True Then
'Notice the automatic type casting Visual Basic does for you.
swDraw.EditTemplate
End If
End Sub

26 Test each of the following:


Save and run the macro.

Before

After

Rollback

Case Study: Connecting to New Documents

67

Lesson 2

API Fundamentals

The API Object Model

Before

After

New component

Before

After

Edit sheet format is


now active in drawing

27 Stop the macro..

Click the close icon in the upper right corner of the form.

68

Case Study: Connecting to New Documents

API Fundamentals

Lesson 2
The API Object Model

Case Study:
Connecting to
Existing
Documents

So far, we have used the method NewDocument to create new instances


of the different document interfaces. We will now connect to existing
documents that have already been opened in your SolidWorks session.

28 Import another userform.


Right-click in the VBA Project
Explorer, and click
Import File... from the popup

menu.
Import the form named
frmExistingDocs.frm
located in the case study
directory.

29 Review methods used for existing files.


Click View, Code or double-click the first command button named:

Connect to SolidWorks.
Const filedir As String = "C:\SolidWorks 2006 Training
Files\API Fundamentals\Templates\"
Private Sub cmdConnect_Click()
Dim swApp As SldWorks.SldWorks
Set swApp = Application.SldWorks
If chkOpen.value = True Then
Dim fileerror As Long
Dim filewarning As Long
swApp.OpenDoc6 filedir + "Sample.sldprt", swDocPART, _
swOpenDocOptions_ViewOnly, "", fileerror, filewarning
End If
If chkLoad.value = True Then
swApp.LoadFile2 filedir + "Sample.igs", ""
End If
If chkNewWindow.value = True Then
swApp.CreateNewWindow
swApp.ArrangeWindows 1
End If
End Sub

Case Study: Connecting to Existing Documents

69

Lesson 2

API Fundamentals

The API Object Model

30 Add code to module.

Switch back to the ObjectModelBasics1 module. Put a comment


in front of the first line, and show the new form on the second line:
Sub main()
frmNewDocs.Show
frmExistingDocs.Show
End Sub

31 Save and run macro.

Try each of the checkboxes separately to test how SolidWorks behaves.


Follow this order:
1.

2.

3.

32 Stop macro.

Click the close icon in the upper right corner of the form.
Return to the VBA editor.
33 Review methods available for every document type.
Click View, Code or double-click the second command button named:

Connect to Model.
Private Sub cmdNewModel_Click()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
' Check to see if a document is loaded
If swModel Is Nothing Then
swApp.SendMsgToUser "Open a part, assembly or drawing."
Exit Sub
End If
If chkToolbars.value = True Then
swModel.SetToolbarVisibility swFeatureToolbar, True
swModel.SetToolbarVisibility swMacroToolbar, True
swModel.SetToolbarVisibility swMainToolbar, True
swModel.SetToolbarVisibility swSketchToolbar, True
swModel.SetToolbarVisibility swSketchToolsToolbar, True
swModel.SetToolbarVisibility swStandardToolbar, True
swModel.SetToolbarVisibility swStandardViewsToolbar, True
swModel.SetToolbarVisibility swViewToolbar, True
End If

70

Case Study: Connecting to Existing Documents

API Fundamentals

Lesson 2
The API Object Model

If chkToolbars.value = False Then


swModel.SetToolbarVisibility swFeatureToolbar, False
swModel.SetToolbarVisibility swMacroToolbar, False
swModel.SetToolbarVisibility swMainToolbar, False
swModel.SetToolbarVisibility swSketchToolbar, False
swModel.SetToolbarVisibility swSketchToolsToolbar, False
swModel.SetToolbarVisibility swStandardToolbar, False
swModel.SetToolbarVisibility swStandardViewsToolbar, False
swModel.SetToolbarVisibility swViewToolbar, False
End If
If chkCustomInfo.value = True Then
Dim retval As Boolean
retval = swModel.AddCustomInfo3("", "MyInfo", _
swCustomInfoText, "MyData")
End If
End Sub

34 Open the following files and run the macro.

Test each file with the checkboxes toggled on and off as shown:
SheetMetalSample.sldprt
SheetMetalSample.sldasm
SheetMetalSample.slddrw
+

Toolbars hidden

Case Study: Connecting to Existing Documents

71

Lesson 2

API Fundamentals

The API Object Model

Toolbars visible

Custom Property

72

Case Study: Connecting to Existing Documents

API Fundamentals

Lesson 2
The API Object Model

35 Stop the macro.

Return to the VBA editor.


36 Review method available only to PartDoc.
Click View, Code or double-click the third command button named:

Existing Part.
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swPart As SldWorks.PartDoc
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swPart = swModel 'Explicit Type Cast
' Check to see if a part is loaded
If swModel Is Nothing Then
swApp.SendMsgToUser "Please open a part."
Exit Sub
End If
If chkMirror.value = True Then
Dim boolstatus As Boolean
boolstatus = swModel.Extension.SelectByID2("Top", "PLANE", _
0, 0, 0, False, 0, Nothing, 0)
'Next method called from specific PartDoc object.
swPart.MirrorPart
Set swModel = swApp.ActiveDoc
swModel.ShowNamedView2 "*Isometric", 7
swModel.ViewZoomtofit2
swApp.ArrangeWindows 1
Dim retval As Boolean
Dim errors As Long
Set swModel = swApp.ActivateDoc2("sheetmetalsample.SLDPRT",_
True, errors)
retval = swModel.DeSelectByID("Top", "PLANE", 0, 0, 0)
End If
End Sub

Case Study: Connecting to Existing Documents

73

Lesson 2

API Fundamentals

The API Object Model

37 Run the macro.

Use the part file: SheetMetalSample.sldprt


+

Mirrored part

38 Stop the macro..

Return to the VBA editor.


39 Review method available only to AssemblyDoc.
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swAssy As SldWorks.AssemblyDoc
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swAssy = swModel 'Explicit Type Cast!
' Check to see if an assembly is loaded
If swModel Is Nothing Then
swApp.SendMsgToUser "Please open an assembly."
Exit Sub
End If
If chkCavity.value = True Then
Dim boolstatus As Boolean
boolstatus = _
swModel.Extension.SelectByID2( _
"sheetmetalsample-1@sheetmetalsample", "COMPONENT", 0, 0, _
0, False, 0, Nothing, 0)
swAssy.EditPart
swModel.ClearSelection
boolstatus = swModel.Extension.SelectByID2( _
"plug-1@sheetmetalsample", "COMPONENT", 0, 0, 0, True, _
0 ,Nothing, 0)
swAssy.InsertCavity4 10, 10, 10, 1, 1, -1
swAssy.EditAssembly
boolstatus = swModel.Extension.SelectByID2( _
"plug-1@sheetmetalsample", "COMPONENT", 0, 0, 0, _
True, 0,Nothing, 0)
swAssy.EditSuppress2
End If

74

Case Study: Connecting to Existing Documents

API Fundamentals

Lesson 2
The API Object Model

40 Run macro.

Use the assembly file: SheetMetalSample.sldasm


+

Edit part

Select component

Insert cavity

Return to edit
assembly mode

Suppress part to
view cavity

Case Study: Connecting to Existing Documents

75

Lesson 2

API Fundamentals

The API Object Model

41 Stop the macro.

Return to the VBA editor.


42 Review method available only to DrawingDoc.
Click View, Code.
Private Sub cmdDraw_Click()
Dim swApp As SldWorks.SldWorks
Dim swDraw As SldWorks.DrawingDoc
Set swApp = Application.SldWorks
Set swDraw = swApp.ActiveDoc
'Check to see if a drawing is loaded
If swDraw Is Nothing Then
swApp.SendMsgToUser "Please open a drawing."
Exit Sub
End If
If chkLayer.value = True Then
'Notice automatic type cast.
swDraw.ClearSelection
Dim retval As Boolean
retval = swDraw.CreateLayer("MyRedLayer", "Red", RGB(255, _
0,0), swLineSTITCH, swLW_THICK, True)
End If
End Sub

43 Run macro.

Use the drawing file: SheetMetalSample.slddrw


+

New layer

44 Exit macro.

76

Case Study: Connecting to Existing Documents

API Fundamentals

Exercise 4:
Working with New Documents

Exercise 4:
Working with
New Documents

Objective

To connect a macro to the SolidWorks application, create new


documents, and call methods on SldWorks and ModelDoc2 objects.

Skills Learned

I
I
I
I

Adding option button controls to a form.


Adding checkbox controls to a form.
Program API calls specific to SldWorks and ModelDoc2
application objects.
Importing modules.

APIs Used

SldWorks.SendMsgToUser2
------------------------------SldWorks.NewDocument
ModelDoc2.InsertSketch2
ModelDoc2.CreateCircleByRadius2
ModelDoc2.ViewZoomtofit2

Procedure

1.
2.
3.
4.
5.
6.
7.
8.

Open SolidWorks with no files created.


Create a new macro named NewDocs.swp.
Add a userform to the macro.
Program the entry point procedure to show the userform.
Use the image as a guide for designing each control.
Program the click event for each button.
Use the methods listed above in your code.
Save and test the macro.

77

Exercise 4:

API Fundamentals

Working with New Documents

Solution

Option Explicit
Sub main()
frmNewDocs.Show
End Sub
--------------------------------------------------------------Option Explicit
Const filedir As String = "C:\SolidWorks 2006 Training
Files\API Fundamentals\Templates\"
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Private Sub cmdSldWorks_Click()
Set swApp = Application.SldWorks
If chkMessage.Value = True Then
swApp.SendMsgToUser2 "Hello, this is a sample message", 1, 2
End If
End Sub
Private Sub cmdModel_Click()
Set swApp = Application.SldWorks
If optPart.Value = True Then
Set swModel = swApp.NewDocument(filedir + _
"APIPart.prtdot", 0, 0#, 0#)
End If
If optAssy.Value = True Then
Set swModel = swApp.NewDocument(filedir + _
"APIAssembly.asmdot", 0, 0#, 0#)
End If
If chkCircle.Value = True Then
swModel.InsertSketch2 True
swModel.CreateCircleByRadius2 0, 0, 0, 0.05
swModel.ViewZoomtofit2
End If
End Sub
---------------------------------------------------------------

78

API Fundamentals

Exercise 5:
Working with Existing Documents

Exercise 5:
Working with
Existing
Documents

Objective

To open specific document types and connect to existing documents


already open.

Skills Learned

I
I
I
I

Adding option button controls to a form.


Adding checkbox controls to a form.
Program API calls specific to SldWorks and ModelDoc2
application objects.
Importing modules.

APIs Used

SldWorks.OpenDoc6
---------------------------------------SldWorks.ActiveDoc
ModelDoc2.AddLightSource
ModelDoc2.SetLightSourcePropertyValuesVB
ModelDoc2.LockLightToModel
ModelDoc2.GraphicsRedraw

Procedure

1.
2.
3.
4.
5.
6.
7.
8.

Open SolidWorks with no files created.


Create a new macro named ExistingDocs.swp.
Add a userform to the macro.
Program the entry point procedure to show the userform.
Use the image as a guide for designing each control.
Program the click event for each button.
Use the methods listed above in your code.
Save and test the macro.

79

Exercise 5:

API Fundamentals

Working with Existing Documents

Solution

Option Explicit
Sub main()
frmExistingDocs.Show
End Sub
--------------------------------------------------------------Option Explicit
Const filedir As String = "C:\SolidWorks 2006 Training
Files\API Fundamentals\Templates\"
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Private Sub cmdSldWorks_Click()
Set swApp = Application.SldWorks
If chkOpen.Value = True Then
Dim fileerror As Long
Dim filewarning As Long
If optPart.Value = True Then
swApp.OpenDoc6 filedir + "sample.sldprt", swDocPART, _
swOpenDocOptions_Silent, "", fileerror, filewarning
End If
If optAssy.Value = True Then
swApp.OpenDoc6 filedir + "sample.sldasm", swDocASSEMBLY, _
swOpenDocOptions_Silent, "", fileerror, filewarning
End If
End If
End Sub
Private Sub cmdModel_Click()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
' Check to see if a document is loaded
If swModel Is Nothing Then
swApp.SendMsgToUser "Please open a part or assembly."
Exit Sub
End If
If chkSpot.Value = True Then
swModel.AddLightSource "SW#2", 4, "Directional2"
swModel.SetLightSourcePropertyValuesVB "SW#2", 4, 1, _
16777215, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
swModel.LockLightToModel 2, False
swModel.GraphicsRedraw
End If
End Sub

80

API Fundamentals

Lesson 3
Setting System Options and
Document Properties

Upon successful completion of this lesson, you will be able to:


I

Use the API to change system options and document properties.

Locate and automate checkboxes, textbox values, listboxes, radio


buttons and slider bars within the SolidWorks options dialog.

81

Lesson 3

82

API Fundamentals

API Fundamentals

User
Preferences System Options

Lesson 3

In order to programatically change system options in SolidWorks, it is


necessary to call specific user preference methods. These methods
allow a program to change individual settings found within the Tools,
Options menu. These methods are:
SldWorks::SetUserPreferenceToggle
SldWorks::SetUserPreferenceIntegerValue
SldWorks::SetUserPreferenceDoubleValue
SldWorks::SetUserPreferenceStringValue

Note

Each method listed above also has a counterpart.


Substitute SetUserPreference with GetUserPreference to retrieve
existing system options.

Setting
Checkboxes

Call the SldWorks::SetUserPreferenceToggle method to turn on and


off checkbox items within the SolidWorks options dialog.

SldWorks::SetUserPreferenceToggle
SldWorks.SetUserPreferenceToggle (UserPreferenceValue, onFlag)

Input:

UserPreferenceValue

See UserPreference Tables For System Options on


page 92.
Toggle items are designated with Toggle.

Input:

onFlag

TRUE =
FALSE

User Preferences - System Options

toggle the item on


= toggle the item off

83

Lesson 3

API Fundamentals

Create a new macro.


Click the New Macro

button on the Macro toolbar.

Name the macro SystemOptions.swp.


2

Early bind to SolidWorks.

Edit code to reflect early binding behavior.


Dim swApp As SldWorks.SldWorks
Sub main()
Set swApp = Application.SldWorks
End Sub

Add code to change toggle values.

Automate the first four checkboxes in the System Options, General


page.
Dim swApp As SldWorks.SldWorks
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

Save and run the macro.

Test to see if the checkboxes are enabled.


Return to VBA when finished.
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.

User Preferences - System Options

API Fundamentals

Lesson 3

Setting Textboxes
with Integers

Call the SldWorks::SetUserPreferenceIntegerValue method to enter


values for textbox items that require integer values.

SldWorks::SetUserPreferenceIntegerValue
retval = swApp.SetUserPreferenceIntegerValue (UserPreferenceValue, value)

Output:

retval

TRUE

Input:

UserPreferenceValue

See UserPreference Tables For System Options on


page 92.
Integer value items are designated with Int.

Input:

value

Numeric value that you want to give to the user


preference specified in userPreferenceValue

if the successful, FALSE if not.

Add code to change viewport color.


On the Colors page, change the Viewport Background color value.
Dim swApp As SldWorks.SldWorks
Dim viewportColor As Long
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
viewportColor = RGB(128, 255, 128) sets color to green
swApp.SetUserPreferenceIntegerValue _
swConst.swSystemColorsViewportBackground, viewportColor
End Sub

Save and run macro.

Test to see if the textbox values have changed.


Return to VBA when finished.

User Preferences - System Options

85

Lesson 3

API Fundamentals

Setting Textboxes
with Doubles

Call the SldWorks::SetUserPreferenceDoubleValue method to enter


values for textbox items that require numeric values with decimal
points.

SldWorks::SetUserPreferenceDoubleValue
retval = swApp.SetUserPreferenceDoubleValue (UserPreferenceValue, value)

Output:

retval

TRUE

Input:

UserPreferenceValue

See UserPreference Tables For System Options on


page 92.
Double value items are designated with Double.

Input:

value

Numeric value that you want to give to the user


preference specified in userPreferenceValue

if the successful, FALSE if not.

Add code to change the detail view scale.


On the Drawings page, change the Detail View Scaling value.
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
End Sub

Save and run macro.

Test to see if the textbox value has changed then return to VBA.

86

User Preferences - System Options

API Fundamentals

Lesson 3

Setting Textboxes
with String Values

Call the SldWorks::SetUserPreferenceStringValue method to enter


values for textbox items that require characters.

SldWorks::SetUserPreferenceStringValue
retval = swApp.SetUserPreferenceStringValue (UserPreferenceValue, value)

Output:

retval

TRUE

Input:

UserPreferenceValue

See UserPreference Tables For System Options on


page 92.
String value items are designated with String.

Input:

value

Numeric value that you want to give to the user


preference specified in userPreferenceValue

if the successful, FALSE if not.

Add code to change backup directory string value.

On the Backups page, change the Save Backup Copies in Directory


string value.
Dim value As String
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
End Sub

10 Save and run macro.

Test to see if the textbox value has changed then return to VBA.

User Preferences - System Options

87

Lesson 3

API Fundamentals

Setting Listboxes

Call the SldWorks::SetUserPreferenceIntegerValue; StringValue or


Toggle method (for lists that have only two choices) to change listbox
values.

Setting Radio
Buttons

Call the SldWorks::SetUserPreferenceIntegerValue or Toggle method


to change radio button values. Toggle is sometimes used for radio
buttons with only two options.

Setting Slider Bars

Call the SldWorks::SetUserPreferenceIntegerValue or DoubleValue


method to move slider bars.

88

User Preferences - System Options

API Fundamentals

Lesson 3

11 Add code to change a radio button and slider bars.

On the Display/Selections page, change the


Hidden Edges Displayed As option to Solid.
On the View Rotation page, change the Mouse Speed value and the
View Animation Speed value.
Dim swApp As SldWorks.SldWorks
Dim color As Long
Dim value As String
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
View Rotation - Mouse Speed
0 = Slow
100 = Fast
swApp.SetUserPreferenceIntegerValue _
swConst.swViewRotationMouseSpeed, 50
View Rotation - ViewAnimationSpeed
0 = Off
0.5 = Fast
1.0
1.5
2.0
2.5
3.0 = Slow
swApp.SetUserPreferenceDoubleValue _
swConst.swViewAnimationSpeed, 1.5
End Sub

12 Save and run macro.

Test to see if the radio button changed and the two slider bars moved.
13 Exit macro.

User Preferences - System Options

89

Lesson 3

API Fundamentals

User
Preferences Document
Properties

In order to customize or automate default document properties in


SolidWorks, it is necessary to connect to both the SldWorks object and
the ModelDoc2 object. Then call the same user preference methods as
before but make the call to ModelDoc2, instead of to SldWorks.
ModelDoc2::SetUserPreferenceToggle
ModelDoc2::SetUserPreferenceIntegerValue
ModelDoc2::SetUserPreferenceDoubleValue
ModelDoc2::SetUserPreferenceStringValue
The following table highlights the ability to set a checkbox for
document property using ModelDoc2, not SldWorks.

ModelDoc2::SetUserPreferenceToggle
ModelDoc2.SetUserPreferenceToggle (UserPreferenceValue, onFlag)

Input:

UserPreferenceValue

See UserPreference Tables For System Options on


page 92.
Toggle items are designated with Toggle.

Input:

onFlag

TRUE =

toggle the item on


toggle the item off

FALSE =

Create a new part.

Create a new macro.


Click the New Macro

button and name the macro


DocumentProperties.swp.
3

Early bind to SolidWorks.

Edit code to reflect early binding behavior.


Dim swApp As SldWorks.SldWorks
Sub main()
Set swApp = Application.SldWorks
End Sub

90

User Preferences - Document Properties

API Fundamentals

Lesson 3

Connect to ModelDoc2.

Add the following lines of code:


Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
End Sub

Add code to change toggle value.

On the Document Properties, Detailing page enable the checkbox for


Dual Dimension Display.
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
swModel.SetUserPreferenceToggle _
swConst.swDetailingDualDimensions, True
End Sub

Create a new part in SolidWorks.

Save and run the macro.


Test to see if the checkbox is enabled.

Locating the
Correct APIs
and
Enumeration
Values

It is often difficult to determine which APIs and enumerations values to


use in the API help file. A helpful way to determine the settings for a
particular option, is to record a new macro and change the setting. Then
edit the macro to find out what APIs were used and what values were
passed to it.

Record a new macro.


Click the Record
button from the Macro toolbar

Change an option.
Click Tools, Options... from the menu and click View Rotation on the

System Options tab.


Set the Mouse speed and the View animation speed to Fast.
Click OK to accept the settings.

Locating the Correct APIs and Enumeration Values

91

Lesson 3

API Fundamentals

Change the options again.


Again, click Tools, Options... from the menu and click View Rotation

on the System Options tab.


Set the Mouse speed and the View animation speed to Slow.
Click OK to accept the settings.

Study the code to determine the settings.

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:
I
I
I

Setting in the System Options to be changed.


Type of user preference method used to change the setting.
Enumerations / Values used when changing the options.

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.
Note

92

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.

UserPreference Tables For System Options

API Fundamentals

Lesson 3

General

Setting

Type

Enumeration / Values

Open Last Used Document

Toggle

swOpenLastUsedDocumentAtStart

Input dimension value

Toggle

swInputDimValOnCreate

Single command per pick

Toggle

swSingleCommandPerPick

Show dimension names

Toggle

swShowDimensionNames

Show errors every rebuild

Toggle

swShowErrorsEveryRebuild

Maximize document on open

Toggle

swMaximizeDocumentOnOpen

Use shaded face highlighting

Toggle

swUseShadedFaceHighlight

Show thumbnail graphics in Windows Explorer

Toggle

swThumbnailGraphics

Use system separator for dimensions

Toggle

swUseSystemSeparatorForDims

Use English Language menus

Toggle

Not Supported

Use English language feature and file names

Toggle

Not Supported

Enable performance email

Toggle

swEnablePerformanceEmail

Enable Confirmation Corner

Toggle

swEnableConfirmationCorner

Auto-show PropertyManager

Toggle

swAutoShowPropertyManager

Automatically edit macro after recording

Toggle

Not Supported

Custom property used as component description

String

swCustomPropertyUsedAsComponentDescription

UserPreference Tables For System Options

93

Lesson 3

API Fundamentals

Drawings

Setting

Type

Enumeration / Values

Automatically place dimensions from model

Toggle

swDrawingAutomaticModelDimPlacement

Automatically scale new drawing views

Toggle

swAutomaticScaling3ViewDrawings

Show contents while dragging drawing view

Toggle

swDrawingViewShowContentsWhileDragging

Smooth dynamic motion of drawing views

Toggle

swDrawingViewSmoothDynamicMotion

Display new detail circles as circles

Toggle

swDrawingCreateDetailAsCircle

Select hidden entities

Toggle

swDrawingSelectHiddenEntities

Eliminate duplicate model dimensions on insert

Toggle

swDrawingEliminateDuplicateDimsOnInsert

Allow auto-update when opening drawings

Toggle

swAutomaticDrawingViewUpdateDefault

Detail item snapping when dragging corner

Toggle

Not Supported

Detail item snapping when dragging center

Toggle

Not Supported

Print out-of-sync water mark

Toggle

swRapidDraftPrintOutOfSynchWaterMark

Show reference geometry names in drawings

Toggle

swShowRefGeomName

Automatically hide components on view creation

Toggle

swDrawingViewAutoHideComponents

Display sketch arc center points

Toggle

swDisplayArcCenterPoints

Display sketch entity center points

Toggle

swDisplayEntityPoints

Save tessellated data for drawings with shaded and


draft quality views

Toggle

swDrawingSaveShadedData

Print breaklines in broken view

Toggle

swDrawingPrintBreaklinesInBrokenView

Print out-of-date drawing views with crosshatch

Int

swDrawingPrintCrosshatchOutOfDateViews

Detail view scaling

Double

swDrawingDetailViewScale

Custom property used as Revision

String

swDrawingCustomPropertyUsedAsRevision

Keyboard movement increment

94

Not Supported

UserPreference Tables For System Options

API Fundamentals

Lesson 3

Display Style

Setting

Type

Enumeration / Values

Display style for new views

Int

swHiddenEdgeDisplayDefault
swDisplayMode_e

Tangent edges in new views

Int

swTangentEdgeDisplayDefault
swDisplayTangentEdges_e

Display quality for new views

Toggle

swDrawingsDefaultDisplayTypeFastHLRHLV
swDrawingsDefaultDisplayTypeHLREdgesWhenSha
ded

UserPreference Tables For System Options

95

Lesson 3

API Fundamentals

Area Hatch

Setting

Type

Enumeration / Values

Area Hatch / Fill

Int

swDrawingAreaHatchFillStyle
swAreaHatchFillStyle_e

Pattern

String

swDrawingAreaHatchPattern
String values can be found in the combo box
dropdown list.

Scale

Double

swDrawingAreaHatchScale

Angle

Double

swDrawingAreaHatchAngle

96

UserPreference Tables For System Options

API Fundamentals

Lesson 3

Colors

Setting

Type

Enumeration / Values

Viewport Background

Int

swSystemColorsViewportBackground

Top Gradient Color

Int

swSystemColorsTopGradientColor

Bottom Gradient Color

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

Selected Face, Shaded

Int

swSystemColorsSelectedFaceShaded

Drawings, Paper Color

Int

swSystemColorsDrawingsPaper

Drawings, Background

Int

swSystemColorsDrawingsBackground

Drawings, Visible Model Edges

Int

swSystemColorsDrawingsVisibleModelEdge

Drawings, Hidden Model Edges

Int

swSystemColorsDrawingsHiddenModelEdge

Dimensions, Imported (Driving)

Int

swSystemColorsImportedDrivingAnnotation

Dimensions, Non Imported (Driven)

Int

swSystemColorsImportedDrivenAnnotation

Dimensions, Dangling

Int

swSystemColorsDanglingDimension

Dimensions, Not Marked for Drawing

Int

Not Supported

Dimensions, Controlled by Design Table

Int

swSystemColorsDTDim

Text

Int

swSystemColorsText

Sketch, Over Defined

Int

swSystemColorsSketchOverDefined

Sketch, Fully Defined

Int

swSystemColorsSketchFullyDefined

Sketch, Under Defined

Int

swSystemColorsSketchUnderDefined

Sketch, Invalid Geometry

Int

swSystemColorsSketchInvalidGeometry

Sketch, Not Solved

Int

swSystemColorsSketchNotSolved

Sketch, Inactive

Int

swSystemColorsSketchInactive

Grid Lines, Minor

Int

swSystemColorsGridLinesMinor

UserPreference Tables For System Options

97

Lesson 3

API Fundamentals

Grid Lines, Major

Int

swSystemColorsGridLinesMajor

Construction Geometry

Int

swSystemColorsConstructionGeometry

Assembly, Edit Part

Int

swSystemColorsAssemblyEditPart

Assembly, Hidden Lines of Edit Part

Int

swSystemColorsAssemblyEditPartHiddenLines

Assembly, Non-Edit Parts

Int

swSystemColorsAssemblyNonEditPart

Inactive Entities

Int

swSystemColorsInactiveEntity

Temporary Graphics

Int

swSystemColorsTemporaryGraphics

Temporary Graphics, Shaded

Int

swSystemColorsTemporaryGraphicsShaded

Active Selection Listbox

Int

swSystemColorsActiveSelectionListBox

Surfaces, Open Edges

Int

swSystemColorsSurfacesOpenEdge

Edges in Shaded With Edges Mode

Int

swSystemColorsShadedEdge

X axis of Reference Triad

Int

swSystemColorsRefTriadX

Y axis of Reference Triad

Int

swSystemColorsRefTriadY

Z axis of Reference Triad

Int

swSystemColorsRefTriadZ

Feature Tree, Normal Item

Int

swSystemColorsTreeItemNormal

Feature Tree, Selected Item

Int

swSystemColorsTreeItemSelected

Annotations, Imported

Int

swSystemColorsImportedAnnotation

Annotations, Non Imported

Int

swSystemColorsNonImportedAnnotation

Assembly Interference Volume

Int

swSytemColorsInterferenceBodyColor

Hidden Edge Selection Show Color

Int

swSystemColorsHiddenEdgeSelectionShow

Property Manager Color

Int

swSystemColorsPropertyManagerColor
swPropertyManagerColorScheme_e

PropertyManagerSkin

Not Supported

Current Color Scheme

Not Supported

Use gradient background

Toggle

swColorsGradientPartBackground

Match graphics

Toggle

swColorsMatchViewAndFeatureManagerBackgroun
d

Use specified color for Shaded With Edges mode

Toggle

swColorsUseShadedEdgeColor

Use specified colors when editing parts in


assemblies

Toggle

swColorsUseSpecifiedEditColors

98

UserPreference Tables For System Options

API Fundamentals

Lesson 3

Sketch

Setting

Type

Enumeration / Values

Use fully defined sketches

Toggle

swFullyConstrainedSketchMode

Display arc centerpoints in part/assembly sketches

Toggle

swDisplayArcCenterPoints

Display entity points in part/assembly sketches

Toggle

swDisplayEntityPoints

Prompt to close sketch

Toggle

swSketchPromptToCloseSketch

Create sketch on new part

Toggle

swSketchCreateSketchOnNewPart

Override dimensions on Drag/Move

Toggle

swSketchOverrideDimensionsOnDrag

Display plane when shaded

Toggle

swSketchDisplayPlaneWhenShaded

Display virtual sharps

Toggle

swDisplayVirtualSharps

Line length measured between virtual sharps in 3d

Toggle

swSketchLineLengthVirtualSharp3d

Enable Spline Tangency and Curvature handles

Toggle

Not Supported

Show spline control polygon by default

Toggle

swSketchShowSplineControlPolygon

Prompt to set driven state

Toggle

swSketchOverdefiningDimsPromptToSetState

Set driven by default

Toggle

swSketchOverdefiningDimsSetDrivenByDefault

UserPreference Tables For System Options

99

Lesson 3

API Fundamentals

Relations / Snaps

Setting

Type

Enumeration / Values

Enable Snapping

Toggle

swFullyConstrainedSketchMode

Snap to model geometry

Toggle

swSketchInferFromModel

Automatic relations

Toggle

swSketchAutomaticRelations

End points and sketch points

Toggle

swSketchSnapsPoints

Center Points

Toggle

swSketchSnapsCenterPoints

Mid-points

Toggle

swSketchSnapsMidPoints

Quadrant Points

Toggle

swSketchSnapsQuadrantPoints

Intersections

Toggle

swSketchSnapsIntersections

Nearest

Toggle

swSketchSnapsNearest

Tangent

Toggle

swSketchSnapsTangent

Perpendicular

Toggle

swSketchSnapsPerpendicular

Parallel

Toggle

swSketchSnapsParallel

Horizontal/vertical lines

Toggle

swSketchSnapsHVLines

Horizontal/vertical to points

Toggle

swSketchSnapsHVPoints

Length

Toggle

swSketchSnapsLength

Grid

Toggle

swSketchSnapsGrid

Snap only when grid is displayed

Toggle

swSnapOnlyIfGridDisplayed

Angle

Toggle

swSketchSnapsAngle

Snap angle

Double

swSnapToAngleValue

100

UserPreference Tables For System Options

API Fundamentals

Lesson 3

Display / Selection

Setting

Type

Enumeration / Values

Hidden edges displayed as

Int

swEdgesHiddenEdgeDisplay
swEdgesHiddenEdgeDisplay_e

Allow selection of wireframe and HLV modes

Toggle

swEdgesHiddenEdgeSelectionInWireframe

Allow selection in HLR and shaded modes

Toggle

swEdgesHiddenEdgeSelectionInHLR

Part/Assembly tangent edge display

Int

swEdgesTangentEdgeDisplay
swEdgesTangentEdgeDisplay_e

Edge display in shaded with edges mode

Int

swEdgesShadedModeDisplay
swEdgesShadedModeDisplay_e

Assembly transparency for in context edit

Int

swEdgesInContextEditTransparencyType
swEdgesInContextEditTransparencyType_e

Percentage of transparency

Int

swEdgesInContextEditTransparency
Range is 0 - 100 / Increment by 10

Highlight all edges of features selected in view

Toggle

swEdgesHighlightFeatureEdges

Dynamic highlight from graphics view

Toggle

swEdgesDynamicHighlight

Show open edges of surfaces in different color

Toggle

swEdgesOpenEdgesDifferentColor

Anti-alias edges

Toggle

swEdgesAntiAlias

Display shaded planes

Toggle

swEdgesDisplayShadedPlanes

Enable selection through transparency

Toggle

swDisplayEnableSelectionThroughTransparency

Display reference triad

Toggle

swDisplayReferenceTriad

Display dimensions flat to screen

Toggle

Not Supported

Projection type for four view viewport

Int

swFourViewportProjectionType
swDrawingProjectionType_e

UserPreference Tables For System Options

101

Lesson 3

API Fundamentals

Performance

Setting

Type

Enumeration / Values

Verification on rebuild

Toggle

swPerformanceVerifyOnRebuild

Ingnore self-intersection check for some sheet


metal features

Toggle

swIgnoreSMFSelfInterCheck

High quality for normal view mode

Toggle

swUseAlphaTransparency

High quality for dynamic view mode

Toggle

swTransparencyHighQualityDynamic

Curvature generation

Toggle

swPerformanceAlwaysGenerateCurvature

Level of detail

Int

swLevelOfDetail
Range 0 - 20 - the smaller the number the
greater the detail

Automatically load components lightweight

Toggle

swAutoLoadPartsLightweight

Always resolve sub-assemblies

Toggle

Not Supported

Check out-of-date lightweight components

Int

swCheckForOutOfDateLightweightComponents
swCheckOutOfDate_e

Resolve lightweight components

Int

swResolveLightweight
0 = Prompt
1 = Always

Rebuild assembly on load

Int

swPerformanceAssemRebuildOnLoad
swPromptAlwaysNever_e

Automatically convert drawing views to draft


quality when unloading components

Int

swPerformanceViewsToDraftQuality
swPromptAlwaysNever_e

Mate animation speed

Double

swMateAnimationSpeed
0 = Off
0.5 = Fast
3 = Slow

Update mass properties while saving document

Toggle

swUpdateMassPropsDuringSave

Use shaded preview

Toggle

swUseShadedPreview

Use Software OpenGL

Toggle

swUseSimpleOpenGL

102

UserPreference Tables For System Options

API Fundamentals

Lesson 3

Assemblies

Setting

Type

Enumeration / Values

Move components by dragging

Toggle

swAssemblyAllowComponentMoveByDragging

Use Large Assembly Mode to improve


performance

Toggle

swLargeAsmModeEnabled

whenever opening an assembly with more than this


number of components:

Int

swLargeAsmModeThreshold

Automatically load components lightweight

Toggle

swLargeAsmModeAutoLoadLightweight

Do not save auto-recover info

Toggle

swLargeAsmModeAutoRecover

Hide all planes, axes, sketches, curves annotations,


etc.

Toggle

swLargeAsmModeHideAllItems

Do not display edges in shaded mode

Toggle

swLargeAsmModeUseHLREdgesInShaded

Suspend automatic rebuild

Toggle

swLargeAsmModeSuspendAutoRebuild

UserPreference Tables For System Options

103

Lesson 3

API Fundamentals

External References

Setting

Type

Enumeration / Values

Open referenced documents with read-only access

Toggle

swExtRefOpenReadOnly

Dont prompt to save read-only referenced


documents (disgard changes)

Toggle

swExtRefNoPromptOrSave

Allow multiple contexts for parts when editing in


assembly

Toggle

swExtRefMultipleContexts

Load referenced documents

Int

swLoadExternalReferences
swLoadExternalReferences_e

Warn about saving referenced documents

Toggle

Not Supported

Search file locations for external references

Toggle

swUseFolderSearchRules

Update out-of-date linked design tables to

Int

swExternalReferencesUpdateOutOfDateLinkedDe
signTable
swExternalReferencesUpdateOutOfDateLinkedDe
signTable_e

Automatically generate names for referenced


geometry

Toggle

swExtRefAutoGenNames

Update component names when documents are


replaced

Toggle

swExtRefUpdateCompNames

Do not create references external to the model

Toggle

swExternalReferencesDisable

104

UserPreference Tables For System Options

API Fundamentals

Lesson 3

Default Templates

Setting

Type

Enumeration / Values

Parts

String

swDefaultTemplatePart

Assemblies

String

swDefaultTemplateAssembly

Drawings

String

swDefaultTemplateDrawing

Always use the default document templates


Prompt user to select document template

Toggle

swAlwaysUseDefaultTemplates

UserPreference Tables For System Options

105

Lesson 3

API Fundamentals

File Locations

Setting

Type

Enumeration / Values

Document Templates

String

swFileLocationsDocumentTemplates

Referenced Documents

String

swFileLocationsDocuments

Custom Property File

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

Sheet Metal Bend Line Note File

String

swFileLocationsBendNoteFormatFile

Sheet Metal Gauge Table

String

Not Supported

Sheet Formats

String

swFileLocationsSheetFormat

Line Style Definitions

String

swFileLocationsLineStyleDefinitions

Dimension / Annotation Favorites

String

swFileLocationsDimensionFavorites

Blocks

String

swFileLocationsBlocks

BOM Templates

String

swFileLocationsBOMTemplates

Hole Table Templates

String

swFileLocationsHoleTableTemplates

Hole Callout Format File

String

swFileLocationsHoleCalloutFormatFile

Revision Table Templates

String

swFileLocationsRevisionTableTemplates

Weldment Cut List Templates

String

swFileLocationsWeldmentCutListTemplates

Weldment Profiles

String

swFileLocationsWeldmentProfiles

Weldment Property File

String

swFileLocationsWeldmentPropertyFile

Macros

String

swFileLocationsMacros

Macro Feature Files

String

swFileLocationsMacroFeatures

Web Folders

String

swFileLocationsWebFolders

SolidWorks Journal File

String

swFileLocationsJournalFile

Design Journal Template

String

swFileLocationsDesignJournalTemplate

106

UserPreference Tables For System Options

API Fundamentals

Lesson 3

Spelling Folders

String

Not Supported

Scene Folders

String

swFileLocationsScenes

Light Folders

String

swFileLocationsLights

Setting

Type

Enumeration / Values

English Units

Double

swSpinBoxEnglishLengthIncrement

Metric Units

Double

swSpinBoxMetricLengthIncrement

Angle increments

Double

swSpinBoxAngleIncrement

Spin Box Increments

UserPreference Tables For System Options

107

Lesson 3

API Fundamentals

View Rotation

Setting

Type

Enumeration / Values

Arrow keys

Double

swViewRotationArrowKeys

Mouse speed

Int

swViewRotationMouseSpeed
0 - 100 (100 is max speed)

View animation speed

Double

swViewAnimationSpeed
Range 0 - 3 (.5 is max speed, 3 is minimum
speed)

108

UserPreference Tables For System Options

API Fundamentals

Lesson 3

Backups

Setting

Type

Enumeration / Values

Save auto recover info every

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

Number of backup copies per document

Int

swBackupCopiesPerDocument

Save backup files in the same location as the


original

Toggle

swSaveBackupFilesInSameLocationAsOriginal

Save backup copies in directory

String

swBackupDirectory

UserPreference Tables For System Options

109

Lesson 3

API Fundamentals

File Explorer

Setting

Type

Enumeration / Values

My Documents

Toggle

swFileExplorerShowMyDocuments

My Computer

Toggle

swFileExplorerShowMyComputer

My Network Places

Toggle

swFileExplorerShowMyNetworkPlaces

Recent Documents

Toggle

swFileExplorerShowRecentDocuments

Hidden referenced documents

Toggle

swFileExplorerShowHiddenReferencedDocuments

Samples

Toggle

swFileExplorerShowSamples

Collaboration

Setting

Type

Enumeration / Values

Enable multi-user environment

Toggle

swCollabEnableMultiUser

Add shortcut menu items for multi-users

Toggle

swCollabAddShortcutMenuItems

Check files opened read-only have been modified.

Toggle

swCollabCheckReadOnlyModifiedByOthers

Check files every _ minutes

Int

Use the values in the enumeration:


swCollabCheckReadOnlyModifiedInterval_e

110

UserPreference Tables For System Options

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.

Detailing

Setting

Type

Enumeration / Values

Dimensioning Standard

Int

swDetailingDimensionStandard
Use enumeration values from
swDetailingStandard_e to change the standard

Dual dimensions display

Toggle

swDetailingDualDimensions

On Top / On Right

Int

swDetailingDualDimPosition
Use enumeration values from
swDetailingDualDimPosition_e to change the
position

Fixed size weld symbols

Toggle

swDetailingFixedSizeWeldSymbol

Display datums per 1982

Toggle

swDetailingDisplayDatumsPer1982

Leading Zeroes

Int

swDetailingLeadingZero
swDetailingLeadingZero_e

Trailing Zeroes

Int

swDetailingDimTrailingZero
Use enumeration values from
swDetailingDimTrailingZero_e to change the
trailing zeroes

Alternate section display

Toggle

swDetailingDisplayAlternateSection

Centerline extension

Double

swDetailingCenterlineExtension

Gap

Double

swDetailingWitnessLineGap

Beyond dimension line

Double

swDetailingWitnessLineExtension

Display type

Int

swDetailingDatumDisplayType
Use enumeration values from
swDatumDisplaytype_e
to change the datum display type

Next label

String

swDetailingNextDatumFeatureLabel

Display symbols per 2002

Toggle

swDetailingDisplaySFSymbolsPer2002

UserPreference Tables For Document Properties

111

Lesson 3

API Fundamentals

Dimensions

Setting

Type

Enumeration / Values

Add parentheses by default

Toggle

swDetailingDimsShowParenthesisByDefault

Snap text to grid

Toggle

swDetailingDimsSnapTextToGrid

Center between extension lines

Toggle

swDetailingDimsCenterText

Include prefix inside basic tolerance box

Toggle

swDetailingDimsPrefixInsideBasicTolBox

Automatically jog ordinates

Toggle

swDetailingDimsAutoJogOrdinates

Offset Distance between dimensions

Double

swDetailingDimToDimOffset

Offset Distance from object

Double

swDetailingObjectToDimOffset

Arrows - Style

Int

swDetailingArrowStyleForDimensions
Use enumeration values from swArrowStyle_e.

Outside - Inside - Smart

Int

swDetailingDimensionArrowPosition
Use enumeration values from
swDimensionArrowSide_e.

Display 2nd outside arrow (Radial)

Toggle

swDetailingRadialDimsDisplay2ndOutsideArrow

Arrows follow position of text (Radial)

Toggle

swDetailingRadialDimsArrowsFollowText

Gap

Double

swDetailingDimBreakGap

Break around dimension arrows only

Toggle

swDetailingDimBreakAroundArrow

Bent Leader Length

Double

swDetailingDimBentLeaderLength

Text alignment Horizontal

Int

swDetailingDimensionTextAlignmentHorizontal
Use enumeration values from
swTextJustification_e

Text alignment Vertical

Int

swDetailingDimensionTextAlignmentVertical
Use enumeration values from
swTextAlignmentVertical_e

Angle/Linear / Angled Display - Use Bent Leaders

Toggle

Not Supported

112

UserPreference Tables For Document Properties

API Fundamentals

Lesson 3

Notes

Setting

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

Leader justification snapping

Toggle

Not Supported

Border Style

Int

swDetailingBalloonStyle
swBaloonStyle_e

Border Size

Int

swDetailingBalloonFit
swBaloonFit_e

Display sheet metal bend notes

Toggle

swShowSheetMetalBendNotes

Bend note Style

Int

swBendNoteStyle
swBendNoteStyle_e

UserPreference Tables For Document Properties

113

Lesson 3

API Fundamentals

Balloons

Setting

Type

Enumeration / Values

Single balloon - Style

Int

swDetailingBOMBalloonStyle
swBalloonStyle_e

Single balloon - Size

Int

swDetailingBOMBalloonFit
swBalloonFit_e

Stacked balloon - Style

Int

swDetailingBOMStackedBalloonStyle
swBalloonStyle_e

Stacked balloon - Size

Int

swDetailingBOMStackedBalloonFit
swBalloonFit_e

Balloon text - upper

Int

swDetailingBOMUpperText
swBalloonTextContent_e

Balloon text - lower

Int

swDetailingBOMLowerText
swBalloonTextContent_e

Bent leaders - Use bent leaders

Toggle

swDetailingBalloonsDisplayWithBentLeader

Bent leaders - Leader length

Double

swDetailingBalloonBentLeaderLength

Auto Balloon Layout

Int

swDetailingAutoBalloonLayout
swBalloonLayoutType_e

114

UserPreference Tables For Document Properties

API Fundamentals

Lesson 3

Arrows

Setting

Type

Enumeration / Values

Arrow Height

Double

swDetailingArrowHeight

Arrow Width

Double

swDetailingArrowWidth

Arrow Length

Double

swDetailingArrowLength

Arrow style for Edge / vertex

Int

swDetailingArrowStyleForEdgeVertexAttachmen
t
swArrowStyle_e

Arrow style for Face / vertex

Int

swDetailingArrowStyleForFaceAttachment
swArrowStyle_e

Arrow style for Unattached

Int

swDetailingArrowStyleForUnattached
swArrowStyle_e

Foreshortened diameter style

Int

swDetailingForeshortenedDiameterStyle
swDetailingForeshortenedDiameterStyle_e

Section View Arrow Length

Double

swDetailingSectionArrowLength

Section View Arrow Width

Double

swDetailingSectionArrowWidth

Section View Arrow Height

Double

swDetailingSectionArrowHeight

UserPreference Tables For Document Properties

115

Lesson 3

API Fundamentals

Virtual Sharps

Setting

Type

Enumeration / Values

Virtual Sharps Style

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

Shaded cosmetic threads

Toggle

swDisplayShadedCosmeticThreads

Geometric tolerances

Toggle

swDisplayGeometricTolerances

Notes

Toggle

swDisplayNotes

Surface finish

Toggle

swDisplaySurfaceFinishSymbols

Annotations Display

116

UserPreference Tables For Document Properties

API Fundamentals

Lesson 3

Welds

Toggle

swDisplayWeldSymbols

Display all types

Toggle

swDisplayAllAnnotations

Text scale numerator

Int

swAnnotationTextScaleNumerator

Text scale denominator

Int

swAnnotationTextScaleDenominator

Always display text the same size

Toggle

swDisplayTextAtSameSizeAlways

Display items only in the view in which they are


created

Toggle

swDisplayOnlyInViewOfCreation

Display annotations

Toggle

swDisplayAnnotations

Use assembly setting for all components

Toggle

swDisplayAnnotationsUseAssemblySettings

Hide dangling dimensions and annotations

Toggle

swAnnotationDisplayHideDanglingDim

Annotations Font

Setting

Type

Enumeration / Values

Note

Text
Format

swDetailingNoteTextFormat

Dimension

Text
Format

swDetailingDimensionTextFormat

Detail

Text
Format

swDetailingDetailTextFormat

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

UserPreference Tables For Document Properties

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

Major grid spacing

Double

swGridMajorSpacing

Minor-lines per major

Int

swGridMinorLinesPerMajor

Snap points per minor

Int

swSnapPointsPerMinor

Do

Setting

118

UserPreference Tables For Document Properties

API Fundamentals

Lesson 3

Units

ModelDoc2::SetUnits may also be used to change these settings.

Setting

Type

Enumeration / Values

Unit System

Int

swUnitSystem
swUnitSystem_e

Length Units

Int

swUnitsLinear
swLengthUnit_e

Length Units - Decimal / Fractions

Int

swUnitsLinearDecimalDisplay
swFractionDisplay_e

Length Units - Round to nearest fraction

Toggle

swUnitsLinearRoundToNearestFraction

Length Units - Decimal places

Int

swUnitsLinearDecimalPlaces

Length Units - Denominator

Int

swUnitsLinearFractionDenominator

Length Units - Convert from 2-4 to 2-4 forma

Toggle

swUnitsLinearFeetAndInchesFormat

Dual Units

Int

swUnitsDualLinear
swLengthUnit_e

Dual Units - Decimal / Fractions

Int

swUnitsDualLinearDecimalDisplay
swFractionDisplay_e

Dual Units - Round to nearest fraction

Toggle

swUnitsDualLinearRoundToNearestFraction

Dual Units - Decimal places

Int

swUnitsDualLinearDecimalPlaces

Dual Units - Denominator

Int

swUnitsDualLinearFractionDenominator

Dual Units - Convert from 2-4 to 2-4 forma

Toggle

swUnitsDualLinearFeetAndInchesFormat

Angular Units

Int

swUnitsAngular
swAngleUnit_e

Angular Units - Decimal Places

Int

swUnitsAngularDecimalPlaces

Density Units - Length

Int

swUnitsMassPropLength
swLengthUnit_e

Density Units - Mass

Int

swUnitsMassPropMass
swUnitsMassPropMass_e

Density Units - Per unit volume

Int

swUnitsMassPropVolume
swUnitsMassPropVolume_e

Density Units - Decimal places

Int

swUnitsMassPropDecimalPlaces

Force

Int

swUnitsForce
swUnitsForce_e

UserPreference Tables For Document Properties

119

Lesson 3

API Fundamentals

Colors

Setting

Type

Enumeration / Values

Wireframe/HLR

Int

swDocumentColorWireFrame

Shading

Int

swDocumentColorShading

Hidden

Int

swDocumentColorHidden

Bend

Int

swDocumentColorFeatBend

Boss

Int

swDocumentColorFeatBoss

Cavity

Int

swDocumentColorFeatCavity

Chamfer

Int

swDocumentColorFeatChamfer

Cut

Int

swDocumentColorFeatCut

Cut-Loft

Int

swDocumentColorFeatLoftCut

Cut-Surface

Int

swDocumentColorFeatSurfCut

Cut-Sweep

Int

swDocumentColorFeatSweepCut

Weld Bead

Int

swDocumentColorFeatWeldBead

Extrude

Int

swDocumentColorFeatExtrude

Fillet

Int

swDocumentColorFeatFillet

Hole

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

120

UserPreference Tables For Document Properties

API Fundamentals

Lesson 3

Form feature

Int

swDocumentColorFeatForm

Shape Feature

Int

swDocumentColorFeatShape

Replace Face

Int

swDocumentColorFeatReplaceFace

Structural Member

Int

swDocumentColorFeatStructuralMember

Gusset

Int

swDocumentColorFeatGusset

End cap

Int

swDocumentColorFeatEndCap

Wrap

Int

swDocumentColorFeatWrap

Apply same color to wireframe, HLR, and shaded

Toggle

swColorsWireframeHLRShadedSame

Ignore feature colors

Toggle

swIgnoreFeatureColors

Material Properties

Setting

Type

Enumeration / Values

Density

Double

swMaterialPropertyDensity

Area Hatch/ Fill

Int

swMaterialPropertyAreaHatchFillStyle
swAreaHatchFillStyle_e

Area Hatch / Pattern

String

swMaterialPropertyCrosshatchPattern
Use the pattern strings listed in the combo
box for this document property.

Area Hatch / Scale

Double

swMaterialPropertyCrosshatchScale

Area Hatch / Angle

Double

swMaterialPropertyCrosshatchAngle

UserPreference Tables For Document Properties

121

Lesson 3

API Fundamentals

Image Quality

Setting

Type

Enumeration / Values

Shaded and draft quality HLR/HLV resolution

Int

swImageQualityShaded

Deviation

Double

swImageQualityShadedDeviation

Optimize edge length (higher quality but slower)

Toggle

swImageQualityUseHighQualityEdgeSize

Apply to all referenced part documents

Toggle

swImageQualityApplyToAllReferencedPartDoc

Save tessellation with part document

Toggle

swImageQualitySaveTesselationWithPartDoc

Wireframe and high quality HLR/HLV resolution

Int

swImageQualityWireframe
Range 0 - 100

Setting

Type

Enumeration / Values

Transparency

Int

swPlaneDisplayTransparency
Range = 0 - 100

Show Intersections

Toggle

swPlaneDisplayShowIntersections

Plane Display

122

UserPreference Tables For Document Properties

API Fundamentals

Exercise 6:
Change Multiple System Options

se

Exercise 6:
Change Multiple
System Options

Objective

To change multiple system options using the SolidWorks API. Create a


macro that sets the following items within Tools, Options...:
General - Show thumbnail graphics in Windows Explorer
Display/Selection - Hidden edges displayed as Dashed
Display/Selection - Assembly transparency for in context edit - Force
assembly transparency; slider bar set to 50%
Backup - Save backup copies in directory: D:\Temp

Skills Learned

APIs Used

SldWorks.SetUserPreferenceToggle
SldWorks.SetUserPreferenceIntegerValue
SldWorks.SetUserPreferenceStringValue

Procedure

1.
2.
3.
4.

Programming system options in SolidWorks.

Open SolidWorks with no files created.


Create a new macro named SystemOptions.swp.
Add code to fit the description above.
Save and test the macro.

123

Exercise 6:

API Fundamentals

Change Multiple System Options

Solution

Option Explicit
Dim swApp As SldWorks.SldWorks
Dim value As String
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

Exercise 7:
Change Multiple
Document
Properties

Objective

To change multiple document properties using the SolidWorks API.


Create a macro that sets the following items within Tools, Options:
Detailing - Dimensioning Standard: ANSI
Arrows- Height: 0.15in, Width: 0.42in, Length: 1.50in
Units - Linear Units: Inches
Units - Linear Units, Decimal Places: 3

Skills Learned

APIs Used

SldWorks.SetUserPreferenceDoubleValue
SldWorks.SetUserPreferenceIntegerValue
SldWorks.SetUserPreferenceStringValue

Procedure

1.
2.
3.
4.

Setting document properties in SolidWorks with the API.

Open a new part file in SolidWorks.


Create a new macro named DocumentProperties.swp.
Add code to fit the description above.
Save and test the macro.

125

Exercise 7:

API Fundamentals

Change Multiple Document Properties

Solution

Dim swApp As SldWorks.SldWorks


Dim swModel As SldWorks.ModelDoc2
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

API Fundamentals

Lesson 4
Automating Part Design

Upon successful completion of this lesson, you will be able to:


I

Design a macro around the part creation process.

Automate sketching entities.

Add dimensions to sketch entities.

Automatically create features such as extrudes and revolves.

Learn how to enable and use contour selection with the API.

127

Lesson 4
Automating Part Design

128

API Fundamentals

API Fundamentals

Lesson 4
Automating Part Design

Case Study:
Automation
Tool for Parts

This macro is designed to


explore the various API calls
used when creating parts. It
automates user preferences,
sketch commands,
dimensioning, contour
selection and feature
definitions.
The macro has one form
containing a multi-page tab
control. Each tab allows the
user to choose which option
to set:

Material
(aluminum or brass)

Profile
(rectangular or circular)

Machine operation
(extrusion, extrusion
with contour selection,
or revolution).

Edit macro.

Open the macro PartAutomation.swp.


2

Store values to database and set units.

Double-click the command button Build Part and enter the


following lines of code:
Private Sub cmdBuild_Click()
Set swApp = Application.SldWorks
Set swModel = swApp.NewPart
swModel.SetAddToDB True
swModel.SetUserPreferenceIntegerValue swUnitsLinear, swMM
swModel.SetAddToDB False
End Sub

Note

Use ModelDoc2::SetAddToDB to add sketch entities while avoiding


grid and entity snapping. This method will also improve system
performance when adding sketch entities with the API. It is a toggle
that is turned on by passing True to the parameter list. After the
sketching APIs have finished, turn it off by calling SetAddToDB again,
and pass False to its parameter list.

Case Study: Automation Tool for Parts

129

Lesson 4

API Fundamentals

Automating Part Design

Setting Material

For the first tab, call ModelDoc2::SetUserPreferenceDoubleValue to


set the material density and crosshatch pattern.

Add code to set the material.


Private Sub cmdBuild_Click()
Set swApp = Application.SldWorks
Set swModel = swApp.NewPart
swModel.SetAddToDB True
swModel.SetUserPreferenceIntegerValue swUnitsLinear, swMM
MATERIAL
If optAl.Value = True Then
swModel.SetUserPreferenceDoubleValue _
swConst.swMaterialPropertyDensity, 2700
swModel.SetUserPreferenceStringValue _
swConst.swMaterialPropertyCrosshatchPattern, _
"ISO (Aluminum)"
Else
swModel.SetUserPreferenceDoubleValue _
swConst.swMaterialPropertyDensity, 8600
swModel.SetUserPreferenceStringValue _
swConst.swMaterialPropertyCrosshatchPattern, _
"ISO (Bronze Brass)"
End If
PROFILE
MACHINE OPERATION
swModel.SetAddToDB False
End Sub

130

Case Study: Automation Tool for Parts

API Fundamentals

Lesson 4
Automating Part Design

Creating the
Sketch Rectangle

For the second tab, call ModelDoc2::SketchRectangle to create the first


profile, ModelDoc2::SketchOffset2 to offset the profile and
ModelDoc2::CreateLine2( ).ConstructionGeometry to create the axis.

1. Create rectangle

2. Create offset

3. Add axis

Adding
Dimensions

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.
The same is true for feature creation.
For instance, if you create a reference plane with a method like
CreatePlaneAtOffset3, or any of the plane creation APIs, the plane will
be selected and highlighted in the FeatureManager design tree. No
selection APIs would be needed to select the plane if the program made
a call to ModelDoc2::InsertSketch2 immediately after it was created.

Note

A detailed review of the selection APIs are covered in Selection and


Traversal Techniques on page 177.

Case Study: Automation Tool for Parts

131

Lesson 4

API Fundamentals

Automating Part Design

Add code to sketch and dimension a rectangle.

Add code to sketch and dimension the profiles.


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

Case Study: Automation Tool for Parts

API Fundamentals

Lesson 4
Automating Part Design

Creating the
Sketch Circle

Call ModelDoc2::CreateCircleByRadius2 to create the second profile.

1. Create circle

2. Create offset

3. Use axis from


previous step

Add code to sketch circle.

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

Creating Extruded
Features

Call FeatureManager::FeatureExtrusion to create the extrude feature.

Case Study: Automation Tool for Parts

133

Lesson 4

API Fundamentals

Automating Part Design

Add code to create an extruded feature.


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

Contour selection is used to select multiple contours when creating


features. In the SolidWorks user interface, a user must put SolidWorks
into contour select mode and then manually select the contours that
they want to extrude or cut. The API provides access to the contour
select capabilities and allows the programmer to automate the selection
process for multiple contours.
Call the SelectionManager::EnableContourSelection to put
SolidWorks into contour selection mode.
Then use ModelDocExtention::SelectByID2 to select the contours used
to extrude or revolve the new feature. When finished, turn off contour
selection.

134

Case Study: Automation Tool for Parts

API Fundamentals

Lesson 4
Automating Part Design

Add code to enable contour selection.


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

Creating Revolved
Features

Call FeatureManager::FeatureRevolve to create the revolve feature.

Case Study: Automation Tool for Parts

135

Lesson 4

API Fundamentals

Automating Part Design

Add code to create revolved feature.


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

Save and run macro.

Test the various options and combinations on the user form. Return to
VBA when finished.

136

Case Study: Automation Tool for Parts

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
NewDocument

PrintDirect
PrintOut

OpenDoc6
LoadFile2

Rebuild
EditRebuild3
ForceRebuild3

Save3
SaveAs4
SaveBMP

Standard View Commands


ShowNamedView2 "*Front", 1

ShowNamedView2 "*Top", 5

ShowNamedView2 "*Back", 2

ShowNamedView2 "*Bottom", 6

ShowNamedView2 "*Left", 3

ShowNamedView2 "*Isometric", 7

ShowNamedView2 "*Right", 4

ShowNamedView2 "*Normal To", 0

Also available through the API:

Note

ShowNamedView2 "*Trimetric", 8
ShowNamedView2 "*Dimetric", 9

View Commands
TranslateBy

ViewDisplayWireframe

ViewOrientationUndo

ViewDisplayHiddengreyed

ViewZoomtofit2

ViewDisplayHiddenremoved

ViewZoomTo2

HlrQuality = 1

ZoomByFactor

HlrQuality = 0

ViewZoomToSelection

ViewDisplayShaded

RotateAboutCenter

AddPerspective

Case Study: Automation Tool for Parts

137

Lesson 4

API Fundamentals

Automating Part Design

Sketch Commands
SelectByID2
SelectByRay

Insert3DSketch2

GridOptions

SketchModifyFlip
SketchModifyRotate
SketchModifyScale
SketchModifyTranslate

InsertSketch2

AutoSolveToggle

Sketch Tools Commands

138

CreateLine2

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

SketchRectangleAtAnyAngle

SplitOpenSegment
SplitClosedSegment

CreatePoint2

CreateLinearSketchStepAndRepeat

CreateCenterLine
CreateLine2.ConstructionGeometry

CreateCircularSketchStepAndRepeat

InsertSketchText

InsertSketchPicture

Case Study: Automation Tool for Parts

API Fundamentals

Lesson 4
Automating Part Design

Features Commands
FeatureExtrusion
FeatureExtrusionThin
FeatureBoss

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

Sketch Relations Commands


AddDimension2
AddHorizontalDimension2
AddVerticalDimension2

GetConstraints

SketchAddConstraints

Autodimension

Reference Geometry Commands


CreatePlaneAtAngle3
CreatePlaneAtOffset3
CreatePlaneAtSurface3
CreatePlaneFixed2
CreatePlanePerCurveAndPassPoint3
CreatePlaneThru3Points3
CreatePlaneThruLineAndPt
CreatePlaneThruPtParallelToPlane

Case Study: Automation Tool for Parts

InsertCoordinateSystem
InsertAxis2

139

Lesson 4

API Fundamentals

Automating Part Design

140

Case Study: Automation Tool for Parts

API Fundamentals

Exercise 8:
Automating the Part Creation Process

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

Automating sketch entities and dimensions


Automating features and set user preferences.

APIs Used

ModelDoc2.SetUserPreferenceDoubleValue
ModelDoc2.SetUserPreferenceStringValue
SldWorks.SetUserPreferenceToggle
ModelDoc2.CreateLine2
ModelDoc2.ViewZoomtofit2
ModelDoc2.AddDimension2
FeatureManager.FeatureExtrusionThin
FeatureManager.FeatureRevolveThin

Procedure

1.
2.
3.
4.
5.

Open the macro AutomatingPartDesign.swp.


Add missing controls to the form.
Program the click event for the Build Part command button.
Use the APIs listed above to automate the design of an L bracket.
Save and run macro.

141

Exercise 8:

API Fundamentals

Automating the Part Creation Process

Solution

Dim swApp As SldWorks.SldWorks


Dim swModel As SldWorks.ModelDoc2
Dim swFeatMgr As SldWorks.FeatureManager
Private Sub cmdBuild_Click()
Set swApp = Application.SldWorks
Set swModel = swApp.NewPart
swModel.SetUserPreferenceIntegerValue swConst.swUnitsLinear,_
swConst.swMETER
If chkSteel.Value = True Then
swModel.SetUserPreferenceDoubleValue _
swConst.swMaterialPropertyDensity, 7800
swModel.SetUserPreferenceStringValue _
swConst.swMaterialPropertyCrosshatchPattern, _
"ISO (Steel)"
End If
swModel.InsertSketch2 False
Dim Height As Double
Dim Width As Double
Height = CDbl(txtHeight.text) / 1000
Width = CDbl(txtWidth.text) / 1000
swApp.SetUserPreferenceToggle swConst.swInputDimValOnCreate,_
False
swModel.CreateLine2 0.01, 0.01, 0, 0.01, 0.01 + Height, 0
swModel.ViewZoomtofit2
swModel.AddDimension2 0, 0.01 + Height / 2, 0
swModel.CreateLine2 0.01, 0.01, 0, 0.01 + Width, 0.01, 0
swModel.ViewZoomtofit2
swModel.AddDimension2 0.01 + Width / 2, 0, 0
swModel.CreateLine2(0, 0, 0, 0, 0.01, 0). _
ConstructionGeometry = True
swModel.ClearSelection
swModel.ViewZoomtofit2
Dim Thick As Double
Thick = CDbl(txtThick.text) / 1000
If optExtrude.Value = True Then
Dim Depth As Double
Depth = CDbl(txtDepth.text) / 1000
Set swFeatMgr = swModel.FeatureManager
swFeatMgr.FeatureExtrusionThin True, False, True, 0, 0, _
Depth, 0, False, False, False, False, 0, 0, False, _
False, False, False, False, Thick, 0, 0, 0, 0, False, _
False, False, False
swModel.ViewZoomtofit2
Else
Dim Angle As Double
Angle = CDbl(txtAngle.text * 3.14 / 180)
Set swFeatMgr = swModel.FeatureManager
swFeatMgr.FeatureRevolveThin Angle, 0, 0, 0, Thick, 0, 0, _
1, 1, 1
End If
swModel.ShowNamedView2 "Isometric", 7
swModel.ViewZoomtofit2
End Sub

142

API Fundamentals

Lesson 5
Assembly Automation

Upon successful completion of this lesson, you will be able to:


I

Open components invisible to the user.

Understand the use of safe entities.

Traverse all the loops in a selected face.

Create and use collections of SolidWorks objects.

Determine if a face is cylindrical.

Use the MathUtility object.

Multiply with transforms.

Add components to specific locations and add mates.

143

Lesson 5
Assembly Automation

144

API Fundamentals

API Fundamentals

Lesson 5
Assembly Automation

Case Study:
Automation
Tool for
Assemblies

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.

Note

This macro works correctly for all configurations of the chassis.

This macro also


works for any
face with a hole.

Case Study: Automation Tool for Assemblies

145

Lesson 5

API Fundamentals

Assembly Automation

Open existing assembly and macro.

Open the assembly Guitar Effect Pedal.sldasm and the macro


AssemblyAutomation.swp.
2

Review code for the form activation.

When the UserForm_Activate event is triggered the macro:


I
I
I
I
I
I

Connects to SldWorks.
Creates a MathUtility object.
Gets a pointer to the active assembly and checks it for validity.
Gets the assembly name.
Truncates the .sldasm extension so we can use it for selection later.
Clears all selections and connects to the SelectionManager object.

Private Sub UserForm_Activate()


Set swApp = Application.SldWorks
Set swMathUtility = swApp.GetMathUtility()
Set swModel = swApp.ActiveDoc
If Not swModel Is Nothing Then
Else
MsgBox ("Open an assembly to run this macro.")
Exit Sub
End If
AssemblyTitle = swModel.GetTitle
Call ParseAssemblyName
swModel.ClearSelection2 (True)
Set swSelMgr = swModel.SelectionManager
End Sub
Public Sub ParseAssemblyName()
Dim strings As Variant
strings = Split(AssemblyTitle, ".")
AssemblyName = strings(0)
End Sub

Tip

146

To navigate quickly to the UserForm_Activate event, double-click on


an empty grey area on the user form. This will automatically display
the forms code and set the cursor on the first line of code in the event
handler.

Case Study: Automation Tool for Assemblies

API Fundamentals

Lesson 5
Assembly Automation

Review code for the command button.

Double-click the first button on the userform to display the code.


When the command button click event is triggered, the macro:
I
I
I
I
I

Tests the validity of the assembly file.


Stores a pointer to the selected face.
Creates a safe entity so that the face can still be selected when the
face becomes invalid
Tests the validity of the face.
Calls sub routines that perform the automation of adding
components and mating them.

Private Sub cmdAddComponentsAndMate_Click()


If Not swModel Is Nothing Then
Else
MsgBox ("Open an Assembly to run this macro on!")
Exit Sub
End If
Set swSelFace = swSelMgr.GetSelectedObject3(1)
Dim swEntity As SldWorks.entity
Set swEntity = swSelFace
Set swSafeSelFace = swEntity.GetSafeEntity
If Not swSelFace Is Nothing Then
'
Else
MsgBox ("You did not select a face.")
Exit Sub
End If
Call EstablishTargetComponentsTransform
Call OpenComponentModelToAddToAssembly("control knob.SLDPRT")
Call EstablishCircularCurveAndEdgeCollections
Call EstablishCylindricalFaceCollection
Call EstablishPointsCollection
Call AddcomponentsToAssembly("control knob.SLDPRT")
Call Finalize
End Sub

Question

What is the purpose of Entity::GetSafeEntity?

Answer

If you try to store a pointer to a SldWorks::Entity object from an


assembly and try to use it for selection after a component has been
added to an assembly, the entity pointer becomes invalid. If your code
tries to use the invalid pointer, VBA will return a runtime error that
states that the object has disconnected from it's client. If you know that
the entity could become invalid and you need to use it, Use the
Entity::GetSafeEntity accessor method to return a pointer to a safe
entity. An addition of a component or a change to the geometry in an
assembly or a part could cause any of the previously stored face
pointers to become invalid. To address this problem the API provides a
mechanism called a safe entity. The safe entities will not become
invalid if a major geometrical change happens in the assembly during
the execution of the program. A safe entity is a SldWorks::Entity object
that has the ability to survive a major geometrical change.

Case Study: Automation Tool for Assemblies

147

Lesson 5

API Fundamentals

Assembly Automation

Transforms

To determine or move a components physical location in an assembly,


we use transforms. A comprehension of assembly space and part space
is required when working with transforms. All parts and assemblies
have their own origin. When you add a component to an assembly, the
new part may be added anywhere relative to the assemblys origin. If
you place the origin of the part directly on the origin of the assembly so
that all three axes of the origins are collinear, then the assembly space
and the part space are identical. If this is not the case then a transform
can be used to set or get the distance and rotation of the part relative to
the assemblys origin.
In this case study we are trying to add control knobs to the chassis. If
the chassis components origin was not aligned and coincident to the
assemblys origin, then the locations for the AddComponent4 method
would have to be determined by multiplying the center point of the
knob hole on the chassis (which is found in part space) by the transform
of the chassis component which is relative to the assemblys origin.

Creating
MathTransforms

The MathUtility::CreateTransform method is used to create a


MathTransform object. The MathTransform object is a simplified
interface used for manipulating a components transformation data.
The MathTransform object manages the transformation matrix data and
provides methods and properties for manipulating this data.

MathUtility::CreateTransform
retval = MathUtility.CreateTransform (ArrayData)

Return:

retval

Pointer to the newly created MathTransform object.

Input:

ArrayData

Sixteen components of the transform.

The
Transformation
Matrix

The SolidWorks transformation matrix is represented as an array of 16


elements:
I
I
I
I

Tip

148

The first nine are elements of a 3x3 rotational sub-matrix.


The next three define a translation vector.
The next one is a scaling factor.
The last three elements are unused in this context.

The Component2 Interface supports the Component2::Transform2


property that returns its transformation matrix values.

Case Study: Automation Tool for Assemblies

API Fundamentals

Lesson 5
Assembly Automation

Add code to establish a transform.

Find the transform of the chassis component.


I
I
I

Create a component pointer.


Set the component pointer to the entity objects owning component.
Store the MathTransform object of the component on the form.

Public Function EstablishTargetComponentsTransform()


Dim swComponent As SldWorks.Component2
Set swComponent = swSafeSelFace.GetComponent()
Set swCompTransform = swMathUtility.CreateTransform _
(swComponent.Transform2)
End Function

Activating
Documents

Call the SldWorks::ActivateDoc2 method to activate an inactive


document in the SolidWorks session. The file becomes the active
document in the SolidWorks user interface, and the method returns a
pointer to that document object.

SldWorks::ActivateDoc2
retval = SldWorks.ActivateDoc2 (Name, Silent, Errors)

Return:

retval

Pointer to a Dispatch object, the document.

Input:

Name

Name of document to activate.

Input:

Silent

TRUE if dialogs and warning messages should be


avoided, FALSE if dialogs and warning messages
should be displayed to the user.

Output:

Errors

An unspecified error was


encountered, and the document was not activated.
swDocNeedsRebuildWarning = The document that was
activated needs to be rebuilt.
swGenericActivateError =

Invisible
Documents

SldWorks::DocumentVisible is used to hide documents from the end


user when they are opened. When a program opens multiple component
part files to add them to an assembly, the SolidWorks user interface
becomes cluttered with all the open documents. A well behaved
program would use this API to hide all this activity from the end user.
Passing False to the visible parameter will hide the newly opened
documents from the user. Passing True will show the newly opened
documents.

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.

Case Study: Automation Tool for Assemblies

149

Lesson 5

API Fundamentals

Assembly Automation

SldWorks::DocumentVisible
retval = SldWorks.DocumentVisible (visible, type)

Return:

void

There is no return value.

Input:

visible

True

Input:

type

Any of the 3 SolidWorks document types use the


enumerations swDocumentTypes_e for valid values.

to show this document type, False to hide it.

Open component.

Add the following code to the


OpenComponentModelToAddToAssembly sub program.
The following code:
I
I
I

Turns off visibility for any newly opened documents.


Opens the components part document.
Reactivates the assembly to do the rest of the work.

Public Sub OpenComponentModelToAddToAssembly(ByVal _


strCompModelname As String)
swApp.DocumentVisible False, swDocPART
swApp.OpenDoc6 strCompModelname, 1, 0, "", errors, warnings
Set swModel = swApp.ActivateDoc2 (AssemblyTitle, True, errors)
Set swAssy = swModel
End Sub

Object Collections

A collection is very similar to an array. It is a data structure used to


manage an array of objects. A collection also has several members used
to add, manage, and remove the data from it.

Establishing the
Curve and Edge
Collections

The EstablishCircularCurveAndEdgeCollections sub program


establishes collections of geometry gathered from the selected face of
the chassis component. These collections of geometry will be used later
in the code for adding mates between the chassis and the control knob.
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

Case Study: Automation Tool for Assemblies

API Fundamentals

Lesson 5
Assembly Automation

Here is the pseudo code for the


EstablishCircularCurveAndEdgeCollections sub program:
I
I
I
I
I
I

Get the first loop on the face.


Traverse all the loops in the selected face.
If it's an inner loop, get the array of edges belonging to the loop.
For every edge in the array get its curve object.
If the curve is a circle then add the current edge to the edge
collection and add the current curve to the curve collection.
Traverse until no more loops are available.

Establish curve and edge collections.

Add the following code to the


EstablishCircularCurveAndEdgeCollections sub program.
Public Sub EstablishCircularCurveAndEdgeCollections()
Dim swLoop As SldWorks.Loop2
Set swLoop = swSelFace.GetFirstLoop
While Not swLoop Is Nothing
If swLoop.IsOuter Then
Don't do anything if it is the outer loop
Else
Dim swEdges As Variant
swEdges = swLoop.GetEdges()
For i = 0 To UBound(swEdges)
Dim swCurve As SldWorks.Curve
Set swCurve = swEdges(i).GetCurve
If swCurve.IsCircle Then
CircularEdgeCollection.Add swEdges(i)
CircularCurveCollection.Add swCurve
End If
Next i
End If
Set swLoop = swLoop.GetNext
Wend
End Sub

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.

Case Study: Automation Tool for Assemblies

151

Lesson 5

API Fundamentals

Assembly Automation

The EstablishCylindricalFaceCollection sub program gathers the


cylindrical faces of the control knob holes and adds them to the
SafeCylindricalFaceCollection.
This sub program traverses the edges stored in the EdgeCollection. It
uses the method Edge::GetTwoAdjacentFaces to return a pointer to
each face that shares the edge. A surface pointer is then returned from
each face. The Surface::IsCylinder property is then used to determine
which of these faces will be the cylindrical face used for the concentric
mate. When the cylindrical face is found, its safe entity is added to the
SafeCylindricalFaceCollection.
Here is the pseudo code:
I
I
I
I
I
I

Getting Adjacent
Faces

Use Edge::GetTwoAdjacentFaces to get faces sharing the circular


edge.
Declare a surface pointer for the first face.
Declare another surface pointer for the second face.
Set the first and second surface pointers.
Determine which one is the cylindrical surface.
When the cylindrical face is found, add it to the face collection.

Use the Edge::GetTwoAdjacentFaces method to return the two


adjacent faces of an edge.

Edge::GetTwoAdjacentFaces
Edge.GetTwoAdjacentFaces (Face1, Face2)

Output:

Face1

Pointer to the first adjacent face.

Output:

Face2

Pointer to the second adjacent face.

Establish face collection.

Add the following code to the EstablishCylindricalFaceCollection sub


program.
Public Sub EstablishCylindricalFaceCollection()
For i = 1 To CircularEdgeCollection.Count
Dim swFaces As Variant
swFaces = CircularEdgeCollection.Item(i). _
GetTwoAdjacentFaces()
Dim swSurface1 As SldWorks.surface
Dim swSurface2 As SldWorks.surface
Set swSurface1 = swFaces(0).GetSurface
Set swSurface2 = swFaces(1).GetSurface
Dim swTempSurf As Sldworks.surface
Dim swEntity As SldWorks.entity
If swSurface1.IsCylinder Then
'Determine which one is the cylindrical surface
Set swTempSurf = swSurface1
Set swEntity = swFaces(0)

152

Case Study: Automation Tool for Assemblies

API Fundamentals

Lesson 5
Assembly Automation

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

One more collection needs to be established before adding the knob


components to the assembly and mating them. A collection of points is
required for adding the new components in the correct location in the
assembly. The points required are the center points of the circular edges
of the knob holes on the chassis component.

Getting Curve
Parameters

The method Curve::CircleParams is used to get the parameters of a


circular curve. The first three values of the returned array are the center
point of the curve.

Curve::CircleParams
retval = Curve.CircleParams ( )

Return:

retval

SafeArray of seven doubles:


center.x, center.y, center.z, axis.x, axis.y, axis.z and
radius
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.
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.

Important!

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.

Case Study: Automation Tool for Assemblies

153

Lesson 5

API Fundamentals

Assembly Automation

The pseudo code for the EstablishPointsCollection is:


I
I
I
I
I
I

Traverse every circular curve and get its center point.


For each circular curve, fill the circleParams array with the circle
information from the curve.
Create an array to store the center point coordinates.
Create a MathPoint object using the coordinate array.
Multiply the MathPoint by the chassis component's transform.
Add the MathPoint to the PointCollection.

Establish point collection.

Add the following code to the EstablishPointsCollection sub


program.
Public Sub EstablishPointsCollection()
For i = 1 To CircularCurveCollection.Count()
Dim circleParams As Variant
circleParams = CircularCurveCollection(i).circleParams
Dim arrayData(2) As Double
Dim swMathPoint As SldWorks.mathPoint
arrayData(0) = circleParams(0)
arrayData(1) = circleParams(1)
arrayData(2) = circleParams(2)
Set swMathPoint = swMathUtility.CreatePoint(arrayData)
Set swMathPoint = swMathPoint. _
MultiplyTransform(swCompTransform)
PointCollection.Add swMathPoint
Next i
End Sub

Adding and Mating


the Knobs to the
Chassis

A sub program named AddComponentsToAssembly is used to add the


new knob components to the assembly and mate them to the chassis.
The pseudo code for the AddComponentsToAssembly sub program is as
follows:
I
I
I
I
I
I
I
I

154

For every location in the point collection:


Add a coincident mate between the bottom face of the knob
component and the selected face on the chassis component.
Add the control knob to the location of the point in the
PointCollection.
Get the name and instance number of the newly added component
for selection purposes.
Select the top plane of the newly added control knob.
Add a coincident mate.
Select the origin of the new control knob and the corresponding
cylindrical face in the cylindrical face collection.
Add the concentric mate.

Case Study: Automation Tool for Assemblies

API Fundamentals

Lesson 5
Assembly Automation

Adding
Components

Use the AssemblyDoc::AddComponent4 method to add a component or


sub assembly to the current assembly.

AssemblyDoc::AddComponent4
retval = AssemblyDoc.AddComponent2 (CompName, X, Y, Z)

Return:

retval

Pointer to dispatch object for the added component.

Input:

CompName

Path name of a loaded part/assembly to add as a


component.

Input

ConfigName

Input:

X coordinate of the component center.

Input:

Y coordinate of the component center.

Input:

Z coordinate of the component cente.r

Adding Mates

Call the AssemblyDoc::AddMate method to create a new mate in an


assembly.

AssemblyDoc::AddMate
AssemblyDoc.AddMate (MateType, Align, Flip, Dist, Angle)

Input:

MateType

swMateCOINCIDENT
swMateCONCENTRIC
swMatePERPENDICULAR
swMatePARALLEL
swMateTANGENT
swMateDISTANCE
swMateANGLE
swMateUNKNOWN

Input:

Align

swMateAlignALIGNED
swMateAlignANTI_ALIGNED
swMateAlignCLOSEST

Input:

Flip

TRUE

Input:

Dist

Distance value used with swMateDISTANCE mate type.

Input:

Angle

Angle value used with swMateANGLE mate type.

Case Study: Automation Tool for Assemblies

to flip the component, FALSE otherwise.

155

Lesson 5

API Fundamentals

Assembly Automation

Add a knob to the assembly and mate it.

Add the following code to the AddComponentsToAssembly sub


program.
Public Sub AddcomponentsToAssembly(ByVal _
strCompFullPath As String)
For j = 1 To PointCollection.Count
Dim swComponent As SldWorks.Component2
Dim pointData As Variant
pointData = PointCollection.Item(j).arrayData
Set swComponent = swAssy.AddComponent4(strCompFullPath,, _
pointData(0), pointData(1), pointData(2))
Dim strCompName As String
strCompName = swComponent.Name2()
swSafeSelFace.Select2 True, 0
swModel.AndSelectByID "Top@" + strCompName & "@" + _
AssemblyName, "PLANE", 0, 0, 0
swAssy.AddMate swMateCOINCIDENT, 0, False, 0, 0
SafeCylindricalFaceCollection(j).Select2 True, 0
swModel.AndSelectByID "Point1@Origin@" + strCompName + _
"@" + AssemblyName, "EXTSKETCHPOINT", 0, 0, 0
swAssy.AddMate swMateCONCENTRIC, 1, False, 0, 0
Next j
End Sub

10 Destroy all collections and variables.

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

11 Save and run macro.


12 Exit macro.

156

Case Study: Automation Tool for Assemblies

API Fundamentals

Exercise 9:
Adding Components

Exercise 9:
Adding
Components

Correct
positions

Incorrect
component
positions

Objective

To understand the use of component transforms by commenting out


certain lines of prebuilt code to illustrate what happens when
transforms are not applied to new components. The control knob will
be added to the assembly in chassis part space, not where the chassis
lives in assembly space.
The chassis has been deliberately moved to the
X 3.0, Y 3.0, Z 3.0 assembly location to highlight this.

Skills Learned

Procedure

Debugging transforms.

Positioning components correctly in assembly space with or


without using mates.

1. Open the assembly Transforms.sldasm.


2. Open the macro Transforms.swp
3. Add breakpoint to the following line.
Call AddcomponentsToAssembly("control knob.SLDPRT")

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

Solution

Private Sub cmdAddComponentsAndMate_Click()


Set swSelFace = swSelMgr.GetSelectedObject3(1)
Dim swEntity As SldWorks.entity
Set swEntity = swSelFace
Set swSafeSelFace = swEntity.GetSafeEntity
If Not swSelFace Is Nothing Then
Else
MsgBox ("You did not select a face.")
Exit Sub
End If
Call EstablishTargetComponentsTransform
Call OpenComponentModelToAddToAssembly("control knob.SLDPRT")
Call EstablishCircularCurveAndEdgeCollections
Call EstablishCylindricalFaceCollection
Call EstablishPointsCollection
Step 3 - Add breakpoint here.
Call AddcomponentsToAssembly("control knob.SLDPRT")
Call Finalize
End Sub
Public Sub EstablishPointsCollection()
For i = 1 To CircularCurveCollection.Count()
Dim circleParams As Variant
circleParams = CircularCurveCollection(i).circleParams
Dim arrayData(2) As Double
Dim swMathPoint As SldWorks.mathPoint
arrayData(0) = circleParams(0)
arrayData(1) = circleParams(1)
arrayData(2) = circleParams(2)
Set swMathPoint = swMathUtility.CreatePoint(arrayData)
Step 6 - Comment the next line.
Set swMathPoint = swMathPoint.MultiplyTransform _
(swCompTransform)
PointCollection.Add swMathPoint
Next i
End Sub
Public Sub AddcomponentsToAssembly(ByVal _
strCompFullPath As String)
For j = 1 To PointCollection.Count
Dim swComponent As Component2
Dim pointData As Variant
pointData = PointCollection.Item(j).arrayData
Set swComponent = swAssy.AddComponent4(strCompFullPath,"", _
pointData(0), pointData(1), pointData(2))
Step 6 - Comment the following lines of code.
Dim strCompName As String
strCompName = swComponent.Name2()
swSafeSelFace.Select2 True, 0
swModel.AndSelectByID "Top@" + strCompName & "@" + _
AssemblyName, "PLANE", 0, 0, 0
swAssy.AddMate swMateCOINCIDENT, 0, False, 0, 0
SafeCylindricalFaceCollection(j).Select2 True, 0
swModel.AndSelectByID "Point1@Origin@" + strCompName + _
"@" + AssemblyName, "EXTSKETCHPOINT", 0, 0, 0
swAssy.AddMate swMateCONCENTRIC, 1, False, 0, 0
Next j
End Sub

158

API Fundamentals

Lesson 6
Drawing Automation

Upon successful completion of this lesson, you will be able to:


I

Design a macro to automate drawing creation.

Create a drawing with multiple sheets based on an assembly with


multiple configurations.

Insert drawing views on each sheet in the drawing.

Automatically insert model annotations and dimensions.

Automatically save drawings in different file formats.

159

Lesson 6
Drawing Automation

160

API Fundamentals

API Fundamentals

Lesson 6
Drawing Automation

Case Study:
Automating
Drawing
Creation

This macro is designed to explore API calls associated with creating


drawings. It automates the production of new drawing sheets and
names each sheet after a specific configuration. It also imports model
dimensions and annotations.

With Cut

Without Cut

Open existing assembly and create new macro.

Open the assembly DrawingAutomation.sldasm. Create a new


macro and name it: DrawingAutomation.swp.
2

Change macro code.

Early bind to SldWorks and connect to the active model.


Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
End Sub

Prompt user for projection type.

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

Case Study: Automating Drawing Creation

161

Lesson 6

API Fundamentals

Drawing Automation

Add drawing template and scaling constants.

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.
Const TemplateName As String = C:\SolidWorks 2006 Training
Files\API Fundamentals\Templates\APIDrawing.drwdot
Const PaperSize As Long = swConst.swDwgPaperA1size
Const ScaleNum As Double = 1
Const ScaleDenom As Double = 2
Dim
Dim
Dim
Dim

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

Create new drawing.

Add the code to create a new drawing document.


Dim
Dim
Dim
Dim
Dim

swApp As SldWorks.SldWorks
swModel As SldWorks.ModelDoc2
Response As Integer
ThirdAngle As Boolean
swDraw As SldWorks.DrawingDoc

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#)
End Sub

Note

162

The macro recorder records the method SldWorks::LoadFile2 to create


a new drawing. This will work, but another method is a better choice
for creating a new drawing: SldWorks::NewDocument.Save and run the
macro.

Case Study: Automating Drawing Creation

API Fundamentals

Lesson 6
Drawing Automation

Save and run the macro.

A new drawing is created, return to VBA when finished.

Getting
Configuration
Names

Use the ModelDoc2::GetConfigurationNames method to get a list of


configuration names existing in this document.

ModelDoc2::GetConfigurationNames
retval = ModelDoc2.GetConfigurationNames ( )

Return:

retval

Safearray of strings containing the names of the


configurations in this part.

Get list of configurations.

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

Case Study: Automating Drawing Creation

163

Lesson 6

API Fundamentals

Drawing Automation

Creating Sheets

Call DrawingDoc::NewSheet3 to create new drawing sheets.

DrawingDoc::NewSheet3
retval = DrawingDoc.NewSheet3 (Name, PaperSize, TemplateIn, Scale1, Scale2,
FirstAngle, TemplateName, Width, Height, PropertyViewName)

Return:

retval

TRUE

Input:

Name

Name of the new sheet.

Input:

PaperSize

swDwgPaperAsize
swDwgPaperAsizeVertical
swDwgPaperBsize
swDwgPaperCsize
swDwgPaperDsize
swDwgPaperEsize
swDwgPaperA4size
swDwgPaperA4sizeVertical
swDwgPaperA3size
swDwgPaperA2size
swDwgPaperA1size
swDwgPaperA0size
swDwgPapersUserDefined

Input:

TemplateIn

swDwgTemplateAsize
swDwgTemplateAsizeVertical
swDwgTemplateBsize
swDwgTemplateCsize
swDwgTemplateDsize
swDwgTemplateEsize
swDwgTemplateA4size
swDwgTemplateA4sizeVertical
swDwgTemplateA3size
swDwgTemplateA2size
swDwgTemplateA1size
swDwgTemplateA0size
swDwgTemplateCustom
swDwgTemplateNone

Input:

Scale1

Scale numerator.

Input:

Scale2

Scale denominator.

Input:

FirstAngle

TRUE

Input:

TemplateName

Name of custom template with full directory path if


templateIn is set to swDwgTemplateCustom.

Input:

Width

Paper width if templateIn is set to swDwgTemplateNone


or swDwgPapersUserDefined.

Input:

Height

Paper height if templateIn is set to


swDwgTemplateNone or swDwgPapersUserDefined.

Input:

PropertyViewName

Name of the view containing the model to get custom


property values from.

164

if successful, FALSE if not.

for first angle projection, FALSE otherwise.

Case Study: Automating Drawing Creation

API Fundamentals

Lesson 6
Drawing Automation

Add new variables.

Add some more variables that are used for creating the new sheets on
the drawing.
Const TemplateName As String = C:\SolidWorks 2006 Training
Files\API Fundamentals\Templates\APIDrawing.drwdot
Const TemplateSize As Long = swConst.swDwgTemplateA1size
Const PaperSize As Long = swConst.swDwgPaperA1size
Const ScaleNum As Double = 1#
Const ScaleDenom As Double = 2#
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

Add the code to create the new drawing sheets.


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

10 Run the code and examine the drawing.

Notice that new tabs are created for each new drawing sheet.
Close the drawing without saving it.

Case Study: Automating Drawing Creation

165

Lesson 6

API Fundamentals

Drawing Automation

Creating Views

Call DrawingDoc::Create1st/3rdAngleViews2 to insert standard


orthographic views (first or third angle projection).

DrawingDoc::Create1stAngleViews2
retval = DrawingDoc.Create1stAngleViews2 (modelName)

DrawingDoc::Create3rdAngleViews2
retval = DrawingDoc.Create3rdAngleViews2 (modelName)

Return:

retval

TRUE

Input:

modelName

Name of the document to create views from.

Tip

if successful, FALSE if not.

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.
11 Insert standard views.

Add the code to create the drawing views.


Run the macro.
Examine the drawing views and then close it when finished.
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

166

Case Study: Automating Drawing Creation

API Fundamentals

Lesson 6
Drawing Automation

Running the macro produces the projection views automatically.

Inserting
Annotations

Call DrawingDoc::InsertModelAnnotations to insert model dimensions


and annotations from the underlying model document.

DrawingDoc::InsertModelAnnotations3
retval = DrawingDoc.InsertModelAnnotations (option,types, allviews, duplicateDims,
hiddenFeatureDims, usePlacementInSketch)

Return:

Variant

VARIANT of type SafeArray of inserted Annotation


objects

Input:

option

0 = All dimensions in the view


1 = All dimensions of the currently selected
component (for assembly drawings)
2 = All dimensions of the currently selected
feature

Input

types

use values from swInsertAnnotations_e

Input:

allViews

TRUE = inserts the annotations for all views in


the drawing
FALSE = inserts annotation only in the selected
view

Input:

duplicateDims

TRUE to insert duplicate dimensions, FALSE to


eliminate duplicate dimensions

Input

hiddenFeatureDims

TRUE to insert dimensions from features that are


hidden, FALSE to not insert dimensions from
features that are hidden

Input

usePlacementInSketch

TRUE to insert dimensions as they were placed in


sketch, FALSE to not

Input

Case Study: Automating Drawing Creation

167

Lesson 6

API Fundamentals

Drawing Automation

12 Insert dimensions and notes.

Add the code to insert the dimensions and annotations from the
underlying assembly model.
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

Running the macro inserts the annotations automatically.

168

Case Study: Automating Drawing Creation

API Fundamentals

Lesson 6
Drawing Automation

Traversing
Drawing Views

Use the methods DrawingDoc::GetFirstView and View::GetNextView


to traverse all the views on a drawing sheet. To do the traversal, use
these methods in a While Loop statement and test the validity of the
view pointer. When the view pointer returned back from the
View::GetNextView method is set to Nothing, the loop exits. The code
in the following step demonstrates how to accomplish the view
traversal on the drawing document.
13 Traverse views and set configurations.
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

Case Study: Automating Drawing Creation

169

Lesson 6

API Fundamentals

Drawing Automation

Saving Drawings
in Different
Formats

Another feature in this program is to save each drawing sheet in other


file formats. Often it is necessary to send drawings to other systems for
printing and viewing purposes. The ModelDoc2::SaveAs4 method is
used to save the drawings in other file formats.

ModelDoc2::SaveAs4
retval = DrawingDoc.InsertModelAnnotations (Name, Version, Options, &Errors,
&Warnings )

Return:

retval

TRUE if the save is successful, FALSE if not

Input:

Name

New name of the document. The file extension


indicates any conversion that should be
performed (for example, Part1.igs to save to
IGES)

Input

Version

Format in which to save this document as defined


in swSaveAsVersion_e

Input

Options

Option indicating how to save the document as


defined in swSaveAsOptions_e

Output

Errors

Errors that caused the save to fail as defined


in swFileSaveError_e

Output

Warnings

Warnings or extra information generated during


the save operation as defined in
swFileSaveWarning_e

Note

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.
14 Declare the output parameters and export path name.

Navigate to the variable declarations and add the following code.


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

Const SaveAsPath As String = _


"C:\SolidWorks 2006 Training Files\API Fundamentals\Export\"
Dim errors As Long
Dim warnings As Long

170

Case Study: Automating Drawing Creation

API Fundamentals

Lesson 6
Drawing Automation

15 Save the drawing sheets in different file formats.

Add the following code to export the drawings.


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

16 Save and run macro.

Return to VBA when finished. Examine the drawing sheets.


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.

Case Study: Automating Drawing Creation

171

Lesson 6

API Fundamentals

Drawing Automation

Drawing Commands
Create1stAngleViews
Create3rdAngleViews

CreateAuxiliaryViewAt3

CreateDetailViewAt3

CreateBreakoutSection

CreateSectionView

UpdateViewDisplayGeometry

CreateSectionViewAt4

InsertHatchedFace

CreateDrawViewFromModelView

Annotation Commands
CreateText2
InsertNote

InsertCenterMark2

InsertSurfaceFinishSymbol2

InsertCenterLine

NewGtol

AddHoleCallout2

InsertBOMBalloon2

InsertCosmeticThread
ShowCosmeticThread
HideCosmeticThread

InsertDatumTargetSymbol

InsertStackedBalloon

InsertWeldSymbol

InsertMultiJogLeader

InsertBlock

InsertDowelSymbol

InsertModelAnnotations
InsertModelDimensions

Layer Commands
CreateLayer
ChangeComponentLayer
SetCurrentLayer

Line Format Commands


SetLineColor

HideEdge

SetLineWidth

ShowEdge

SetLineStyle

172

Case Study: Automating Drawing Creation

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.
The macro should insert
1st or 3rd angle views
based on configurations,
add dimensions and
notes to the views, add a
shaded isometric view,
and repeat the process with additional sheets per each configuration.
Optional challenge #1: Try to rename the default sheet (Sheet1) with
the first configuration (Cut) before adding more sheets.
Optional challenge #2: Try to save each sheet to the following files:
.dxf, .dwg, .jpg and .tif

Skills Learned

APIs Used

Automating drawing and annotation commands.

Working with multiple configurations in drawing views.

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

Const TemplateName As String = "C:\SolidWorks 2006 Training


Files\API Fundamentals\Templates\APIDrawing.drwdot"
Const TemplateSize As Long = swConst.swDwgTemplateBsize
Const PaperSize As Long = swConst.swDwgPaperBsize
Const ScaleNum As Double = 1#
Const ScaleDenom As Double = 2#
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
Dim isFirstSheet As Boolean
isFirstSheet = True
For i = 0 To UBound(ConfigNamesArray)
ConfigName = ConfigNamesArray(i)
If isFirstSheet = True Then
swDraw.ActivateSheet "Sheet1"
Dim swSheet As Sheet
Set swSheet = swDraw.GetCurrentSheet
swSheet.SetName ConfigName
Else
retval = swDraw.NewSheet3(ConfigName, TemplateSize, _
PaperSize, ScaleNum, ScaleDenom, Not ThirdAngle, "", _
0#, 0#, "")
End If
isFirstSheet = False
If ThirdAngle = True Then
retval = swDraw.Create3rdAngleViews2(swModel.GetPathName)
Else
retval = swDraw.Create1stAngleViews2(swModel.GetPathName)
End If
swDraw.CreateDrawViewFromModelView swModel.GetPathName, _
"*Isometric", 0.2635088599471, 0.1934578136726, 0
swDraw.ViewDisplayShaded
retval = swDraw.InsertModelAnnotations(0, False, _
swConst.swInsertDimensions + swConst.swInsertNotes, _
True)

174

API Fundamentals

Exercise 10:
Drawing Automation

Set swView = swDraw.GetFirstView


Do While Not swView Is Nothing
swView.ReferencedConfiguration = ConfigName
Set swView = swView.GetNextView
Loop
swDraw.ForceRebuild
Const SaveAsPath As String = "C:\SolidWorks 2006 Training _
Files\API Fundamentals\"
swDraw.SaveAs4 SaveAsPath
errors, warnings
swDraw.SaveAs4 SaveAsPath
errors, warnings
swDraw.SaveAs4 SaveAsPath
errors, warnings
swDraw.SaveAs4 SaveAsPath
errors, warnings
Next i
End Sub

& ConfigName & ".DXF", 0, 0, _


& ConfigName & ".DWG", 0, 0, _
& ConfigName & ".JPG", 0, 0, _
& ConfigName & ".TIF", 0, 0, _

175

Exercise 10:
Drawing Automation

176

API Fundamentals

API Fundamentals

Lesson 7
Selection and Traversal
Techniques

Upon successful completion of this lesson you will be able to:


I

Programmatically select objects.

Access selected objects using the SelectionManager.

Determine the type of a selected feature.

Extract and modify feature data.

Traverse features.

Traverse geometry.

Suppress features and set feature visibility.

Select features at a known FeatureManager position.

177

Lesson 7
Selection and Traversal Techniques

178

API Fundamentals

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.
It requires that the
user selects the
Extrude1 feature
before running the
macro.

Open existing part and macro.

Open the part Preselection.sldprt and the macro


Preselection.swp.
2

Add code to the Generate button.

Add the following code


Private Sub cmdGenerate_Click()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
End Sub

Case Study: Programming With a Selected Object

179

Lesson 7

API Fundamentals

Selection and Traversal Techniques

SelectionManager

The SelectionManager is an object interface that is dedicated to


managing selected objects in the SolidWorks user interface. Every
document created in SolidWorks has its own SelectionManager
property that is accessible using the API. Anything that is selected in a
document is temporarily stored in the SelectionManager. The selected
object remains there until it is un-selected or when a rebuild occurs.
The SelectionManager is a 1 based collection. The first available index
is 1, not 0. The SelectionManager also exposes methods and properties
that allow the programmer to access objects at any index. The
programmer can then return the object pointer at a specific index and
call methods or properties on that object.

Accessing the
Selection Manager

To get an interface pointer to the SelectionManager object, you would


use the ModelDoc2::SelectionManager property:
Dim SelMgr as SldWorks.SelectionMgr
Set SelMgr = ModelDoc2.SelectionManager.

ModelDoc2::SelectionManager
SelectionMgr = ModelDoc2.SelectionManager

Output:

SelectionMgr

Counting Selected
Objects

Pointer a Dispatch object, the SelectionMgr object for


this document

To determine the number of selected objects, use


SelectionMgr::GetSelectedObjectCount.

SelectionMgr::GetSelectedObjectCount
retval = SelectionMgr.GetSelectedObjectCount ( )

Return:

retval

Number of currently selected objects.

Add the following code.

Connect to the Selection Manager and return the object count.


Private Sub cmdGenerate_Click()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swSelMgr As SldWorks.SelectionMgr
Dim count As long
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
End Sub

180

Case Study: Programming With a Selected Object

API Fundamentals

Lesson 7
Selection and Traversal Techniques

Accessing
Selected Objects

To get an interface pointer to a currently selected object use


SelectionMgr::GetSelectedObject5.

SelectionMgr::GetSelectedObject5
retval = SelectionMgr.GetSelectedObject5 (AtIndex)

Return:

retval

Pointer a dispatch object.

Input:

AtIndex

Index position within the current list of selected items


where AtIndex ranges:From 1 To
SelectionMgr::GetSelectObjectCount

Getting Selected
Object Types

To determine the selected object type use


SelectionMgr::GetSelectedObjectType2.

SelectionMgr::GetSelectedObjectType2
retval = SelectionMgr.GetSelectedObjectType2 (AtIndex)

Note: If the object returned is a feature, use Feature::GetTypeName for determining the feature
type.
Return:

retval

Object type. See API Help file for full list.

Input:

AtIndex

Index position within the current list of selected items


where AtIndex ranges:From 1 To
SelectionMgr::GetSelectObjectCount

Getting Feature
Type Names

To verify that a specific feature is selected use Feature::GetTypeName.

Feature::GetTypeName
retval = Feature.GetTypeName ( )

Return:

retval

Feature type. See API Help file for full list.

Declare a feature variable.

Add the variable in the button click event.


Private Sub cmdGenerate_Click()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swSelMgr As SldWorks.SelectionMgr
Dim count As long
Dim Feature As SldWorks.Feature
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swSelMgr = swModel.SelectionManager
count = swSelMgr.GetSelectedObjectCount

Case Study: Programming With a Selected Object

181

Lesson 7

API Fundamentals

Selection and Traversal Techniques

Return a pointer to the selected feature.

Scroll down and add the following code:


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 = Extrusion Then
swApp.SendMsgToUser "Please select only Extrude1."
Exit Sub
End If
End Sub

Feature Data
Objects

Every feature in the SolidWorks FeatureManager design tree has a


corresponding FeatureData object available in the API. The Feature
object represents the interface that exposes methods and properties
available for all features. The FeatureData object is the more specific
object that exposes the functionality of each specific feature type.

Accessing the
Feature Data
Object

To return a pointer to the FeatureData object from a Feature object use


the method Feature::GetDefinition.

Feature::GetDefinition
retval = Feature.GetDefintion ( )

Return:

retval

Accessing
Selections

Dispatch pointer to the feature definition object. See


API Help file for full list of feature objects.
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

if the selections were accessed successfully,


if not.

FALSE

Input:

TopDoc

Top-level document.

Input:

Component

Component in which the feature is to be modified.

182

Case Study: Programming With a Selected Object

API Fundamentals

Lesson 7
Selection and Traversal Techniques

Releasing
Selections

When using AccessSelections, the program must also make a


corresponding call to ExtrudeFeatureData2::ReleaseSelectionAccess
to restore the rollback state for cases when a feature is not modified.
This method is only needed if the features data is not modified.
If the FeatureData objects data is modified, another method is used to
regenerate the feature with the new data. This method,
Feature::ModifyDefinition, will be explained shortly.

ExtrudeFeatureData2::ReleaseSelectionAccess
void ExtrudeFeatureData2.ReleaseSelectionAccess ( )

Return:

void

No return value.

Connect to a FeatureData object.

Add the following code to connect to the ExtrudeFeatureData object.


Private Sub cmdGenerate_Click()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swSelMgr As SldWorks.SelectionMgr
Dim count As long
Dim Feature As SldWorks.Feature
Dim ExtrudeFeatureData As Sldworks.ExtrudeFeatureData2
Dim retval As Boolean
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swSelMgr = swModel.SelectionManager
count = swSelMgr.GetSelectedObjectCount
If count > 1 Then
swApp.SendMsgToUser "Please select only Extrude1."
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
End Sub

Modifying Feature
Data Properties

One of the modifications for an extruded feature is setting the depth.


First call ExtrudeFeatureData2::GetDepth to retrieve the existing
depth value and then call ExtrudeFeatureData2::SetDepth to set a new
value.

Case Study: Programming With a Selected Object

183

Lesson 7

API Fundamentals

Selection and Traversal Techniques

Modify the Object


Definition

Finally, call Feature::ModifyDefinition to implement changes.

Feature::ModifyDefinition
retval = Feature.ModifyDefinition (Definition, TopDoc, Component)

Return:

retval

TRUE

if the feature is updated successfully, FALSE if

not.
Input:

Definition

Dispatch pointer to the feature definition object.

Input:

TopDoc

Top-level document.

Input:

Component

Component for the feature.

Modify extrude depth.

Add the following code entries to modify the depth of the extruded
feature.
Private Sub cmdGenerate_Click()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swSelMgr As SldWorks.SelectionMgr
Dim count As long
Dim Feature As SldWorks.Feature
Dim ExtrudeFeatureData As SldWorks.ExtrudeFeatureData2
Dim retval As Boolean
Dim Depth As Double
Dim Factor As Integer
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

184

Case Study: Programming With a Selected Object

API Fundamentals

Lesson 7
Selection and Traversal Techniques

Save and run the macro.

Select the Extrude1


feature from the
FeatureManager and
run the macro.
Enter 5 in the
multiplication factor
text box and click the
Generate button.
Click it again and
notice how the length
of the extrusion keeps
getting larger. Return
to VBA when
finished.

The SolidWorks
BREP Model

In order to traverse geometry in SolidWorks, a programmer should


understand the boundary representation (BREP) model that SolidWorks
uses and how the API represents these objects. Two object types are
used to represent the BREP model in the SolidWorks API.
I
I

Topology objects expose members that are used to manipulate the


boundaries of all the geometry in the model.
Geometry objects expose members that are used to manipulate the
actual data that define the geometrical shape that the topology
surrounds.

Highest Level Object

Lowest Level Object

The SolidWorks BREP Model

185

Lesson 7

API Fundamentals

Selection and Traversal Techniques

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.
Traversing
Topology and
Geometry

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.

186

The SolidWorks BREP Model

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
I
I
I

Selecting all types of faces (cylindrical, planar, etc.) on a body.


Finding faces for adding mates.
Finding edge, curve, and point information on faces.
Automating multiple face modifications.
Adding attributes to faces.

Open an existing part and create a new macro.

Open the part BodyFaceTraversal.sldprt.


Click
2

and name the macro BodyFaceTraversal.swp.

Add code to Sub Main.

Connect to SolidWorks and the active document.


Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Sub main()
Set swApp = Application.SldWorks
If Not swApp Is Nothing Then
Set swModel = swApp.ActiveDoc
If Not swModel Is Nothing Then
End If
Set swModel = Nothing
End If
Set swApp = Nothing
End Sub

Case Study: Body and Face Traversal

187

Lesson 7

API Fundamentals

Selection and Traversal Techniques

Connect to the part document interface.

Although this explicit type cast is not necessary, it is done here to


enable the IntelliSense on the PartDoc pointer.
Dim swPart As SldWorks.PartDoc
Sub main()
Set swApp = Application.SldWorks
If Not swApp Is Nothing Then
Set swModel = swApp.ActiveDoc
If Not swModel Is Nothing Then
'Notice the Explicit Type Casting
Set swPart = swModel
If Not swPart Is Nothing Then
End If
Set swPart = Nothing
End If
Set swModel = Nothing
End If
Set swApp = Nothing
End Sub

Returning a List of
Body Pointers

PartDoc::GetBodies2 returns an array of all of the bodies in a part


document. A loop can be used to traverse this returned list of bodies.

PartDoc::GetBodies2
retval = PartDoc.GetBodies2 (BodyType, VisibleOnly)

Return:

retval

SafeArray of dispatch pointers to the bodies.

Input:

BodyType

swSolidBody - solid body


swSheetBody - sheet body
swWireBody - wire body
swMinimumBody - point body
swGeneralBody - general, non-manifold body
swEmptyBody - NULL body
swAllBodies - all solid bodies

Input:

VisibleOnly

gets only the visible bodies, FALSE gets all of the


bodies in the part.

188

TRUE

Case Study: Body and Face Traversal

API Fundamentals

Lesson 7
Selection and Traversal Techniques

Return the array body object pointers.


Dim
Dim
Dim
Dim

swApp As SldWorks.SldWorks
swModel As SldWorks.ModelDoc2
swPart As SldWorks.PartDoc
retval As Variant

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

Declare an indexer and a face pointer.


Dim
Dim
Dim
Dim
Dim
Dim

swApp As SldWorks.SldWorks
swModel As SldWorks.ModelDoc2
swPart As SldWorks.PartDoc
retval As Variant
i As Integer
swFace As SldWorks.face2

Program a loop to traverse the faces.


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

Case Study: Body and Face Traversal

189

Lesson 7

API Fundamentals

Selection and Traversal Techniques

Face Material
Properties

Use the property Face2::MaterialPropertyValues to get or set material


properties for a face.
Material properties are the colors and visual properties of a face. These
properties can be overridden on every face in a model.

Face2::MaterialPropertyValues
MaterialPropertyValues = Face2.MaterialPropertyValues Gets property
Face2.MaterialPropertyValues = MaterialPropertyValues Sets property

Output:

MaterialPropertyValues

SafeArray of material values on a face. The format of


the return values is an array of doubles as follows:
MaterialPropertyValues(0)
MaterialPropertyValues(1)
MaterialPropertyValues(2)
MaterialPropertyValues(3)
MaterialPropertyValues(4)
MaterialPropertyValues(5)
MaterialPropertyValues(6)
MaterialPropertyValues(7)
MaterialPropertyValues(8)

Red
Green
Blue
Ambient
Diffuse
Specular
Shininess
Transparency
Emission

Declare an array to hold face material properties.


Dim
Dim
Dim
Dim
Dim
Dim
Dim

190

swApp As SldWorks.SldWorks
swModel As SldWorks.ModelDoc2
swPart As SldWorks.PartDoc
retval As Variant
i As Integer
swFace As SldWorks.face2
matProps(8) As Double

Case Study: Body and Face Traversal

API Fundamentals

Lesson 7
Selection and Traversal Techniques

Set up an array of material properties.

Then add the code to pass the array to the current face.
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!

Traverse remaining faces.


Do While Not swFace Is Nothing
swFace.MaterialPropertyValues = ((matProps))
swModel.GraphicsRedraw2
Set swFace = swFace.GetNextFace
Loop
Next i
End If
Set swPart = Nothing
End If
Set swModel = Nothing
End If
Set swApp = Nothing
End Sub

10 Save and run macro.

Return to VBA when finished.

Case Study: Body and Face Traversal

191

Lesson 7

API Fundamentals

Selection and Traversal Techniques

Case Study:
Feature
Manager
Traversal

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.

Open existing part and macro.

Open the part FeatMgrTraversal.sldprt and the macro


FeatMgrTraversal.swp.

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

Pointer to dispatch object for the 1st feature in the


document.

Case Study: Feature Manager Traversal

API Fundamentals

Lesson 7
Selection and Traversal Techniques

Consecutive calls to Feature::GetNextFeature in this loop would


continue the traversal
Feature:GetNextFeature
retval = Feature.GetNextFeature ( )

Return:

retval

Dispatch pointer to the next feature.

Add the feature traversal code.


Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swFeature As SldWorks.feature
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

Displaying Feature
Names and Types

The property Feature::Name is used to retrieve the screen name of the


feature. Use Feature::GetTypeName to return the underlying data type
name of the feature.

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.
3

Retrieve and display feature information.

Declare some variables to store a feature name and type.


Dim
Dim
Dim
Dim
Dim

swApp As SldWorks.SldWorks
swModel As SldWorks.ModelDoc2
swFeature As SldWorks.feature
FeatName As String
FeatType As String

Case Study: Feature Manager Traversal

193

Lesson 7

API Fundamentals

Selection and Traversal Techniques

Return the feature name and type to the user.


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

Save and run the macro.

Return to VBA when finished.

Note

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.

Setting Feature
Suppression

Call Feature::SetSuppression to suppress or un-suppress features.

Feature::SetSuppression
suppressSet = Feature.SetSuppression (suppressState)

Return:

suppressSet

TRUE

if the suppression state was successfully set,


if not.

FALSE

Input:

194

suppressState

swSuppressFeature
swUnSuppressFeature
swUnSuppressDependent

Case Study: Feature Manager Traversal

API Fundamentals

Lesson 7
Selection and Traversal Techniques

Add code to suppress features.

This code suppresses all of the fillet features in the FeatureManager.


Use an apostrophe to comment the MsgBox function call to eliminate
the repetitive dialog from appearing.
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swFeature As SldWorks.feature
Dim FeatName As String
Dim FeatType As String
Dim swSubFeature As SldWorks.feature
Dim SubFeatName As String
Dim 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
FeatName = swFeature.Name
FeatType = swFeature.GetTypeName
If FeatType = "Fillet" Then
Dim suppressSet As Boolean
Dim suppressState As Long
suppressSet = swFeature.SetSuppression_
(swConst.swSuppressFeature)
End If
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

Save and run macro.

Return to VBA when finished.

Case Study: Feature Manager Traversal

195

Lesson 7

API Fundamentals

Selection and Traversal Techniques

Setting Feature UI
State

Call Feature::SetUIState to control the visibility of the features in the


FeatureManager.

Feature::SetUIState
Feature.SetUIState (StateType, Flag)

Input:

StateType

swIsHiddenInFeatureMgr

Input:

Flag

TRUE hides the display of the feature in the


FeatureManager design tree, FALSE otherwise.

Hide all features.

Edit the code to hide all of the features in the FeatureManager design
tree.
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

Save and run macro.

Return to VBA when finished.


10 Show all features.

Change the parameter for Feature::SetUIState to False and replay


macro.
Note

196

The Undo command will not work for UI settings.

Case Study: Feature Manager Traversal

API Fundamentals

Lesson 7
Selection and Traversal Techniques

Obtaining a
Feature by
FeatureManager
Position

To obtain a feature from a specific location in the FeatureManager, call


ModelDoc2::FeatureByPositionReverse. This method starts counting
from the last feature in the Feature Manager and walks upwards to
get the feature at the index you pass to it.

ModelDoc2::FeatureByPositionReverse
retval = ModelDoc2.FeatureByPositionReverse (PositionFromEnd)

Return:

retval

Pointer to dispatch object for the nth from last feature


in the document.

Input:

PositionFromEnd

The feature position number from the last feature. 0

gives the last feature

11 Modify code.

Remove the feature traversal code, and substitute the call to


ModelDoc2::FeatureByPositionReverse.
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

12 Save and run macro.


13 Exit macro.

Case Study: Feature Manager Traversal

197

Lesson 7

API Fundamentals

Selection and Traversal Techniques

198

Case Study: Feature Manager Traversal

API Fundamentals

Exercise 11:
Handling Preselection 1

Exercise 11:
Handling
Preselection 1

Objective

Learn how to access the SelectionManager and retrieve selected object


types. This example calculates the distance between two parallel faces,
so the macro must compare what the user selects to what SolidWorks
recognizes as a face.

Skills Learned

Handling selected object types.

Handling two face selections at one time.

APIs Used

ModelDoc2.SelectionManager
SelectionMgr.GetSelectedObjectType2
SelectionMgr.GetSelectedObject5
Face2.GetSurface

Procedure

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

Const ParallelDistTolerance As Double = 0.0001


Function Sq(Num As Double) As Double
Sq = Num * Num
End Function
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
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swSelMgr = swModel.SelectionManager
SelType1 = swSelMgr.GetSelectedObjectType2(1)
SelType2 = swSelMgr.GetSelectedObjectType2(2)
If SelType1 <> swSelFACES Or SelType2 <> swSelFACES Then
Exit Sub
End If
Set swFace1 = swSelMgr.GetSelectedObject5(1)
Set swFace2 = swSelMgr.GetSelectedObject5(2)
Set swSurf1 = swFace1.GetSurface
Set swSurf2 = swFace2.GetSurface
varSelPt1 = swSelMgr.GetSelectionPoint(1)
varSelPt2 = swSelMgr.GetSelectionPoint(2)
varClosePt1 = swSurf1.GetClosestPointOn(varSelPt2(0), _
varSelPt2(1), varSelPt2(2))
varClosePt2 = swSurf2.GetClosestPointOn(varSelPt1(0), _
varSelPt1(1), varSelPt1(2))
Dist1 = Sqr(Sq(varSelPt1(0) - varClosePt2(0)) + _
Sq(varSelPt1(1) - varClosePt2(1)) + Sq(varSelPt1(2) - _
varClosePt2(2)))
Dist2 = Sqr(Sq(varSelPt2(0) - varClosePt1(0)) + _
Sq(varSelPt2(1) - varClosePt1(1)) + Sq(varSelPt2(2) - _
varClosePt1(2)))
If Abs(Dist1 - Dist2) <= ParallelDistTolerance Then
swApp.SendMsgToUser "Distance = " + _
Str(Round(Dist1 * 1000, 2)) + " mm"
Else
swApp.SendMsgToUser "Faces not parallel"
End If
End Sub

200

API Fundamentals

Exercise 12:
Handling Preselection 2

Exercise 12:
Handling
Preselection 2

Objective

To access the SelectionManager, count the number of selected objects,


retrieve the selected object types (edges) and get the underlying curve
information for each. This example displays the overall length of
multiple, preselected edges.

Skills Learned

Handling selected object types.

Handling more than one selected object by using a selection count.

APIs Used

ModelDoc2.SelectionManager
SelectionMgr.GetSelectedObjectCount
SelectionMgr.GetSelectedObjectType2
SelectionMgr.GetSelectedObject5
Edge.GetCurve

Procedure

1.
2.
3.
4.

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

Solution

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
Set swApp = CreateObject("SldWorks.Application")
Set swModel = swApp.ActiveDoc
Set swSelMgr = swModel.SelectionManager
SelCount = swSelMgr.GetSelectedObjectCount
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
swApp.SendMsgToUser "Length = " + _
Str(Round(Length * 1000, 2)) + " mm"
End Sub

202

API Fundamentals

Exercise 13:
Traversing the FeatureManager

Exercise 13:
Traversing the
FeatureManager

Objective

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

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

Traversing the FeatureManager

Solution

Const MinRadius = 0.005


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
Set swApp = Application.SldWorks
Set swPart = swApp.ActiveDoc
Set swFeat = swPart.FirstFeature
swPart.ClearSelection
Do While Not swFeat Is Nothing
FeatTypeName = swFeat.GetTypeName
If FeatTypeName = "Fillet" Then
Set FilletData = swFeat.GetDefinition
Radius = FilletData.DefaultRadius
If Radius <= MinRadius Then
retval = swFeat.Select(True)
End If
FilletCount = FilletData.FilletItemsCount
If FilletCount > 0 Then
retval = FilletData.AccessSelections(swPart, Nothing)
For i = 0 To FilletCount - 1
Set FilletItem = FilletData.GetFilletItemAtIndex(i)
Radius = FilletData.GetRadius(FilletItem)
If Radius <= MinRadius Then
SelFeat = True
Exit For
End If
Next i
FilletData.ReleaseSelectionAccess
If SelFeat = True Then
SelFeat = False
retval = swFeat.Select(True)
End If
End If
End If
Set swFeat = swFeat.GetNextFeature
Loop
End Sub

204

API Fundamentals

Lesson 8
Adding Custom Properties
and Attributes

Upon successful completion of this lesson you will be able to:


I

Add custom properties and summary information to a SolidWorks


model document.

Retrieve and modify existing custom properties values.

Create, define and register attribute definitions.

Add document attributes to a file.

Add face attributes to a model.

Traverse attributes on the model to set or get their parameters.

205

Lesson 8
Adding Custom Properties and Attributes

206

API Fundamentals

API Fundamentals

Lesson 8
Adding Custom Properties and Attributes

Case Study:
Custom
Properties

Custom Properties are user-defined pieces of information that are


stored on SolidWorks model documents. To display the custom
properties for any SolidWorks document, click File, Properties..., and
click the Custom tab. A list of custom properties is displayed. This
case study demonstrates how to programatically add and return custom
property values on a SolidWorks model document. The diagram below
shows the custom property dialog with one custom property added.

Open a new part and create a new macro.


Click the New Macro
button on the Macro toolbar.

Name the macro CustomProps.swp.


2

Early bind to SolidWorks and connect to the active document.

Add the following lines of programming code:


Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
End Sub

Case Study: Custom Properties

207

Lesson 8

API Fundamentals

Adding Custom Properties and Attributes

Adding Custom
Properties to a
SolidWorks
Document

Use the ModelDoc2::AddCustomInfo3 method to add custom property


information to the document or to the specified configuration.

ModelDoc2::AddCustomInfo3
retval = ModelDoc2.AddCustomInfo3 (Configuration, FieldName, FieldType, FieldValue)

Return:

retval

TRUE

Input:

Configuration

Name of the configuration.

Input:

FieldName

Name of custom property.

Input:

FieldType

swCustomInfoUnknown
swCustomInfoText
swCustomInfoDate
swCustomInfoNumber
swCustomInfoYesOrNo

Input:

FieldValue

Value of custom property.

if added, FALSE if not.

Add code to create a custom property.


Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
swModel.AddCustomInfo3 , MyTest, swCustomInfoText, _
This is a test.
End Sub

Save and run the macro.


In SolidWorks, click File, Properties.... Click the Custom tab.

The property list displays the new property name, type and value.
Close this dialog and return to editing the macro in VBA.

208

Case Study: Custom Properties

API Fundamentals

Lesson 8
Adding Custom Properties and Attributes

Setting and
Getting Custom
Property Values

Use the ModelDoc2::CustomInfo2 method to get and set custom


property information for the document.

ModelDoc2::CustomInfo2
value = ModelDoc2.CustomInfo2 (Configuration, FieldName) Gets custom info
ModelDoc2.CustomInfo2 (Configuration, FieldName) = value Sets custom info

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

Text in the field.

Input:

Configuration

Name of the configuration.

Input:

FieldName

Name of custom property.

Add code to return the custom property value to the user.


Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim value As String
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

Save and run macro.

The custom information is returned, modified, and returned again to the


user. Return to VBA when finished.

Original Setting

Case Study: Custom Properties

Modified Setting

209

Lesson 8

API Fundamentals

Adding Custom Properties and Attributes

Getting Custom
Property Names

Use the ModelDoc2::GetCustomInfoNames2 method to return the


name list of the custom properties defined on the document.

ModelDoc2::GetCustomInfoNames2
retval = ModelDoc2.GetCustomInfoNames2 (Configuration)

Return:

retval

Safearray containing an array of string values of the


custom property names.

Input:

Configuration

Name of the configuration.

Getting the
Custom Property
Count

Use the ModelDoc2::GetCustomInfoCount2 method to return the


number of custom properties that have been added to the document.

ModelDoc2::GetCustomInfoCount2
count = ModelDoc2.GetCustomInfoCount2 (Configuration)

Output:

count

Number of custom information fields.

Input:

Configuration

Name of the configuration.

Modify code.

Change the code to add multiple properties and then return their names
to the user.
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
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"

Dim retval() As String


Dim i As Integer
retval = swModel.GetCustomInfoNames2("")
For i = 0 To UBound(retval)
swApp.SendMsgToUser2 retval(i), 0, 0
Next
Dim count As Long
count = swModel.GetCustomInfoCount2("")
swApp.SendMsgToUser2 _
You have & count & custom properties., 0, 0
End Sub

210

Case Study: Custom Properties

API Fundamentals

Lesson 8
Adding Custom Properties and Attributes

Save and run the macro.

Check the added custom properties.


Exit the macro and return to VBA when finished.

Case Study:
Configurations
With Custom
Properties

In SolidWorks, custom properties can be added to specific


configurations of the model. This next program will demonstrate how
to add configuration specific custom properties using the SolidWorks
API.
The pseudo code for this macro is as follows:
I
I
I

Connect to the model and traverse the configurations.


Activate each configuration and return the mass properties of the
model.
Create configuration specific custom properties that store the
density, mass, volume and area on the active configuration.

After running the macro, a user can examine the configuration specific
custom properties as shown in the diagram above.
Note

Because the geometry of the model is different for each configuration,


the values of the properties will also be different for each configuration.

Case Study: Configurations With Custom Properties

211

Lesson 8

API Fundamentals

Adding Custom Properties and Attributes

Open part.

Open the file CustomProperties.sldprt. It has three


configurations.

Open macro.

Open the file CustomPropsConfig.swp and review code.


The code returns the list of configuration names and displays them to
the user.
3

Run macro to display the configuration names.

Return to VBA when finished.


4

Modify the units, density and hatch pattern.

In the loop for traversing the configuration names, comment the


SendMsgToUser2 method, and add the following code.
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
retval = swModel.GetConfigurationNames()
For i = 0 To UBound(retval)
swApp.SendMsgToUser2 retval(i), 0, 0
swModel.ShowConfiguration2 retval(i)
swModel.SetUserPreferenceIntegerValue _
swConst.swUnitsLinear, swConst.swCM
Dim density As Double
density = 2700
swModel.SetUserPreferenceDoubleValue _
swConst.swMaterialPropertyDensity, density
swModel.SetUserPreferenceStringValue _
swConst.swMaterialPropertyCrosshatchPattern, _
"ISO (Aluminum)"

212

Case Study: Configurations With Custom

API Fundamentals

Lesson 8
Adding Custom Properties and Attributes

Returning Mass
Properties From a
SolidWorks Model

The macro will now be programmed to return a list of the mass


properties from the model. In the SolidWorks user interface, this
information can be returned to the user by clicking on
Tools, Mass Properties... from the menu.

Using the API to


Return the Mass
Properties

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
retval = ModelDocExtension.GetMassProperties ( Accuracy, status )

Output

retval

SafeArray of size 13; the last element is the accuracy


at which returned mass properties are calculated

Input

Accuracy

0 = as is
1 = default
2 = maximum

Output:

status

Status of the mass property results as defined in


swMassPropertiesStatus_e

Case Study: Configurations With Custom Properties

213

Lesson 8

API Fundamentals

Adding Custom Properties and Attributes

Returning the mass properties from the model.

Add the following code to return the mass properties from the model
and store them in configuration specific custom properties.
Dim density As Double
density = 2700
swModel.SetUserPreferenceDoubleValue _
SwConst.swMaterialPropertyDensity, density
swModel.SetUserPreferenceStringValue _
SwConst.swMaterialPropertyCrosshatchPattern, _
"ISO (Aluminum)"
Dim massprops As Variant
Dim status As Long
massprops = swModel.Extension.GetMassProperties(1, status)
swModel.AddCustomInfo3 retval(i), _
"Density - " & retval(i), _
swConst.swCustomInfoText, _
Format(density / 1000, "###0.000000")
swModel.AddCustomInfo3 retval(i), _
"Mass - " & retval(i), _
swConst.swCustomInfoText, _
Format(massprops(5) * 1000, "###0.000000")
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

Note

214

The intrinsic VBA Format function is used to format the precise


numbers returned from the mass properties method. They are formatted
with a specific number of places on either side of the decimal point. For
more information look up the Format function in Microsoft Visual
Basic Help.

Case Study: Configurations With Custom

API Fundamentals

Lesson 8
Adding Custom Properties and Attributes

Save and run the macro.

Check the custom properties of each configuration against the system


results for mass properties. They will match.
Configuration: 2 Hole
Density:

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
Volume:

35.47 cm3

Area:

404.51 cm2

Case Study: Configurations With Custom Properties

215

Lesson 8

API Fundamentals

Adding Custom Properties and Attributes

Case Study:
File Summary
Information

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

Call the ModelDoc2::SummaryInfo method to get or set custom file


summary information for a SolidWorks document.

ModelDoc2::SummaryInfo
value = ModelDoc2.SummaryInfo (FieldId) Gets property.
ModelDoc2.SummaryInfo (FieldId) = value Set property.

Return:

value

Text in the field.

Input:

FieldId

Identifier for field as defined in swSummInfoField_e

Review the code for the macro.

Open the macro named CustomFileSummary.swp.


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)
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

Case Study: File Summary Information

API Fundamentals

Lesson 8
Adding Custom Properties and Attributes

Run the macro and examine the results.

The Summary Information tab reflects the changes made by the macro.

Case Study:
Document
Attributes

An Attribute is a user defined container of


custom variables a programmer can store
on a SolidWorks model. The custom
variables are called the attributes
parameters.
Unlike custom properties, attributes are not
stored on the custom property pages in
SolidWorks. Instead they are stored directly
on the model. They can either be stored
directly on the model document, or they
will be stored on the actual model
geometry. This ability allows attributes to be traversed. A programmer
can store an attribute on every face of the model, and then later,
traverse the model geometry to retrieve or change their parameters.
Attributes have more storage capability than custom properties. They
are a container for custom information. Custom properties only allow a
user to store one piece of information per property. Attributes are
unlimited in this regard. A programmer can define an attribute and
store many different parameters of different types in it.
Just like custom properties, attributes are saved with a document. This
behavior is called persistence.

Case Study: Document Attributes

217

Lesson 8

API Fundamentals

Adding Custom Properties and Attributes

Naming Attributes

Attributes can be named anything a programmer desires. However,


remember that other third party applications use attributes. It is
recommended that programmers name their attributes with a unique
three character prefix.

Important!

If an application is going to be distributed as a partner-developed third


party application, the authors of the application should contact API
support at SolidWorks and request a unique three character prefix to
use for defining attributes.
Send attribute prefix requests to: apisupport@solidworks.com
1

Open a new part and create new macro.

Name the macro DocumentAttributes.swp.


2

Connect to Solidworks and the active document.

Early bind to SolidWorks and connect to the model.


Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
End Sub

The Attribute
Objects
AttributeDef Object
(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

The Attribute Objects

API Fundamentals

Lesson 8
Adding Custom Properties and Attributes

Attribute Object

To create instances of the attribute definition to a SolidWorks


document, connect to the attribute object using the
AttributeDef::CreateInstance3, as the accessor:

(swAttr)

Dim swAtt As SldWorks.Attribute


Set swAtt = swAttDef.CreateInstance3 (Name)

Attribute Methods
.GetParameter (NameIn)
.GetName
.GetEntity
.GetBody
.Delete

Parameter Object

To get or set the parameters from an attribute created on a model,


connect to the parameter object using the Attribute::GetParameter
method, as the accessor:

(swParam)

Dim swParam As SldWorks.Parameter


Set swParam = swAtt.GetParameter (Name)

Parameter Methods
.GetName
.GetType
.GetDoubleValue & .SetDoubleValue
.GetStringValue & .SetStringValue

The next steps of the case study define an attribute and register with it
with SolidWorks.
3

Declare an attribute definition object and create it.

Add the following code to the macro:


Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swAttDef As SldWorks.attributeDef
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swAttDef = swApp.DefineAttribute(pubMyDocAttributeDef)
End Sub

The Attribute Objects

219

Lesson 8

API Fundamentals

Adding Custom Properties and Attributes

Add the attributes parameters and register it.


Set swAttDef = swApp.DefineAttribute("pubMyDocAttributeDef")
swAttDef.AddParameter "MyFirstParameter", _
swConst.swParamTypeDouble, 10, 0
swAttDef.AddParameter "MySecondParameter", _
swConst.swParamTypeDouble, 20, 0
swAttDef.Register
End Sub

Create an instance of the attribute.

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

Creating an attribute directly on model geometry is demonstrated in the


next case study.

Note
6

Display the attributes parameter values.

The following code displays the attributes parameter values.


Dim swAttDef As SldWorks.attributeDef
Dim swAtt As SldWorks.Attribute
Dim swParam1 As SldWorks.Parameter
Dim swParam2 As SldWorks.Parameter
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)
Set swParam1 = swAtt.GetParameter("MyFirstParameter")
Set swParam2 = swAtt.GetParameter("MySecondParameter")
MsgBox "There is one attribute on this file, " & vbCrLf & _
"with two parameters." & vbCrLf & _
"Parameter 1 = " & swParam1.GetDoubleValue & vbCrLf & _
"Parameter 2 = " & swParam2.GetDoubleValue
End Sub

220

The Attribute Objects

API Fundamentals

Lesson 8
Adding Custom Properties and Attributes

Save and run macro.

Look at the FeatureManager design tree.


The last feature is the attribute that was
created by the macro.

Case Study:
Face Attributes

Exit macro.

The following case study demonstrates


how to create a CNC drilling program
for a plate with many holes in it.
The code for the
Generate Machining Info button on
this user interface traverses the
geometry of the plate and stores
attributes on specific faces. More
specifically, the code traverses all the
faces on a part and when it encounters
a cylindrical face, it stores CNC
machining information in an attribute
on that face
The parameters for the attribute are:
I
I
I
I
I
I
I

Case Study: Face Attributes

Feed Rate
Speed Rate
XPosition
YPosition
ZPosition
Hole Depth
Hole Diameter

221

Lesson 8

API Fundamentals

Adding Custom Properties and Attributes

Open the part and macro.

Open the part Drillplate.sldprt and the


macro FaceAttribute.swp.
In VBA, display UserForm1 by doubleclicking on it from the Project Explorer
window.

Create the attribute definition and add parameters.

Double-click on any empty area on the form to navigate to the


UserForm_Activate event. Add the following code in the location
shown.
'Create an Attribute Definition here.
Set swAttDef = swApp.DefineAttribute("pubMyFaceAttributeDef")
swAttDef.AddParameter "FeedRate", _
swConst.swParamTypeDouble,10, 0
swAttDef.AddParameter "SpeedRate", _
swConst.swParamTypeDouble,20, 0
swAttDef.AddParameter "XPos", _
swConst.swParamTypeDouble,0, 0
swAttDef.AddParameter "YPos", _
swConst.swParamTypeDouble,0, 0
swAttDef.AddParameter "ZPos", _
swConst.swParamTypeDouble,0, 0
swAttDef.AddParameter "Depth", _
swConst.swParamTypeDouble,0, 0
swAttDef.AddParameter "HoleDiameter", _
swConst.swParamTypeDouble,0, 0
swAttDef.Register

Important!

222

Once an attribute definition has been named and registered, a


programmer cannot create a new attribute definition, with the same
name, in the same running session of SolidWorks.

Case Study: Face Attributes

API Fundamentals

Lesson 8
Adding Custom Properties and Attributes

Finding the
Cylindrical Faces
and Attaching
Attributes

The attribute definition was defined and registered with SolidWorks in


the UserForm_Activate event. The next task for the macro will be to
traverse the geometry and attach new instances of this attribute on all of
the cylindrical model faces. To save time, the traversal code has
already been added to the macro. The following steps of the case study
will create instances of the attribute in the geometry traversal code.
3

Create instances of the face attribute.

Show the user form again and double-click on the button labeled
Generate Machining Info.
Add the following code to create instances of the attribute on the
models cylindrical faces.
Private Sub cmdGenerateMachiningInfo_Click()
Set swPart = swModel
If Not swPart Is Nothing Then
retval = swPart.GetBodies2(swConst.swSolidBody, True)
For i = 0 To UBound(retval)
Dim j As Integer
j = 0
Set swFace = retval(i).GetFirstFace
Do While Not swFace Is Nothing
Dim swSurface As surface
Set swSurface = swFace.GetSurface
If swSurface.IsCylinder Then
Dim cylParams As Variant
cylParams = swSurface.CylinderParams
Set swAtt = swAttDef.CreateInstance5(swModel, _
swFace, "MyFaceAttribute-" & j, 0, _
swConst.swAllConfiguration)
j = j + 1
End If
Set swFace = swFace.GetNextFace
Loop
Next i
End If
Set swPart = Nothing
End Sub

Case Study: Face Attributes

223

Lesson 8

API Fundamentals

Adding Custom Properties and Attributes

Set the attributes parameter values.

Once an attribute is created, the parameters can be returned and their


values can be set.
Add the following code immediately after the call to CreateInstance5.
Set swAtt = swAttDef.CreateInstance5(swModel, _
swFace, "MyFaceAttribute-" & j, 0, _
swConst.swAllConfiguration)
If Not swAtt Is Nothing Then
Set swAttParam = swAtt.GetParameter("FeedRate")
bRet = swAttParam.SetDoubleValue2(0.002, _
swConst.swAllConfiguration, "")
Set swAttParam = swAtt.GetParameter("SpeedRate")
bRet = swAttParam.SetDoubleValue2(250, _
swConst.swAllConfiguration, "")
Set swAttParam = swAtt.GetParameter("XPos")
bRet = swAttParam.SetDoubleValue2 _
(cylParams(0) / 0.0254, _
swConst.swAllConfiguration, "")
Set swAttParam = swAtt.GetParameter("YPos")
bRet = swAttParam.SetDoubleValue2 _
(cylParams(1) / 0.0254, _
swConst.swAllConfiguration, "")
Set swAttParam = swAtt.GetParameter("ZPos")
bRet = swAttParam.SetDoubleValue2 _
(cylParams(2) / 0.0254, _
swConst.swAllConfiguration, "")
Set swAttParam = swAtt.GetParameter("HoleDiameter")
bRet = swAttParam.SetDoubleValue2 _
((cylParams(6) / 0.0254) * 2, _
swConst.swAllConfiguration, "")
Set swAttParam = swAtt.GetParameter("Depth")
bRet = swAttParam.SetDoubleValue2(1.3, _
swConst.swAllConfiguration, "")
Set swAtt = Nothing
End If
j = j + 1
End If
Set swFace = swFace.GetNextFace
Loop
Next i
End If
Set swPart = Nothing
End Sub

224

Case Study: Face Attributes

API Fundamentals

Lesson 8
Adding Custom Properties and Attributes

Displaying
Callouts in the
Model View

The Callout object is used to


create a SolidWorks style callout
that is displayed in the model
view. In this case it is used to
provide feed back to the
programmer to make sure the
traversal code is working
properly. In this example, the
callout object is passed as the
third parameter to the
swFace.Select3 method.

Callout Object

Callouts Displayed on the Model

To create instances of a Callout object, use


SelectionMgr::CreateCallout, as the accessor:

(swCallOut)

Dim swCallout As SldWorks.Callout


Set swCallout = swSelMgr.CreateCallout

Callout Members
.Label
.Target Style
.TextBox

Add code to display callout information.

Before a face is selected, format a Callout object with the attribute


name, speed rate, feed rate, and the cylindrical face values.
Pass the Callout object to the third parameter of the Entity::Select3
method.
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

Case Study: Face Attributes

&
&
&
*

_
_
_
2

225

Lesson 8

API Fundamentals

Adding Custom Properties and Attributes

Creating the CNC


Code

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

Even though the code in the Generate Machining Info button


specifically attached the attributes to the face entities of the model, the
code for the Generate CNC Code button performs a feature traversal
instead of a geometry traversal to retrieve the attributes.
Although the attributes are located on faces in the model, a programmer
can still access them from the FeatureManager design tree. This is
because an attribute is a type of feature.
In many cases it can be faster to traverse the FeatureManager design
tree to retrieve the attributes. The reason for this is that a model may
have thousands of faces and only a hundred features. It would be faster
to traverse the hundred features rather than the thousand faces on the
model to retrieve the attribute data.
If a programmer decides to traverse the geometry to find the attributes,
the Entity::FindAttribute method is used to return an attribute pointer
from an entity in the traversal code.

Tip

Review attribute retrieval code.

Display the user form in VBA and double-click on the button labeled
Generate CNC Code.
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
Dim paramHoleDia As SldWorks.Parameter
Set paramHoleDia = swAtt.GetParameter("HoleDiameter")
Dim paramFeedRate As SldWorks.Parameter
Set paramFeedRate = swAtt.GetParameter("FeedRate")

226

Case Study: Face Attributes

API Fundamentals

Lesson 8
Adding Custom Properties and Attributes

Dim paramSpeedRate As SldWorks.Parameter


Set paramSpeedRate = swAtt.GetParameter("SpeedRate")
Dim paramXPos As SldWorks.Parameter
Set paramXPos = swAtt.GetParameter("XPos")
Dim paramYPos As SldWorks.Parameter
Set paramYPos = swAtt.GetParameter("YPos")
Dim paramZPos As SldWorks.Parameter
Set paramZPos = swAtt.GetParameter("ZPos")
Dim paramDepth As SldWorks.Parameter
Set paramDepth = swAtt.GetParameter("Depth")
If paramHoleDia.GetDoubleValue <> DrillDiameter Then
FirstPass = True
i = i + 1
End If
DrillDiameter = paramHoleDia.GetDoubleValue
If FirstPass = True Then
ListBox1.AddItem "// Drill Dia = " & _
paramHoleDia.GetDoubleValue
ListBox1.AddItem "G50 X0 Y0 Z0 // Go Home"
ListBox1.AddItem "G00 G05 T0" & i
ListBox1.AddItem "M03 S" & paramSpeedRate.GetDoubleValue
ListBox1.AddItem "G00 X" & paramXPos.GetDoubleValue & _
" Y" & paramYPos.GetDoubleValue & " Z1.0"
ListBox1.AddItem "G00 Z.05"
ListBox1.AddItem "G83 F" & paramFeedRate. _
GetDoubleValue & " Q" & _
paramHoleDia.GetDoubleValue / 2 & " Z" & _
paramDepth.GetDoubleValue
Else
ListBox1.AddItem "X" & paramXPos.GetDoubleValue & _
" Y" & paramYPos.GetDoubleValue
End If
FirstPass = False
End If
Set swFeature = swFeature.GetNextFeature
Wend
ListBox1.AddItem "G50 X0 Y0 Z0"
ListBox1.AddItem "M30"
End Sub

Case Study: Face Attributes

227

Lesson 8

API Fundamentals

Adding Custom Properties and Attributes

Save and run the macro.

Click on the Generate Machining Info button.


The cylindrical faces on the model are highlighted
and the callouts are displayed in the model view.
Examine the multiple attributes that are listed in the
FeatureManager design tree.

Click the Generate CNC Code button.

Examine the CNC code added to the list box on the user form.
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

Case Study: Face Attributes

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
retval = AttributeDef.CreateInstance5 ( ownerDoc, ownerObj, nameIn, options,
configurationOption )

Return:

retval

Pointer to the newly created Attribute object

Input:

ownerDoc

Document whose FeatureManager design tree to


which to add this attribute

Input

ownerObj

Component or entity to which to add this attribute:

Input

nameIn

Name to assign to this attribute instance

Input

options

Creation control options

Input

configurationOption

Configuration options as defined in


swInConfigurationOpts_e

Tip

If an attribute feature is hidden, it cannot be selected or deleted from


the model. To make the attribute visible, use the method
Feature::SetUIState. Once it is visible it can be selected with any of the
selection APIs and then a call to ModelDoc2::DeleteSelection would
delete it from the model.

Case Study: Face Attributes

229

Lesson 8

API Fundamentals

Adding Custom Properties and Attributes

230

Case Study: Face Attributes

API Fundamentals

Exercise 14:
Adding Mass Properties as Custom Properties

Exercise 14:
Adding Mass
Properties as
Custom
Properties

Objective

To retrieve mass properties from a part by setting the material density,


processing all configurations and adding that data as custom properties.
Set the material to Aluminum (density = 2.7 grams/cm3).

Skills Learned

Handling configurations.

Getting mass properties.

Adding custom properties

APIs Used

ModelDoc2.GetConfigurationNames
ModelDoc2.ShowConfiguration2
ModelDoc2.SetUserPreferenceIntegerValue
ModelDoc2.SetUserPreferenceStringValue
ModelDoc2.GetMassProperties
ModelDoc2.AddCustomInfo3

Procedure

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

Adding Mass Properties as Custom Properties

Solution

Option Explicit
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim retval() As String
Dim i As Integer
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
Dim density As Double
density = 2700
swModel.SetUserPreferenceDoubleValue _
swConst.swMaterialPropertyDensity, density
swModel.SetUserPreferenceStringValue _
swConst.swMaterialPropertyCrosshatchPattern, _
"ISO (Aluminum)"
Dim massprops As Variant
Dim status As Long
massprops = swModel.Extension.GetMassProperties(1, status)
swModel.AddCustomInfo3 retval(i), _
"Mass - " & retval(i), _
swConst.swCustomInfoText, _
Format(massprops(5) * 1000, "###0.000000")
swModel.AddCustomInfo3 retval(i), _
"Density - " & retval(i), _
swConst.swCustomInfoText, _
Format(density / 1000, "###0.000000")
swModel.AddCustomInfo3 retval(i), _
"Volume - " & retval(i), _
swConst.swCustomInfoText, _
Format(massprops(3) * 1000 * 1000, "###0.000000")
Next
End Sub

232

API Fundamentals

Exercise 15:
Adding Attributes to Edges

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

Determine its length


Select it
Attach a callout to it
Store an attribute on it
Add the line number and its length to the listbox on the form

Skills Learned
I
I
I
I
I

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

Adding Attributes to Edges

Solution

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
Private Sub UserForm_Activate()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
If swModel Is Nothing Then
MsgBox "There is no open document to run this macro on."
Exit Sub
End If
If swModel.GetType <> swDocPART Then
MsgBox "This code only works on a part document."
Exit Sub
End If
Set swAttDef = swApp.DefineAttribute("pubLineAttributeDef")
swAttDef.AddParameter "LineLength", _
swConst.swParamTypeDouble, 10, 0
swAttDef.Register
End Sub
Private Sub btnCreateLineAttributes_Click()()
Traverse the body to find all of the cylindrical surfaces
Set swPart = swModel
If Not swPart Is Nothing Then
retval = swPart.GetBodies2(swConst.swSolidBody, True)
For i = 0 To UBound(retval)
Dim j As Integer
j = 0
Set swFace = retval(i).GetFirstFace
Do While Not swFace Is Nothing
Dim i_Edges As Variant
i_Edges = swFace.GetEdges
For k = 0 To UBound(i_Edges)
Dim i_curve As Curve
Set i_curve = i_Edges(k).GetCurve
If i_curve.IsLine Then
Set swAtt = swAttDef.CreateInstance5(swModel, _
i_Edges(k), "LineAttribute" & j, 0, _
swConst.swAllConfiguration)
If Not swAtt Is Nothing Then
Set swAttParam = swAtt.GetParameter("LineLength")
Dim curveParams As Variant
curveParams = i_Edges(k).GetCurveParams2
Dim linelength As Double

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
Create a callout object
Dim swCallout As SldWorks.Callout
Set swCallout = swSelMgr.CreateCallout
swCallout.TargetStyle = _
swConst.swCalloutTargetStyle_e. _
swCalloutTargetStyle_Arrow
Set the label with the values of the geometry.
swCallout.Label = "Edge " & j & " =" & linelength
ListBox1.AddItem swCallout.Label
Use Select3 to add the callout to the selection
swFace.Select3 True, 0, swCallout
Set swAtt = Nothing
End If
End If
j = j + 1
Next k
Set swFace = swFace.GetNextFace
Loop
Next i
Set swPart = Nothing
End If
End Sub

235

Exercise 15:
Adding Attributes to Edges

236

API Fundamentals

API Fundamentals

Lesson 9
The SolidWorks API SDK

Upon successful completion of this lesson, you will be able to:


I

Download and install the SolidWorks API SDK.

Create a Microsoft Visual Basic.NET Add-In.

Create a Microsoft Visual C#.NET Add-In.

Create a Microsoft Visual C++ Add-In.

237

Lesson 9
The SolidWorks API SDK

238

API Fundamentals

API Fundamentals

Lesson 9
The SolidWorks API SDK

The API SDK

The API SDK is the Software Development Kit that is provided by


SolidWorks for developers to write add-ins that interact with
SolidWorks software. The SDK provides wizards for Visual Studio 6
and Visual Studio.NET for creating add-in applications for
SolidWorks. It also provides many useful programming examples that
can be used in API programming projects.

Installing the 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.
1

Browse to the SolidWorks web site.

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

Double-click the SDK hyper link.

On the API Support download page, click on the first link titled
SolidWorks API SDK 2006

The API SDK

239

Lesson 9

API Fundamentals

The SolidWorks API SDK

Open the file.


A File Download dialog appears. Click Open to install the SDK.

Install the SDK.

Double-click on the file named api_sdk.exe to start the installation.

This dialog may vary depending on which Zip utility is installed on the
machine that the SDK is being setup on.

Note
5

240

Continue with installation.


Click Next.

The API SDK

API Fundamentals

Lesson 9
The SolidWorks API SDK

The API SDK

Accept the License Agreement.

Add the customer information.

Choose the Custom configuration.

241

Lesson 9

API Fundamentals

The SolidWorks API SDK

Determine the installed development environment.

Check to see what version of Visual Studio is loaded on the installation


computer.
If the computer has Visual Studio.NET 2003 then the Visual
Studio.NET 2003 Add-in Wizards should be installed.
If the computer is running a version of Visual Studio.NET released
before 2003, Visual Studio.NET Add-in Wizards should be installed.

Important!

If the wrong versions of the add-in wizards are installed, they will not
work properly.
10 Choose the options to install.

This computer has Microsoft Visual Studio.NET 2003 installed on it.


Choose to install this feature and all of the sub features.

242

The API SDK

API Fundamentals

Lesson 9
The SolidWorks API SDK

11 Click Next.

12 Click Install.

13 Installation Progress.

This installation progress dialog is displayed.

The API SDK

243

Lesson 9

API Fundamentals

The SolidWorks API SDK

14 Complete the installation.


Click Finish to exit the installation wizard.

Case Study:
Creating a
VB.NET Add-In.

Now that the SDK is installed, a SolidWorks add-in application can be


created using any of the .NET programming languages. Up to this point
all code has been written using the Visual Basic programming
language. The next case study will use Visual Basic.NET.

Create a new SolidWorks Add-In with Visual Basic.NET.

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.
In the Name: text box, type SwVBAddIn1 and click OK.

244

Case Study: Creating a VB.NET Add-In.

API Fundamentals

Lesson 9
The SolidWorks API SDK

Set the add-in options as shown.


Click Finish to complete the wizard.

Examine the programming project.

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.

Case Study: Creating a VB.NET Add-In.

245

Lesson 9

API Fundamentals

The SolidWorks API SDK

Compile the project

From the Visual Studio Build menu, click Build Solution. The project
should successfully compile.
The build results are displayed in the Output window.

References

In most cases, the project should successfully


compile. However in some cases, references to
the SolidWorks type libraries may not be
successfully created. If the references are not
created, the project will not build successfully.
References in Visual Studio.NET are added
similarly to the Tools, References... menu in
VBA. When you add a type library to a project
in Visual Studio.NET, a reference is created to it
in the References folder in the Solution
Explorer.
Examine the Project Explorer and expand the
References folder. In the diagram to the right,
none of the SolidWorks type libraries have been
added in the References folder.

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.

Case Study: Creating a VB.NET Add-In.

API Fundamentals

Lesson 9
The SolidWorks API SDK

Add a reference to the project.


Navigate to the Solution Explorer.

Right-click on the References folder.


Click Add Reference from the popup menu.
6

Add the SldWorks 2006 type library.


From the Add Reference dialog box, click the COM tab.

Scroll down the list of components and double-click the


SldWorks 2006 Type Library to add it to the Selected
Components list.
Leave the dialog open to add other references.

Add the constants type library.

Scroll down the list of Components double-click the


Sldworks 2006 Constant type library.

Case Study: Creating a VB.NET Add-In.

247

Lesson 9

API Fundamentals

The SolidWorks API SDK

Add the SolidWorks Add-In type library.

Also double-click the


SolidWorks exposed type libraries for add-in use.
Click OK to add these references to your project.

The following step is only necessary if


the reference to the System.Drawing.dll
was not created automatically by the
add-in wizard.

Important!

Add a .NET reference to the project.


Right-click on the References folder and click Add Reference.

From the .NET tab, double-click the reference named


System.Drawing.dll.
Click OK to add this reference to the project.

248

Case Study: Creating a VB.NET Add-In.

API Fundamentals

Lesson 9
The SolidWorks API SDK

10 Build the project.


Go to the Build menu and click Build Solution to compile the project.

Comparing Addin
DLLs and StandAlone Executables

There are two types of applications that can be created to interact with
SolidWorks.
I
I

Add-in applications (*.DLL)


Stand-alone applications (*.EXE)

There are advantages and disadvantages to either application.


Add-in applications run in the same process space as the SolidWorks
application. Add-in applications allow greater control over the hosting
application. Menus, toolbars and PropertyManager pages can be
implemented in SolidWorks with an add-in. The disadvantage is that if
an exception occurs, the SolidWorks session is affected by the
exception also.
Applications can also be created that run outside of the SolidWorks
process space. This is called a stand-alone application. An advantage
of creating a stand-alone application is that when an exception occurs,
only the stand-alone application is affected. The hosting application
will still run unaffected (in most cases.) The disadvantage is that
toolbars, menus and property pages cannot be properly implemented in
a stand alone program. Also, the performance of a stand-alone
application is not as good. This is because all the calls to the
SolidWorks API must be translated over the process boundaries.
Note

The remaining chapters of this book demonstrate how to create and


implement add-in applications. Stand-alone applications are not
covered in detail.

Case Study: Creating a VB.NET Add-In.

249

Lesson 9

API Fundamentals

The SolidWorks API SDK

Loading and
Running an Add-in
Application

Once an add-in application compiles successfully, it can be loaded into


a running SolidWorks session. This is done by opening the DLL using
the File, Open... command in the SolidWorks user interface.
When a project is initially compiled it is compiled as a debug build. A
debug version of the DLL is created in the projects \Debug directory
of the programming project.

Tip

An add-in projects properties can be changed to create a release build


of the add-in. To do this:
1.) Click Project, Properties... from the Visual Studio menu.
2.) Click the Configuration Manager button.
3.) Change the Active Solution Configuration to Release.
4.) Click Close to exit the dialog.
5.) Click OK to exit the properties dialog.

Important!

250

If a release build is compiled, the DLL will be located in the projects


\Release directory.

Case Study: Creating a VB.NET Add-In.

API Fundamentals

Lesson 9
The SolidWorks API SDK

11 Load the DLL into SolidWorks.


In SolidWorks, from the File menu, click Open....

Change the Files of type: filter to Add-Ins (*.DLL).


Navigate to the add-in projects obj/debug directory.
Double-click the file named SwVBAddIn1.dll.
This will cause SolidWorks to load the add-in.
12 Check the Add-In Manager.
Click Tools, Add-Ins....

Scroll down in the list of add-ins to find


SwVBAddIn1.
Click OK to exit the Add-ins Manager.

Tip

When the DLL is loaded, SolidWorks automatically adds the


add-ins name to the SolidWorks Add-Ins Manager. It also
automatically added the required registry entries.
The registry entries are made in the registry under
HKEY_LOCAL_MACHINE\SOFTWARE\Solidworks\Add-Ins.
SolidWorks will make these registry entries for any legitimate DLL
that is opened using the File, Open... menu. When distributing a DLL,
a good setup program will make these entries. To remove the add-in
name from the Add-Ins Manager, delete the corresponding key from
the registry. A well written setup program will remove these entries
when the add-in is removed from an end users computer..

Case Study: Creating a VB.NET Add-In.

251

Lesson 9

API Fundamentals

The SolidWorks API SDK

13 Invoke the menu created by the Add-In.


Click the newly created menu SwVBAddIn1

to expose its sub-menus, then click


Create Cube.

14 Show the PropertyManager Page.


From the SwVBAddIn1 menu, click ShowPMP....

15 Examine the custom toolbar.

The toolbar has three buttons that are not functional.


Additional programming is needed to implement the
buttons.
16 Unload the Add-In.
From the Tools menu, click Add-Ins....

Clear the check box next to


SwVBAddin1 to unload it.
Click OK.

17 Close SolidWorks.

Return to the development environment.

Case Study:
Creating a C#
Add-in

252

C# is another popular programming language that can be used to write


SolidWorks add-ins. It combines many language features from Visual
Basic 6.0 and Visual C++ into one complete language. The API SDK
includes the SolidWorks C# Add-In Wizard. This add-in application
wizard works exactly like the wizard demonstrated in the last case
study. The C# Add-In Wizard creates a skeleton application for a
SolidWorks Add-In.

Case Study: Creating a C# Add-in

API Fundamentals

Lesson 9
The SolidWorks API SDK

Create a new SolidWorks C# Addin.


From the Visual Studio.Net File menu, click New, Project....

Click the Visual C# Projects folder in the


Project Types list box.
Click SolidWorks C# Addin from the Templates list.
Name the add-in SwCSharpAddin1.
Click OK to start the SolidWorks C# Addin wizard.

Set the add-in options.

Click Finish to complete the wizard.

Important!

If the wizard fails to create the proper references to the SolidWorks


type libraries, return to steps 5 through 10 in the previous case study.

Case Study: Creating a C# Add-in

253

Lesson 9

API Fundamentals

The SolidWorks API SDK

Build the project.


From the Build menu, click Build Solution to compile the project.

Start SolidWorks and load the add-in.

Load the DLL named SwCSharpAddin.DLL from the projects


obj\Debug directory.
5

Examine the new menus.

Create a Cube.

From the SwCSharpAddin1 menu,


click Create Cube.

Show the Property Page.


From the SwCSharpAddin1 menu, click
Show PMP....

Examine the custom toolbar.

Unload the add-in.


From the Tools menu, click Add-Ins....

Clear the check box next to


SwCSharpAddin1 to unload it.
Click OK to exit the Add-Ins Manager.

10 Close SolidWorks and return to VB.NET.

254

Case Study: Creating a C# Add-in

API Fundamentals

Lesson 9
The SolidWorks API SDK

Case Study:
C++ Add-Ins

Another wizard in the SDK is available that creates a skeleton for a


C++ add-in application. C++ applications provide the best performance
of all the API compatible programming languages.
This exercise is not a comprehensive study of C++ programming. It
demonstrates how to create a C++ add-in application. It also
demonstrates how to compile, load and debug the DLL created by the
wizard.
1

Create a SolidWorks COM AddIn.

Start a new project in Visual Studio.NET.


Choose Visual C++ Projects from the Project Types list.
Name the add-in SwAddin1 and set its Location.

Double-click the SolidWorks COM Addin icon from the Templates


list.

Case Study: C++ Add-Ins

255

Lesson 9

API Fundamentals

The SolidWorks API SDK

Review the names of the add-in object.

Keep the default names.

Select the threading options.

On the left side of the wizard page, click the Options link.
Leave the Threading options and the Interface check box set to their
default values.

256

Case Study: C++ Add-Ins

API Fundamentals

Lesson 9
The SolidWorks API SDK

Select the SwOptions.


Click on the SwOptions link.

Click all of the options on this page.


Click Finish.

Compiling a C++
Add-In

Case Study: C++ Add-Ins

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.

257

Lesson 9

API Fundamentals

The SolidWorks API SDK

Change the project properties.


From the Visual Studio Project menu, click Properties....

Click the C/C++ folder.


Click the General sub item.

Change the directories.


Change the Additional Include Directories path property to:
C:\Program Files\SolidWorks.

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.

Case Study: C++ Add-Ins

API Fundamentals

Lesson 9
The SolidWorks API SDK

Build the project.

The project should successfully compile.


Loading the C++
Add-In

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.

Load the DLL into SolidWorks.

In SolidWorks, click File, Open...


Change the Files of type: filter to Add-Ins (*.dll).
Navigate to the directory where the programming project is located.
Now navigate to the \Debug directory.
Double-click the file named SwAdd-In1.dll.
The add-in will be loaded into SolidWorks.
9

Create a new part.

Create a new part document in SolidWorks.


This will enable all of the menu items that the add-in has created.
10 Click the menu created by the add-in.
Click SwAddIn1, Start Notepad... to test the menu.

Case Study: C++ Add-Ins

259

Lesson 9

API Fundamentals

The SolidWorks API SDK

11 Click the Show PMP menu item.


Click SwAddIn1, Show The PMP... from the

menu.
A sample property page is displayed in the
PropertyManager.

12 Click the Toolbar.

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.

Return to the development environment.


Debugging the
C++ Add-in

260

A C++ programming project can be set up to start the SldWorks.exe file


when the debugger starts. Break points can be set in the code and the
programmer can debug the code line by line while the add-in is running
in SolidWorks. The following steps in the case study demonstrate how
to set up the project so it can be debugged.

Case Study: C++ Add-Ins

API Fundamentals

Lesson 9
The SolidWorks API SDK

14 Display the Class View window.


From the Visual Studio View menu, click Class View.
15 Expand the CSwAddin1 class

CSwAddin1 is the name of the add-in object generated by the add-in


wizard.
Double-click on the ConnectToSW method.

16 Add a break point.

The source code file is opened and the cursor is set on the first line of
this method.
Click in the margin next to the method call to create a break point.

Case Study: C++ Add-Ins

261

Lesson 9

API Fundamentals

The SolidWorks API SDK

17 Start debugging.

From the Visual Studio Debug menu, click Start.


The Executable for Debugging Session dialog is displayed.
Enter the path for where the SldWorks.exe file resides on the
development computer.

Note

SldWorks.exe is a release build with no source included. A programmer


can debug the add-in code but cannot step into any SolidWorks source
code for debugging purposes. The No Symbolic Information dialog
may displayed
18 Step through the code.
Keep pressing the F10 key to step through the code in this method.

19 Press the F5 to continue executing the code.

Control will be returned to the SolidWorks application.


Close SolidWorks to stop the debugger.
20 Close the add-in solution.
From the Visual Studio File menu, click Close Solution.

262

Case Study: C++ Add-Ins

API Fundamentals

Lesson 9
The SolidWorks API SDK

Choosing a
Programming
Language

The purpose of this chapter is to familiarize the reader with several of


the programming wizards provided in the API SDK. A programmer can
use any of the languages featured here to create add-in applications for
SolidWorks. The choice is up to the programmer and will usually be
determined by which language the programmer is most familiar with.
Because SolidWorks supports a working VBA compiler, This book is
written using Visual Basic as the programming language of choice.
This ensures that any reader will be able to complete most of this book
without purchasing any other development environments.
There are no exercises for this lesson. The remaining lessons will
continue using VB.NET as the programming language.

Choosing a Programming Language

263

Lesson 9

API Fundamentals

The SolidWorks API SDK

264

Choosing a Programming Language

API Fundamentals

Lesson 10
Customizing the SolidWorks
User Interface

Upon successful completion of this lesson, you will be able to:


I

Use the SolidWorks VB.NET Add-In Wizard.

Load a custom add-in into SolidWorks and debug it.

Add a custom menu and menu items to SolidWorks.

Design and implement a custom toolbar for the add-in.

Create and implement a custom PropertyManager page with


custom controls.

Customize other components in the SolidWorks user interface.

265

Lesson 10
Customizing the SolidWorks User Interface

266

API Fundamentals

API Fundamentals

Lesson 10
Customizing the SolidWorks User Interface

Case Study:
Customizing
the UI With
VB.NET

This case study demonstrates how to customize the SolidWorks user


interface using Visual Basic.NET. To make an application look and
feel more like it is a part of SolidWorks software, a programmer can
create their own user interface components in SolidWorks. The
following is a list of the user interface components that can be added or
customized using the API:
I
I
I
I
I
I
I

*PropertyManager pages
*Menus and sub-menus
*Toolbars
*Pop-up menus
*FeatureManager pages
Model views
Status bar

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.

Note

Create a new SolidWorks VB.NET Add-In.

Name the add-in CustomSWAddin.


Click OK.

Case Study: Customizing the UI With VB.NET

267

Lesson 10

API Fundamentals

Customizing the SolidWorks User Interface

Set the add-in properties.


Click Finish.

Display the source code.

Press Ctrl + Alt + L to show the Solution Explorer window.


Double-click on the file named CustomSwAddin.VB.
The source code file is activated in the code editor.
This file contains the class definition of this projects add-in object.
Spend a few moments and examine the source code.

268

Save the project.


From the File menu, click Save All.

Compile the DLL.


From the Build menu, click Build Solution to compile the DLL.

Case Study: Customizing the UI With VB.NET

API Fundamentals

Lesson 10
Customizing the SolidWorks User Interface

Load the DLL into SolidWorks.

Start SolidWorks.
From the File menu, click Open....
Change the Files of type filter to Add-Ins (*.dll).
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.
7

Test the new user menu.

From the new CustomSwAddin menu, click Create Cube.


After the cube is extruded in the new part, click
CustomSwAddin, ShowPMP to display the new custom
PropertyManager page.
Also notice the new custom toolbar.

Display the Add-Ins Manager.


From the Tools menu, click Add-Ins... to
display the Add-Ins Manager.

Scroll to the CustomSwAddin entry.


Leave the add-in selected.
Click OK to exit the Add-Ins Manager.

Close SolidWorks.

Return to Visual Studio.

Case Study: Customizing the UI With VB.NET

269

Lesson 10

API Fundamentals

Customizing the SolidWorks User Interface

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.
The major difference is that when working in a macro, SolidWorks is
hosting the VBA macro editor. When writing an add-in application, the
development environment is a separate application. A project property
will need to be set to tell the compiler where the SolidWorks
executable is located on the development computer.
By setting this property in the development environment, SolidWorks
can be launched automatically by the debugger. The programmer can
then interactively work in SolidWorks and debug the add-in code at the
same time.
10 Edit the project properties.
From the Project menu, click CustomSwAddin Properties....

Click on the Configuration Properties folder to expand the folder.


Click on the Debugging sub item in this list.
Click the Start external program option.
Use the browse button to browse to the directory where SolidWorks
is installed.
Click on the file named SldWorks.exe.
Click Open to accept this file.
Click Apply to set this property in the project.
Click OK to exit the project properties.

270

Case Study: Customizing the UI With VB.NET

API Fundamentals

Lesson 10
Customizing the SolidWorks User Interface

11 Set a break point.

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
and DisconnectFromSW.

ConnectToSW

Establish a break point by clicking in the margin next to following line


of code:

12 Debug the program.


From the Debug menu in Visual Studio, click Start.

This will start SolidWorks and the debugger.


When SolidWorks starts, the add-in will automatically load, and the
code stops executing at the break point.

Debugger
Keyboard
Shortcuts

The following key strokes are used when debugging in


Visual Studio.NET:
I
I
I

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.

These keyboard shortcuts are slightly different from the debugging


keyboard shortcuts in VBA.

Case Study: Customizing the UI With VB.NET

271

Lesson 10

API Fundamentals

Customizing the SolidWorks User Interface

13 Continue debugging.
Press F10 to step through several lines of code in the ConnectToSW

function.
Step to the End

Function

statement.

Press F5 to continue executing the code.


14 Create a cube.

Return to the SolidWorks user


interface.
From the CustomSwAddin menu,
click Create Cube....

15 Stop the debugger.


From the Debug menu in Visual Studio, click Stop Debugging.

Doing this will end the current SolidWorks session and return focus to
Visual Studio.

Understanding
The Add-in
Code

The source code in the file named CustomSwAddin.VB is shown in


the following diagram. This is the class definition of the add-in object.

Note

Many comments have been added to the code diagrams in this case
study. The add-in wizard does not generate these automatically.

272

Understanding The Add-in Code

API Fundamentals

Lesson 10
Customizing the SolidWorks User Interface

Importing
Namespaces

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.

Namespace Name

Description

Imports SldWorks

Namespace name of the SolidWorks type library.

Imports SwPublished

Namespace name of an additional SolidWorks type


library used for creating add-in and
PropertyManagerPage objects.

Imports SwConst

Namespace name of the SolidWorks constant type


library.

Imports
System.Runtime.InteropServices

Namespace name of the


System.Runtime.InteropServices namespace. This is
used when working in projects that use legacy COM
style type libraries and un-managed code.

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

can be typed like this:


Dim swModel As ModelDoc2

Notice the namespace name has been eliminated. The namespace prefix
can be eliminated for every object declared from this namespace.
The Add-in Class

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.

Understanding The Add-in Code

273

Lesson 10

API Fundamentals

Customizing the SolidWorks User Interface

16 Examine the namespace and class declarations.

The following code has been commented. Study the code.


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.

17 Expand the ISwAddin Implementation region.

Read the comments in the following diagram to understand the code.


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.

274

Understanding The Add-in Code

API Fundamentals

Lesson 10
Customizing the SolidWorks User Interface

Connecting to
Solidworks

SolidWorks calls the SwAddin::ConnectToSW method when an


add-in is initially loaded. This method is used to create new custom
user interface items, set up SolidWorks notification handlers, and
establish bidirectional communication between the add-in and
SolidWorks.

SwAddin::ConnectToSW
IsConnected = SwAddin.ConnectToSW (ThisSW, cookie)

Output:

IsConnected

TRUE

Input:

ThisSW

Pointer to the SldWorks Dispatch object.

Input:

Cookie

Add-in ID.

if the add-in connected successfully, FALSE if not

18 Expand the ConnectToSW Function.

Expand the ConnectToSW function.


Study the code and comments.

Understanding The Add-in Code

275

Lesson 10

API Fundamentals

Customizing the SolidWorks User Interface

Bidirectional
Communication

When SolidWorks loads an add-in, a cookie is used to assign the add-in


a unique identifier. The cookie is generated dynamically by
SolidWorks when an add-in is loaded. SolidWorks uses this cookie to
determine what add-in it is communicating with it at any given time.
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.

Setting Callback
Information

Use the method SldWorks.SetAddinCallbackInfo to send the cookie and


the add-ins Me pointer back to SolidWorks.

SldWorks.SetAddinCallbackInfo
Status = SldWorks.SetAddinCallbackInfo ( ModuleHandle, AddinCallbacks, Cookie )

Output:

Status

TRUE

Input:

ModuleHandle

Instance handle of the add-in.

Input:

AddinCallbacks

Pointer to the object that includes the add-in callback


methods.

Input:

Cookie

Add-in ID.

276

if the add-in connected successfully, FALSE if not

Understanding The Add-in Code

API Fundamentals

Lesson 10
Customizing the SolidWorks User Interface

19 Review the method.

Review the code for the SldWorks::SetAddinCallbackInfo method.


The add-ins object pointer and the cookie are passed back to
SolidWorks to establish bidirectional communication.

20 Review the rest of the code in this function.

The following four lines of code are wizard generated.


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.

Right-click on the user defined function named


AddMenus and click Go To Definition from the
popup menu.

Custom Menus

Call the SldWorks::AddMenu method to add a new menu to the


SolidWorks interface.

SldWorks::AddMenu
retval = SldWorks.AddMenu ( docType, menu, position )

Output:

retval

TRUE

Input:

docType

Document type to which the menu item is to be


added.

Input:

menu

Menu name to be added.

Input:

position

Specifies the position at which to add the new menu


or submenu.

Understanding The Add-in Code

if the add-in connected successfully, FALSE if not

277

Lesson 10

API Fundamentals

Customizing the SolidWorks User Interface

Menus in SolidWorks are added depending on the document type that


is currently active in the SolidWorks session.
The first parameter of the SldWorks::AddMenu method lets you specify
what document type this menu will be enabled for.
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

If there is a maximized document active in SolidWorks, the icon takes a


position in the menu. Remember to include the icon as a menu position
whenever a document is maximized. If a document is minimized, do
not include the icon as a menu position.
Menu positions:
3
1 2
4

22 Review the AddMenus sub program.

This first menu is set up only if their are no documents open in the
current SolidWorks session.

278

Understanding The Add-in Code

API Fundamentals

Lesson 10
Customizing the SolidWorks User Interface

Custom Menu
Items

After a custom menu is created, establish menu items by calling


SldWorks::AddMenuItem2. This method is used to add menu items to
the existing or custom menus in SolidWorks. Study the diagram to
understand each of the parameters.

SldWorks::AddMenuItem2
IsMenuItemAdded = SldWorks.AddMenuItem2 ( DocumentType, Cookie, MenuItem, Position,
MenuCallback, MenuEnableMethod, HintString )

Output:

IsMenuItemAdded

TRUE

Input:

DocumentType

Document type to which to add the menu item.

Input:

Cookie

Add-in ID.

Input:

MenuItem

Menu string
("menuItem@subMenuString@menuString").

Input:

Position

Position at which to add the new menu item.

Input:

MenuCallback

Function to call when this menu item is selected.

Input:

MenuEnableMethod

Optional function that controls the state of the menu


item.

Input:

HintString

Text to show in the SolidWorks status bar when the


user moves their mouse over this menu item.

Setting Up
Callbacks

if menu item is added, FALSE if not.

The fourth parameter of this method requires some explanation. A


callback is a method that an add-in exposes that can be called by
SolidWorks. A callback is a user defined sub program or function. It is
defined in the add-in object and is declared Public so that it can be
accessed externally from the DLL. A callback would need to be
implemented in this add-in because when a custom menu item is
clicked, SolidWorks needs to direct this call back to the exposed
method.

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.

Understanding The Add-in Code

279

Lesson 10

API Fundamentals

Customizing the SolidWorks User Interface

23 Examine the code for AddMenuItem2


The menu item named Create Cube is added to the custom menu.

When the user clicks the menu item in SolidWorks, SolidWorks


invokes the callback function named MenuCallBack exposed by the
add-in.

24 Review the rest of the code in the AddMenus sub program.

The rest of the code in this module sets up the menus for all of the other
document types.

25 Expand the UI Callbacks region.

All of the callback functions for the menus and toolbars are listed in
this region of the source code.

280

Understanding The Add-in Code

API Fundamentals

Lesson 10
Customizing the SolidWorks User Interface

26 Expand the MenuCallback function

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.

27 Debug the application.

Start the debugger.


When SolidWorks starts, notice that the
new menu and menu items are created.
From the CustomSWAddin menu,
click Create Cube... to invoke the
callback function in the DLL.

28 Stop the debugger.

Return to the development environment.


Creating and
Adding Custom
Toolbars to an
Add-in

In order to create a custom toolbar, an understanding of how the toolbar


bitmap images function is necessary. Consider a custom toolbar with
one button. The SldWorks::AddToolbar4 method requires two images,
one small, one large. For the small bitmap, the image for each button
must be 16x16 pixels, for the large bitmap it must be 24x24 pixels.

Understanding The Add-in Code

281

Lesson 10

API Fundamentals

Customizing the SolidWorks User Interface

Tip

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.

Creating the
Toolbar Bitmaps

Consider a custom toolbar with many buttons. The


SldWorks::AddToolbar4 method still requires two images, one small,
one large. For the small bitmap the image for each button must be 16xN
(N= number of button), and for the large bitmap it must be 24xN.

Small Bitmaps Guide:


Single Button

Multiple Buttons

16
pixels

16
16 pixels

16 x Number of Buttons

Large Bitmaps Guide:


Multiple Buttons

Single Button

24
pixels

24

24 pixels
Toolbar Index

282

24 x Number of Buttons

The SldWorks::AddToolbarCommand2 method


assigns each button an index number (zero based,
starting from the far left). This breaks the single
image into intelligent multiple sections, or in our
case, usable automation buttons.

Understanding The Add-in Code

API Fundamentals

Lesson 10
Customizing the SolidWorks User Interface

ToolTip

The SldWorks::AddToolbarCommand2 method


also assigns a tool tip text string that allows
programmers to notify users what functionality
lies beneath each button.

Adding Toolbar
Bitmaps to a
VB.NET Solution

The toolbar button bitmaps must be


included in the project. To create a new
bitmap, right-click on the top level node in
the Solution Explorer. From the Add
menu on the popup, click Add New
Item.... Finally, double-click Bitmap File
from the Add New Item dialog.

Visual Studio.NET opens a new bitmap in the Image Editor. To make


the bitmap the proper size, drag the lower right corner of the bitmap
with the mouse, and watch the status bar to see the pixel dimensions
change.

Note

The add-in wizard creates two sample toolbar bitmaps automatically


and adds them to the solution. The next steps in this case use the wizard
generated bitmaps.

Understanding The Add-in Code

283

Lesson 10

API Fundamentals

Customizing the SolidWorks User Interface

The Bitmap
Handler Class

A utility class named BitmapHandler will load the bitmaps on to


toolbars when they are created. This class is also generated
automatically by the add-in wizard.
In the Solution Explorer window, a file named
BitmapHandler.vb is included in the project. This source code file
contains the definition for the BitmapHandler class.

The Class View


Window

The Class View window is useful for browsing the class definitions in
a project. The class view represents the projects classes in a
hierarchical tree view. Each class node in the tree can be expanded to
view all of its members. A member of a class can then be clicked and
the source code for that member will be displayed in the editor.

29 Show the Class View.


From the View menu, click
Class View.

Expand the class named


BitmapHandler.
This class has three methods.
The method of interest is the
CreateFileFromResourceBitmap method. This method is used to create
a bitmap image that can be used on a toolbar from a bitmap resource
saved in the DLLs assembly manifest.
30 Double-click on a method name.

Double-click on the CreateFileFromResourceBitmap method in the


class view to display the code.
This method extracts the bitmap that is stored in the add-in DLLs
assembly manifest, and then saves it onto the hard disk.
Once it recreates the image, it takes the new file path name and sends it
back to the caller so that it can be added to the custom toolbar.

284

Understanding The Add-in Code

API Fundamentals

Lesson 10
Customizing the SolidWorks User Interface

Note

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.

Adding Toolbars

The method SldWorks::AddToolbar4 creates a custom toolbar and adds


the toolbar name to the View, Toolbars menu in SolidWorks

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.

Understanding The Add-in Code

285

Lesson 10

API Fundamentals

Customizing the SolidWorks User Interface

SldWorks::AddToolbar4
NewToolBarID = SldWorks.AddToolbar4 ( Cookie, Title, smallBitmapImage,
largeBitmapImage, MenuPositionForToolbar, DocumentType )

Output:

NewToolBarID

Toolbar ID for use with other method.

Input:

Cookie

Add-in ID.

Input:

Title

Title of the toolbar.

Input:

smallBitmapImage

Bitmap file to use for the small bitmap for the


toolbar.

Input:

largeBitmapImage

Bitmap file to use for the large bitmap for the


toolbar.

Input:

MenuPositionForToolbar

Not used (SolidWorks always puts toolbar names


in alphabetical order).

Input:

DocumentType

Type of document the toolbar should be displayed


with.

31 Review the AddToolbar method.

Double-click the CustomSwAddin::AddToolbar method from the


Class View.
32 Examine the code in the editor.

The code in this diagram:


I
I
I
I

286

Uses the BitmapHandler class to extract the bitmaps.


The paths for the bitmaps are returned to the caller.
Specifies what document type to create the toolbar for.
Finally, the SldWorks::AddToolbar4 method creates the toolbar
using the paths to the images created by the BitmapHandler object.

Understanding The Add-in Code

API Fundamentals

Lesson 10
Customizing the SolidWorks User Interface

Note

The BitmapHandler object was defined as a variable in the


CustomSwAddin class. It is instantiated in the ConnectToSw method.

Adding Toolbar
Commands

Use the SldWorks::AddToolbarCommand2 to add toolbar commands to


each button on a toolbar. This method also tells SolidWorks what
callback function to use when the button is pressed by the end user.

SldWorks::AddToolbarCommand2
IsToolbarCommandAdded = SldWorks.AddToolbarCommand2 ( Cookie, ToolbarID,
ToolbarIndex, ButtonCallback, ButtonEnableMethod, ToolTip, HintString )

Output:

IsToolbarCommandAdded

TRUE

Input:

Cookie

Add-in ID.

Input:

ToolbarID

Toolbar ID from SldWorks::AddToolbar4.

Input:

ToolbarIndex

0-based index of the bitmap button.

Input:

ButtonCallback

Function called when the user clicks the button.

Input:

ButtonEnableMethod

Function called to set whether or not the button


should be enabled.

Input:

ToolTip

ToolTip for the toolbar button.

Input:

HintString

Text to show in the SolidWorks status bar when the


user moves their mouse over this toolbar button.

Note

if successful, FALSE if unsuccessful.

The ButtonEnableMethod parameter is used to specify another callback


function that can be implemented in the add-in. This is a special
purpose callback function that is used for enabling or disabling a
toolbar button when it is clicked.
33 Review the code that adds the toolbar commands.

Scroll down further in the AddToolbar method to study this code.

Understanding The Add-in Code

287

Lesson 10

API Fundamentals

Customizing the SolidWorks User Interface

34 Examine the toolbar button callbacks.

Expand the UI Callbacks region in the source code file.


Scroll down to review the toolbar callback functions.

Tip

The toolbar enable methods currently return 1. Returning 1 from these


callback methods ensures that the button will still be enabled after it is
clicked.
The following settings can be used with toolbar enable functions:
I

0 - Disabled and dimmed (also called grayed-out.)


1 - Enabled. (default behavior if update function is omitted)

2 - Disabled and pressed in.

3 - Enabled and pressed in.

35 Add code to the toolbar callback methods.

Use the SldWorks::SendMsgToUser method to display the number of


the toolbar button that was clicked by the user.

288

Understanding The Add-in Code

API Fundamentals

Lesson 10
Customizing the SolidWorks User Interface

36 Test the toolbar.


Click Debug, Start from the Visual Studio menu.

SolidWorks starts, and loads the add-in.


Click any of the buttons on the toolbar.

A message box displays the ID of the toolbar button that was pressed.

37 Stop the debugger.

Return to the development environment.

Property Pages

Another benefit of creating an add-in application is


the ability to create custom PropertyManager pages.
The API provides functionality that a programmer
can use to design custom PropertyManager pages.
These custom pages support all of the features and
controls available on the intrinsic PropertyManager
pages in SolidWorks. Custom PropertyManager
pages allow a developer to provide a robust user
interface for an add-in that looks and behaves like
part of SolidWorks software.

PropertyPage
Members

Two interfaces of the SwPublished type library are used when creating
a custom PropertyManager page with the API.
I
I

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

Customizing the SolidWorks User Interface

UserPMPage

Add-In
SldWorks

Add-In

The Add-In calls the


AddPMP method to create
an instance of the
UserPMPage object. The
Add-In passes a pointer
to itself and its
pointer to SolidWorks
so that UserPMPage can
communicate with these
objects.

SldWorks
Group1
Group2
Option1
Option2
Option3

Checkbox1
List1
Selection1
Num1
Combo1

ppage
This class member implements
the PropertyManagerPage2
interface.

handler
This class member implements the
PropertyManagerPage2Handler2
interface.

UserPMPage contains the ppage member.


The ppage member represents the PropertyManagerPage2
interface.
UserPMPage also contains the handler member.
The handler member implements the
PropertyManagerPage2Handler2 interface.
All of the controls that are used on the custom
PropertyManager page are also members of the UserPMPage
class.

PropertyManager
Page2

The PropertyManagerPage2 object provides add-in applications the


ability to display and interact with a PropertyManager page that
supports the look and feel of a SolidWorks PropertyManager. This
object represents the actual page that is displayed to the end user. It
provides the methods needed to add group boxes and controls to the
page, and also to display it.

PropertyManager
Page2Handler2

The PropertyMangerPage2Handler2 is an interface that must be


implemented to interact with a programmer defined
PropertyManagerPage2 object. This interface handles all of the events
that are sent from the custom PropertyManager page.
The PropertyManagerPage2Handler2 interface is instantiated before
the page is created. After it is created, its pointer is passed to the
SldWorks::CreatePropertyManagerPage method. By passing the
pointer to this method, SolidWorks becomes aware that these two
objects work together to handle the events sent from the end user when
they are interacting with the page.
The wizard generated project creates a class member of the
UserPMPPage object named PMPageHandler. This object implements
the PropertyManagerPage2Handler2 interface that is defined in the
SwPublished type library.

290

Property Pages

API Fundamentals

Lesson 10
Customizing the SolidWorks User Interface

All of the methods of the PropertyManagerPage2Handler2 interface


must be implemented in the PMPageHandler object or the project will
not compile.
Creating a
PropertyManager
Page

Create a new PropertyManager page with the method


SldWorks::CreatePropertyManagerPage.

SldWorks::CreatePropertyManagerPage
retval = SldWorks.CreatePropertyManagerPage ( title, Options, handler, errors )

Output:

retval

Pointer to the newly created PropertyManager page.

Input:

title

Title of the page.

Input:

Options

Options as defined in
swPropertyManagerPageOptions_e.

Input:

handler

Pointer to the event handler for this page.

Output:

errors

Status of the creation as defined in


swPropertyManagerPageStatus_e.
Display the page using PropertyManagerPage2::Show.

PropertyManagerPage2::Show
retval = PropertyManagerPage2.Show ( )

Output:

retval

Status of page creation.


0 = success, other values = failure.

38 Review the code to add the property page.


From the Class View window, double-click on the

CustomSwAddin::AddPMP method.
The code for the AddPMP function is displayed in the code editor.

This function creates a new instance of the UserPMPPage object and


calls its Init method.
Right-click on the ppage.Init function call and choose
Go To Definition... from the popup menu.

Property Pages

291

Lesson 10

API Fundamentals

Customizing the SolidWorks User Interface

39 Study the UserPMPPage::Init function.

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.

40 Examine the code to create the page.

Right-click on the CreatePage function and choose


Go To Definition from the popup menu.
A new handler object is created and the handler.Init method is called.
This method passes the add-in and the SolidWorks pointers to the
handler object so that they can also communicate.
Finally the PropertyManager page is created and the handler object is
passed to it.

Property Page
Groups and
Controls

292

The next step to create the PropertyManager


page is to add group boxes that organize the
controls on the page.The diagram shows
two custom group boxes. One is expanded,
and the other is collapsed.

Property Page Groups and Controls

API Fundamentals

Lesson 10
Customizing the SolidWorks User Interface

Adding Group
Boxes

Use the API method PropertyManagerPage2::AddGroupBox to add a


group box to a custom PropertyManager page.

PropertyManagerPage2::AddGroupBox
retval = PropertyManagerPage2.AddGroupBox ( Id, Caption, Options )

Output:

retval

Pointer to the newly created group box.

Input:

Id

Input:

Caption

Title of the group box.

Input:

Options

Options as defined in swAddGroupBoxOptions_e.

Group and control


IDs

Resource ID of the group box.

When a property page is constructed, every group and control that is


created on the page is given a unique ID. A Select Case statement can
be used in the control event handlers for that page to determine what
control was interacted with by the end user of the add-in. The group
and the control IDs are created and managed by the developer of the
add-in. They are long integer values that are assigned to these objects at
design time.
41 Examine the code to add the group boxes to the page.
Use the Class View to display the UserPMPPage::AddControls

function in the editor.


After three local variables are declared, two group boxes are
constructed using the PropertyManagerPage2::AddGroupBox method

Property Page Groups and Controls

293

Lesson 10

API Fundamentals

Customizing the SolidWorks User Interface

42 Add code to a group box event handler.


Use the Class View to display the PMPageHandler::OnGroupExpand

method.
Add the following code which uses the group box ID to determine
which group box on the PropertyManager page was expanded.

Adding Controls

Use PropertyManagerPageGroup::AddControl to add controls to a


PropertyManager page.

PropertyManagerPageGroup::AddControl
retval = PropertyManagerPage2.AddControl ( Id, ControlType, Caption, LeftAlign,
Options, Tip )

Output:

retval

Pointer to the newly created


PropertyManagePageControl.

Input:

Id

Resource ID of this control.

Input:

ControlType

Type of control as defined in


swPropertyManagerPageControlType_e.

Input:

Caption

Caption of this control.

Input:

LeftAlign

Left-align property of this control as defined in


swPropertyManagerPageControlLeftAlign_e.

Input:

Options

Options as defined in swAddControlOptions_e.

Input:

Tip

ToolTip for this control.

294

Property Page Groups and Controls

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
GroupBox

.AddControl, .Expanded, .Visible

Button

.Caption

Checkbox

.Caption, .Checked

Combobox

.AddItems, .Clear, .CurrentSelection,


.Height, .ItemText, .Style

Listbox

.AddItems, .Clear, .CurrentSelection


.Height, .ItemText, .Style

Label

.Caption
.Style

NumberBox

.SetRange
.Value

Option

.Checked
.Style

SelectionBox

.GetSelectionFocus
.SetSelectionFilters
.SetSelectionFocus
.Callout
.Height
.Mark
.SetCalloutLabel
.SetSelectionColor
.SingleEntityOnly
.Style

TextBox

.Text

BitmapButton

.Checked
.IsCheckable
.SetBitmaps
.SetBitmapsByName
.SetStandardBitmaps

Checkable
BitmapButton

Tip

The AddControl method is also exposed on the


PropertyManagerPage2 interface. Controls can be added directly to
the PropertyManager page without creating a group box.

Property Page Groups and Controls

295

Lesson 10

API Fundamentals

Customizing the SolidWorks User Interface

43 Return to the AddControls method.


Use the Class View to return to the UserPMPPage::AddControls

method.
Scroll down to examine the code for adding the controls to the group
boxes.
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.

44 Scroll down further.

Three more option controls are created on the group box.


Take note that each option control is assigned an ID.

296

Property Page Groups and Controls

API Fundamentals

Lesson 10
Customizing the SolidWorks User Interface

45 Modify the OnOptionCheck event handler.


Use the Class View window to display the code for the

PMPPageHandler::OnOptionCheck event handler.


Add the following code to this event handler.

Adding Picture
Labels to Controls

Use the PropertyManagerPageControl:: SetStandardPictureLabel to


display SolidWorks defined picture labels on PropertyManager page
controls. The standard picture labels are described in the SwConst type
library in the swControlBitmapLableType_e enumeration.

Tip

To add a custom bitmap to a PropertyManager page control, use the


PropertyManagerPageControl::SetPictureLabelByName method.
46 Add a new control to the PropertyManager page.
Find the UserPMPPage object in the Class View.

Double-click on the checkbox1 member of the class.


The declarations of all of the PropertyManager page controls are
displayed in the editor.

Property Page Groups and Controls

297

Lesson 10

API Fundamentals

Customizing the SolidWorks User Interface

47 Add a new control variable.

Add code to declare a new number box control variable.

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.
48 Add a new control ID.

Scroll down to the definitions of the control IDs.


Add the following variable to define the new number box control ID.

298

Property Page Groups and Controls

API Fundamentals

Lesson 10
Customizing the SolidWorks User Interface

49 Add the number box control.


Use the Class View to view the UserPMPPage::AddControls method

Add the code to create the number box with a picture label.

Removing
Menus and
Toolbars

When an add-in is unloaded from SolidWorks, the


SwAddin::DisconnectFromSW method is called. This method is used to
remove any custom user interface items that were created by the add-in.
It is also used to destroy other resources used by the add-in.

SwAddin::DisconnectFromSW
IsDisconnected = SwAddin.DisconnectFromSW ( )

Output:

IsDisconnected

TRUE

if the add-in disconnected successfully, FALSE if

not.
Use SldWorks::RemoveMenu to remove any custom menus created by
the add-in.
SldWorks::RemoveMenu
retval = SldWorks.RemoveMenu ( DocType, MenuItemString, CallbackFcnAndModule)

Output:

retval

TRUE

Input:

DocType

Document type as defined in swDocumentTypes_e .

Input:

MenuItemString

Menu string (for example,


submenuString@menuString).

Input:

CallbackFcnAndModule

Callback function and module for this menu item .

Removing Menus and Toolbars

if the menu item was removed successfully,


FALSE if not.

299

Lesson 10

API Fundamentals

Customizing the SolidWorks User Interface

Use SldWorks::RemoveToolbar2 to remove any toolbars that the add-in


created.
SldWorks::RemoveToolbar2
Status = SldWorks.RemoveToolbar2 ( Cookie, ToolbarID )

Output:

Status

TRUE

if the toolbar was removed successfully, FALSE if

not.
Input:

Cookie

Add-in ID.

Input:

ToolbarID

Toolbar ID.

50 Display the DisconnectFromSW method.


Use the Class View window to display the

CustomSwAddin::DisconnectFromSW method.
Right-click on the RemoveMenus function and click
Go To Definition.

51 Review the code.

The code in this function removes all of the menus that were created for
each SolidWorks document type.

Tip

Use the SldWorks::RemoveMenu method to remove an entire menu and


all of its menu items. It is not necessary to remove the menu items
individually.

300

Removing Menus and Toolbars

API Fundamentals

Lesson 10
Customizing the SolidWorks User Interface

52 Review the code that removes the toolbar.


Use the Class View to display the code for the

CustomSWAddin::RemoveToolbar method.
This method removes the toolbar when the add-in is unloaded.

53 Test the add-In.

Debug the add-in.


From the CustomSwAddin menu, click
Create Cube....
After the new part is created, click Show PMP
from the CustomSwAddin menu.
The new number box control with a picture
label is now visible under the three option
buttons.
54 Test the group box event
handler.

Expand the second group box on


the PropertyManager page.
A message is displayed that
specifies which group box was
expanded.
Click OK to dismiss the
message.

Removing Menus and Toolbars

301

Lesson 10

API Fundamentals

Customizing the SolidWorks User Interface

55 Click an option.

Click an option button in the


first group box.
A message is displayed that
specifies which option was
clicked.
Click OK to dismiss the
message.
Click OK to dismiss the
PropertyManager page.

56 Unload the add-in.


From the Tools menu, click Add-Ins....

Clear the CustomSwAddin option


Click OK to unload the add-in.

57 Examine the SolidWorks user interface.

The custom menu and toolbar are no longer available.


58 Stop the debugger
Save and close the Visual Basic.NET project.

Other Areas of
Customization

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.

302

Other Areas of Customization

API Fundamentals

Lesson 10
Customizing the SolidWorks User Interface

Custom Pop-up
Menus

Call SldWorks::AddMenuPopupItem2 to add a


menu item to a shortcut menu.
This method will need to be assigned a callback
method so that when it is clicked in the
SolidWorks user interface, the appropriate
callback event is triggered.

Custom
ModelView
Windows

In order to create your own custom model view window, call


ModelViewManager::AddControl.

Other Areas of Customization

303

Lesson 10

API Fundamentals

Customizing the SolidWorks User Interface

304

Other Areas of Customization

API Fundamentals

Exercise 16:
Implement a New Menu

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

Procedure

1.
2.
3.
4.
5.
6.

Run the SolidWorks VB.NET Addin Wizard.


Create a Property Page when selecting the add-in options.
Add a new menu item to the custom menu created by the add-in.
Implement the callback method for the new menu item.
The callback method creates an extruded cylinder.
Compile the project and test the new menu item.

305

Exercise 16:

API Fundamentals

Implement a New Menu

Solution

The following lines of code were added to the AddMenus sub program
to add the menus.

Add the following code to the UI Callbacks region.

306

API Fundamentals

Exercise 17:
Implement Toolbar Buttons

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

Procedure

1. Expand the UI Callbacks region.


2. Add code to each toolbar callback to rotate the part in either the x,
y, or z direction.
3. Compile the project and test the toolbars.

307

Exercise 17:
Implement Toolbar Buttons

Solution

308

API Fundamentals

API Fundamentals

Exercise 18:
Implement Controls on a Property Manager Page

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

Procedure

1.
2.
3.
4.
5.

Remove all of the controls from the first group box


Remove second group box
Add a combobox and a button control to the first group box
Implement the OnButtonPress event for the button.
The button click event will traverse all the faces on a body, and
color them according to the color selected in the combobox control.
6. Compile the project and test the custom PropertyManager page.

309

Exercise 18:

API Fundamentals

Implement Controls on a Property Manager Page

Solution

In the #Region "Property Manager Page Controls", add two


control variables and two control IDs for two new controls.

Code for the AddControls sub program.

310

API Fundamentals

Exercise 18:
Implement Controls on a Property Manager Page

New user variable on the PMPageHandler object.

Code for the OnComboboxSelectionChanged event handler.

Code for the OnButtonPress event handler.

311

Exercise 18:
Implement Controls on a Property Manager Page

312

API Fundamentals

API Fundamentals

Lesson 11
Notifications

Upon successful completion of this lesson, you will be able to:


I

Write code that listens and reacts to a SolidWorks notification.

Identify which SolidWorks objects support notifications.

Set up a simple notification in VBA.

Use the add-in wizard to create event handlers for notifications.

Learn how the add-in wizard handles document level event


handlers.

313

Lesson 11
Notifications

314

API Fundamentals

API Fundamentals

Lesson 11
Notifications

Notifications

Certain events in SolidWorks can be listened to and handled by a


client application when the event occurs. This event is called a
notification. With only a few lines of additional programming code,
you can catch SolidWorks notifications and execute API calls when the
event occurs.
The following objects support notifications in SolidWorks:
I
I
I
I
I
I
I

Notifications in
VBA

SldWorks
PartDoc
AssemblyDoc
DrawingDoc
ModelView
FeatMgrView
SwPropertySheet

In order to capture notifications in SolidWorks, use the WithEvents


keyword when declaring objects.
Dim WithEvents swApp As SldWorks.SldWorks

A change occurs in the VBA development environment when the


WithEvents keyword is used to declare an object that supports
notifications. Selecting the object that is declared using the WithEvents
keyword from the Object pull down menu causes the Procedure pull
down menu to be populated with all of the notifications that are
available on this objects interface.
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.
In the diagram below the FileNewNotify notification is selected from
the procedure pull down menu. Consequently, the skeleton notification
handler code is written. When this macro runs, any time a new
document is created in SolidWorks, this notification will be routed to
this handler in the code. This macro then executes the code in this
handler to react to the notification.
Object Pull Down Menu

Notifications

Procedure Pull Down Menu

315

Lesson 11

API Fundamentals

Notifications

Case Study:
Simple
Notification

This case study captures a notification sent by SolidWorks and routes it


to a notification handler in the client application. When the notification
is sent, the client will respond to the end user with a message indicating
exactly what event was triggered.

Note

This example implements an event handler in a macro. Although it may


be useful to do this in a macro, notification event handlers are best
suited to be implemented in an add-in (DLL) application. A case study
later in this lesson covers this technique in detail.
1

Create a new macro.

From the macro toolbar click


2

Save the macro.


From the New Macro dialog box, save the macro as

notifications.swp.
3

The Class Module

Add a class module.


From the Insert menu, click Class Module.

In this example, a class module is used to create an object that contains


a SolidWorks object variable. This class object is created in memory
and stays there until SolidWorks is shut down. If this class object only
had the scope of a macro, it would be destroyed as soon as the macro
exited. This design ensures that the class object will stay alive and
capture SolidWorks events even though the macro exited.
4

Modify code in the class module.

Add the following variable declaration.

Select the swApp variable.

Select swApp from the Object pull down menu.

316

Case Study: Simple Notification

API Fundamentals

Lesson 11
Notifications

Choose a procedure.

Click the down arrow on the Procedure pull down menu.


All of the notifications supported by swApp are in the list.
Keep the default choice, FileOpenNotify.

Review the code for the notification.

The code for the notification handler is appended to the source code.

Add code to the handler.

Add the following line of code within the notifications handler.

Add code to the class module.

Add the following lines of code to the class module.

Case Study: Simple Notification

317

Lesson 11

API Fundamentals

Notifications

10 Change the macro entry code.

Double-click on notifications1 in the Project Explorer.


Make the following changes to the code:

11 Save and run macro.


12 Open existing part.

Open the file named Sample.sldprt.


The following message box should appear:

13 Close the file.

Exit SolidWorks.

Case Study:
Using
Notifications in
.NET

In the previous case study a notification was handled on the SldWorks


application object. Things get a little more complicated when creating
notification handlers for SolidWorks document and model view
objects. Documents and model views are created dynamically by the
end users of SolidWorks. Additional code is required to create and
manage the dynamically created event handler objects. These objects
get created and associated to each document and model view
dynamically created by the end user.
The SolidWorks VB.NET Addin wizard creates all of the code
necessary to attach notification event handlers to the SolidWorks
object. It also generates code to create and manage all of the
dynamically created document event handler objects. This case study
explains how document event handlers are created, how they work, and
how they are destroyed.

318

Case Study: Using Notifications in .NET

API Fundamentals

Lesson 11
Notifications

Create a new Add-in.

Use the SolidWorks VB.NET Addin wizard to create a new add-in.


Name the Add-In DotNetNotifications.
Choose to provide events for all of the SolidWorks object interfaces
that support events.
Clear the CreatePropertyPage option.
Click Finish.

Examine the local variables.

Double-click on the file named DotNetNotifications.VB in the


Solution Explorer.
This will activate the source code file in the editor.
Expand #Region Local

Variables.

The iSwApp variable has been declared using the WithEvents keyword.

Case Study: Using Notifications in .NET

319

Lesson 11

API Fundamentals

Notifications

Examine the ConnectToSW function.


Use the Class View window to display the

DotNetNotifications::ConnectToSW function in the editor.


Scroll down to the AttachEventHandlers function call.
This function is called to create and attach event handlers.
Right-click on this sub program call and choose Go To Definition from
the popup menu.

Review the code.

The first line of code in this sub program calls a function that attaches
the notifications to the SolidWorks application object.
Right-click on the AttachSWEvents call and click Go To Definition
from the popup menu.

Examine the code.

The AttachSWEvents function attaches notification event handlers to


four different notifications sent by the SolidWorks application object.

320

Case Study: Using Notifications in .NET

API Fundamentals

Lesson 11
Notifications

The AddHandler
Keyword

The AddHandler keyword tells the add-in application to listen for a


specific notification being sent from the SolidWorks application. The
first parameter is the name of the SolidWorks notification that the
add-in is to handle.

The AddressOf
Keyword

The second parameter is the memory address of the add-in


implemented delegate function that will be called when the notification
is sent from SolidWorks. When the DotNetNotifications class is
instantiated in memory, the delegate function will be located at a
specific memory address on this object. The AddressOf keyword
returns this memory address and passes it as the second parameter of
the AddHandler function. Anytime the notification is sent from
SolidWorks, the add-in routes the notification to the delegate function
located at this memory address.

Note

These keywords are not used in VBA.


6

Navigate to a delegate function.

In the AttachSWEvents function, scroll to the third AddHandler


statement.
Right-click on the second parameter - Me.SldWorks_FileNewNotify2
Click Go To Definition from the popup menu.

Add the code to the delegate function.

Add the following code to the FileNewNotify2 delegate function.

Debug the project and load the DLL.

From the SolidWorks File menu, click New... and create a new part
document. The delegate function is triggered and displays the
messages.

Case Study: Using Notifications in .NET

321

Lesson 11

API Fundamentals

Notifications

Stop the debugger.

Return to the development environment.


The Event Handler
Classes

On the add-in wizard options page, all of the Addin Events options
were selected.

This caused the wizard to create five classes


that are used to wrap the notification delegate
functions for several SolidWorks objects that
support notifications. The highlighted objects
in the Class View are the classes created by the
wizard that wrap the delegate functions for the
notifications.
Three of these classes support the notifications
sent from the specific SolidWorks document
types.
I
I
I

PartEventHandler
AssemblyEventHandler
DrawingEventHandler

Another class is a wrapper for a SolidWorks model view object.


I

DocView

Finally, a base class for all of the document level event handlers is
created.
I

322

DocumentEventHandler

Case Study: Using Notifications in .NET

API Fundamentals

Lesson 11
Notifications

The Document
Event Handler
Class

The DocumentEventHandler is the base class of the PartEventHandler,


AssemblyEventHandler, and the DrawingEventHandler. The
DocumentEventHandler is also used to manage all of the DocView
event handler objects that are created for each model view on each
document.

.
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.

Case Study: Using Notifications in .NET

323

Lesson 11

API Fundamentals

Notifications

Every document that is open in the SolidWorks session will have an


associative event handler object created. When it is created, it is added
to the openDocs hash table. This hash tables contents can grow quite
large, especially when working in a large assembly. When one of the
open documents is destroyed, the hash table is searched for its
associated event handler object so that it can also be destroyed. If a data
structure were used that did not have high performance data retrieval
capabilities, the add-ins performance could deteriorate.
The openDocs hash table manages all of the DocumentEventHandlers.

Attaching the
DocumentEvent
Handlers

There are two occurrences where an add-in will create document event
handlers.
I

When the add-in loads, wizard generated code in the


SwAddin::AttachEventHanders function is used to traverse all of
the open documents to create and attach event handler objects to
them.
The SldWorks::DocumentLoadNotify notification is overridden to
create and attach new event handlers on new or opened documents.

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.
10 Return to the AttachEventHandlers function.
Use the Class View window to display the code for the

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

Case Study: Using Notifications in .NET

API Fundamentals

Lesson 11
Notifications

11 Go to the definition of AttachModelDocEventHandler.

Right-click on the AttachModelDocEventHandler function call, and


click Go To Definition from the popup menu.

12 Study the code.

This code uses a Select Case statement to determine what type of


document is passed to this function.
When the type is determined, the appropriate document event handler
class is created.
Two methods are called on the DocumentEventHandler class to:
I
I

Initialize the object.


Attach the event handlers to its corresponding document.

After these methods are called, the DocumentEventHandler is added to


the add-ins openDocs hash table member.

Case Study: Using Notifications in .NET

325

Lesson 11

API Fundamentals

Notifications

Inheritance

The Visual Basic.NET programming language supports a feature called


inheritance. Inheritance allows classes to inherit functionality from a
base class. This eliminates having to completely redefine the base class
functionality in classes that are derived from it.

Polymorphism

Visual Basic.NET also supports a feature called polymorphism.


Polymorphism is the ability to implement base class functions
differently in the classes that are derived from it. The functions in the
derived classes are identically named, but can be implemented quite
differently.
There are three classes derived from the DocumentEventHandler base
class. They are:
I
I
I

PartEventHandler
AssemblyEventHandler
DrawingEventHandler

The DocumentEventHandler base class has three functions that are


declared with the Overridable keyword. The code in these Overridable
functions will be overridden in the derived classes.
The three overridable functions are:
I
I
I

Init
AttachEventHandlers
DetachEventHandlers

Polymorphism is demonstrated by overriding these functions


differently in the derived classes.
Note

These programming features are not available in VBA or Visual Basic


6.0.
13 Explore the DocumentEventHandler class.
In the Class View window, double-click on the

DocumentEventHandlerClass to display its class definition in the


editor.
Examine the first three Overrideable functions.
None of these function prototypes have implementation code. These
functions are overridden in the classes that are derived from this base
class.

326

Case Study: Using Notifications in .NET

API Fundamentals

Lesson 11
Notifications

14 Examine the ConnectModelViews method.

Scroll to the ConnectModelViews method in the


DocumentEventHandler class.
This method traverses all of the model views in the document.
Every time a new model view is encountered, a new DocView event
handler class is instantiated.
Two methods are called on the DocView class to:
I
I

Initialize the object.


Attach the event handlers to the model views.

Finally the new ModelView pointer and its corresponding DocView


event handler class are added to the DocumentEventHandlers
openModelViews hash table.

Case Study: Using Notifications in .NET

327

Lesson 11

API Fundamentals

Notifications

The Derived Event


Handler Classes

The next part of this case study examines the three classes derived from
the DocumentEventHandler class.
I
I
I

PartEventHandler
AssemblyEventHandler
DrawingEventHandler

15 Display the code for the PartEventHandler class.


Double-click the PartEventHandler class in the Class View window.

This class declares a PartDoc variable with the WithEvents keyword.


It overrides the three overridable functions declared in the base class.
It also implements two notification delegate functions.

16 Add code

Add the following code to the PartDoc_NewSelectionNotify delegate


function.
When anything is selected in any SolidWorks part document, this
message will be displayed.

328

Case Study: Using Notifications in .NET

API Fundamentals

Lesson 11
Notifications

17 Display the code for the AssemblyEventHandler class.


Double-click the AssemblyEventHandler class in the Class View

window.
This class declares an AssemblyDoc variable with the WithEvents
keyword.
It overrides the three overridable functions declared in the base class.
It also implements two notification delegate functions.

18 Add code

Add the highlighted code to the AssemblyDoc_NewSelectionNotify


delegate function.
When anything is selected in any assembly document, this message will
be displayed.

Case Study: Using Notifications in .NET

329

Lesson 11

API Fundamentals

Notifications

19 Display the code for the DrawingEventHandler class.


Double-click the DrawingEventHandler class in the Class View

window.
This class declares a DrawingDoc variable with the WithEvents
keyword.
It overrides the three overridable functions declared in the base class.
It also implements two notification delegate functions.

20 Add code

Add the highlighted code to the DrawingDoc_NewSelectionNotify


delegate function.
When anything is selected in any drawing document, this message will
be displayed.

The DocView
Class

330

The DocView class is used to implement notification event handlers for


model views on all types of SolidWorks documents. The DocView
class is not derived from the DocumentEventHandler class.
SolidWorks model view objects are supported identically across all
model document types. Therefore, class derivation and polymorphism
are not necessary for this class definition.

Case Study: Using Notifications in .NET

API Fundamentals

Lesson 11
Notifications

21 Display the code for the DocView class.


Double-click the DocView class in the Class View window.

22 Add code.

Add the following code to the ModelView_RepaintNotify delegate.

23 Debug and test the Add-In.


From the Debug menu, click Start.
24 Create a new part document.
Click OK whenever the ModelView_RepaintNotify notification displays

its message.
Click OK when the SldWorks_FileNewNotify2 notification displays its
message.

Note

Several ModelView_RepaintNotify events are fired when opening a


new document.

Case Study: Using Notifications in .NET

331

Lesson 11

API Fundamentals

Notifications

25 Create a new assembly.


Click OK whenever the ModelView_RepaintNotify notification displays

its message.
Click OK when the SldWorks_FileNewNotify2 notification displays its
message.

26 Create a new drawing.


Click OK whenever the ModelView_RepaintNotify notification displays

its message.
Click OK when the SldWorks_FileNewNotify2 notification displays its
message.

332

Case Study: Using Notifications in .NET

API Fundamentals

Lesson 11
Notifications

27 Switch back to the part document.


Use the Ctrl + Tab keys to make the part document active.

Select the Front Plane from the FeatureManager design tree.


The PartDoc_NewSelectionNotify notification is sent to the add-in, and
the appropriate message is displayed to the user.
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.

28 Return to the code.

Return to the development environment.


From the Debug menu, click Stop Debugging.
Detaching the
Document and
Model View Event
Handlers

Whenever this add-in is loaded into SolidWorks, many document and


model view event handling objects can be created and added to the
hash tables. Several methods on all of the event handling objects are
used to detach and destroy them when their corresponding document is
destroyed.
Every document event handler that the add-in wizard created
implements an event handler for the DestroyNotify notification. When
this notification is sent, it starts a chain reaction through all of the
relative event handler classes created by the document. This chain
reaction removes and destroys any event handlers objects and hash
table entries that are associated to the document being destroyed.

Case Study: Using Notifications in .NET

333

Lesson 11

API Fundamentals

Notifications

29 Examine the DestroyNotify event handler.

Double-click on the PartEventHandler::PartDoc_DestroyNotify


member in the Class View window.
The implementation code calls the DetachEventHandlers - a method on
the PartEventHandler object.
Right-click on this method and choose Go To Definition from the
popup menu.

30 Review the DetachEventHandlers method.

This method calls the RemoveHandler statement on all of the


notifications that this event handler object supported.
Afterwards, it calls the DisconnectModelViews method on the base
class to remove the model view event handlers and hash table entries.
Once all of the document and model view event handlers are removed,
the document object can be removed from the add-in objects openDocs
hash table.
Right-click on the DisconnectModelViews method and choose
Go To Definition from the popup menu.

31 Examine the DisconnectModelViews method.

This method traverses all of the model views in the openModelViews


hash table entries.
Every time a model view is encountered:
I
I

334

The event handlers are removed from the model view.


The model views hash table entries are removed.

Case Study: Using Notifications in .NET

API Fundamentals

Lesson 11
Notifications

Note

The openModelViews hash table entries are removed by two separate


helper functions. The PartEventHandler::DetachEventHandlers and
DocumentEventHandler::DetachModelViewEventHandler helper
functions are used to remove the DocView object pointers and their
corresponding keys from the hash table.
32 Create a break point and debug the code.

Double-click on the PartEventHandler::PartDoc_DestroyNotifiy


method in the Class View.
Add a break point on this notification event handler.
Debug the application.
When SolidWorks starts, create a new part document.

33 Close the new document in SolidWorks.


Use the F10 key to step to the next line of code.

Use the F11 key to step into the DetachEventHandlers method.

34 Continue stepping into the code.


Use the F10 key to step to the DisconnectModelViews function call.

Press the F11 key to step into the function.

35 Continue debugging.
Continue pressing the F10 until you reach the DetachEventHandlers

method.
Press the F11 key to step into this method.

Case Study: Using Notifications in .NET

335

Lesson 11

API Fundamentals

Notifications

36 Step into the helper functions.


Continue pressing the F10 key until you reach the

DetachModelViewEventHandler function.
The event handlers are now removed from the model view.
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.

38 Step to the next line of code.


Press the F10 key to remove the key from the openModelViews hash

table.
Continue pressing the F10 key to exit this function and return to the
PartEventHandler::DetachEventHandlers function

336

Case Study: Using Notifications in .NET

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.
Press F11 to step into the next method.

40 Step through to the end of this method.

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

Anytime SolidWorks is shutdown the SldWorks notifications must also


be removed. There is a method on the add-in class that is used to
remove event handlers created for any SolidWorks application events.
41 Insert a breakpoint.

Click the DotNetNotifications::DisconnectFromSW method in the


Class View.
Insert a break point on the DetachEventHandlers method call.

Case Study: Using Notifications in .NET

337

Lesson 11

API Fundamentals

Notifications

42 Continue Debugging.

Return to SolidWorks and exit the application


The debugger will halt on the break point.
Press the F11 key to step into the code.

43 Examine the code.

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.

44 Continue debugging.
Use the F10 key to step through this code and return to the originating

caller of this function.

338

Case Study: Using Notifications in .NET

API Fundamentals

Lesson 11
Notifications

45 Complete debugging.

The code returns back to the DetachEventHandler sub program.


The rest of the code in this function is used to destroy any remaining
open documents in the SolidWorks session.
Press the F10 key to step through the rest of this sub program.
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.

46 Close the programming project.

When the DisconnectFromSW function exits, the debugger stops


because SolidWorks has terminated and the add-in has unloaded.

Case Study: Using Notifications in .NET

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
ActiveDocChangeNotify

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.

ActiveModelDocChangeNotify

Post-notifies the user program when the active ModelDoc object


has changed.

BeginTranslationNotify

Notifies a client when a file is about to be translated to


another 3D file format.

DestroyNotify

Pre-notifies the user program when the application is about to be


destroyed.

DocumentConversionNotify

This event is fired when a SolidWorks document is opened whose


version is older than the version of SolidWorks being used.

DocumentLoadNotify

Post-notifies the user program when a document is loaded

EndTranslationNotify

Notifies a client after a file has been translated to another 3D


file format.

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

Post-notifies the user program when an existing file has been


opened. SldWorks::GetOpenDocumentByName can then be used with
FileName to get a pointer to the newly opened document.

FileOpenNotify2

This event is very similar to FileOpenNotify. The difference is


that the Event is fired later in the process than the original
event, so that if users respond to the event by opening a new
part, NewDocument, NewPart, NewAssembly or NewDrawing2 will be
successful.

FileOpenPostNotify

Post-notifies a client when a file has been opened.

FileOpenPreNotify

Pre-notifies a client when a file is opened.

LightSheetCreateNotify

This event will be fired when a lighting sheet has been created.

NonNativeFileOpenNotify

This event will be fired when non-native SolidWorks files are


opened. The file types handled currently include files with the
following extensions: .dxf, .dwg, .igs, .sat, .step, .vda, .wrl,
and .dll.

OnIdleNotify

Notifies the client when the application is sitting idle.

PromptForFilenameNotify

This event is generated when a dependent document is missing from


the file being opened.

PropertySheetCreateNotify

Notifies the user program when an exported SWPropertySheet is


being created so that the application can add pages to it.

ReferenceNotFoundNotify

This event notifies the user program before SolidWorks displays a


dialog box prompting the user to browse for the file.

340

Case Study: Using Notifications in .NET

API Fundamentals

Lesson 11
Notifications

PartDoc Events
ActiveConfigChangeNotify

Pre-notifies the client program when the configuration has


been changed

ActiveConfigChangePostNotify

Post-notifies the client program when the configuration has


been changed.

AddCustomPropertyNotify

Notifies the client that a custom property has been added


to the part document.

AddItemNotify

Notifies the client that an Item has been added to the part
document.

BodyVisibleChangeNotify

Notifies the client when a body is made visible or


invisible in the part document.

ChangeCustomPropertyNotify

Notifies the client when a custom properties value is


changed.

DeleteCustomPropertyNotify

Notifies the client that a custom property has been deleted


from the part document.

DeleteItemNotify

Notifies the client when an item has been deleted from the
part document.

DeleteSelectionPreNotify

Pre-notifies the client that the selection is about to be


deleted.

DestroyNotify

Notifies the client that the part document is being


destroyed.

DimensionChangeNotify

Notifies the client when ever a dimension value is changed


on the part document.

DynamicHighlightNotify

Notifies the client when ever the dynamically highlighted


entity changes.

FeatureEditPreNotify

Pre-notifies the client when a feature is being edited.

FeatureManagerTreeRebuildNotify

Notifies the client whenever the FeatureManager design tree


is rebuilt.

FeatureSketchEditPreNotify

Pre- notifies the client when a sketch is being edited in


the part document.

FileReloadCancelNotify

Notifies the client when the file reload has been canceled
by the user of the part document.

FileReloadNotify

Notifies the client when a part document is reloaded.

FileReloadPreNotify

Pre-notifies the client when a part document is reloaded.

FileSaveAsNotify
FileSaveAsNotify2

Notifies the client when a the part document is being saved


using the save as dialog.

FileSaveNotify

Notifies the client when a file is saved.

FileSavePostCancelNotify

Post-notifies a client when a file save has been canceled.

FileSavePostNotify

Post-notifies a client when a file is saved.

LightingDialogCreateNotify

Notifies the client when the create light dialog is


displayed.

LoadFromStorageNotify

Post-Notifies the user program when it is safe to load data


from third-party storage.

Case Study: Using Notifications in .NET

341

Lesson 11

API Fundamentals

Notifications

PartDoc Events
LoadFromStorageStoreNotify

Post-notifies the user program when it is safe to load data


from third-party storage

ModifyNotify

Notifies the client program when the document made dirty.

NewSelectionNotify

Notifies the client when the selection list changes.

RegenNotify

Pre-Notifies the client when the part is about to be


rebuilt.

RegenPostNotify
RegenPostNotify2

Post-Notifies the client after the part is rebuilt.

RenameItemNotify

Notifies the client when a feature has been renamed in the


FeatureManager design tree.

SaveToStorageNotify

Post-notifies the user program when it is safe to save data


to third-party storage.

SaveToStorageStoreNotify

Post-notifies the user program when it is safe to save data


to third-party storage.

ViewNewNotify
ViewNewNotify2

Notifies the client when a new view window is created of


the part document.

342

Case Study: Using Notifications in .NET

API Fundamentals

Lesson 11
Notifications

AssemblyDoc Events
ActiveConfigChangeNotify

Pre-notifies the client program when the configuration is


changed.

ActiveConfigChangePostNotify

Post-notifies the client program when the configuration has


been changed.

AddCustomPropertyNotify

Notifies the client that a custom property has been added


to the part document.

AddItemNotify

Notifies the client that an Item has been added to the part
document.

BeginInContextEditNotify

Notifies the client that component or subassembly is about


to be edited in the assembly.

BodyVisibleChangeNotify

Notifies the client when a body is made visible or


invisible in the part document.

ChangeCustomPropertyNotify

Notifies the client when a custom properties value is


changed.

ComponentMoveNotify

Notifies the client when a component is moved in the


assembly.

ComponentStateChangedNotify
ComponentStateChangedNotify2

Notifies the client when the state of the component has


changed.

ComponentVisibleChangeNotify

Notifies the client when a components visibility has


changed.

DeleteCustomPropertyNotify

Notifies the client that a custom property has been deleted


from the part document.

DeleteItemNotify

Notifies the client when an item has been deleted from the
part document.

DeleteSelectionPreNotify

Pre-notifies the client that the selection is about to be


deleted.

DestroyNotify

Notifies the client that the part document is being


destroyed.

EndInContextEditNotify

Notifies the client that the user is done editing a part in


the assembly.

FeatureEditPreNotify

Pre-notifies the client when a feature is being edited.

FeatureManagerTreeRebuildNotify

Notifies the client whenever the FeatureManager design tree


is rebuilt.

FeatureSketchEditPreNotify

Pre-notifies the client when a sketch is being edited in


the part document.

FileDropNotify

Post-notifies a client when a file is being dropped into


the assembly from another application.

FileDropPreNotify

Pre-notifies a client when a file is being dropped into the


assembly from another application.

FileReloadNotify

Notifies the client when a part document is reloaded.

FileReloadPreNotify

Pre-notifies the client when a part document is reloaded.

FileSaveAsNotify
FileSaveAsNotify2

Notifies the client when a the part document is being saved


using the save as dialog.

Case Study: Using Notifications in .NET

343

Lesson 11

API Fundamentals

Notifications

AssemblyDoc Events
FileSaveNotify

Notifies the client when a file is saved.

FileSavePostNotify

Post-notifies a client when a file is saved.

InterferenceNotify

Notifies the client when interference is found when moving


components in the assembly.

LightingDialogCreateNotify

Notifies the client when the create light dialog is


displayed.

LoadFromStorageNotify

Post-Notifies the user program when it is safe to load data


from third-party storage.

LoadFromStorageStoreNotify

Post-notifies the user program when it is safe to load data


from third-party storage

ModifyNotify

Notifies the client program when the document made dirty.

NewSelectionNotify

Notifies the client when the selection list changes.

RegenNotify

Pre-Notifies the client when the part is about to be


rebuilt.

RegenPostNotify

Post-Notifies the client after the part is rebuilt.

RenameItemNotify

Notifies the client when a feature has been renamed in the


FeatureManager design tree.

SaveToStorageNotify

Post-notifies the user program when it is safe to save data


to third-party storage.

SaveToStorageStoreNotify

Post-notifies the user program when it is safe to save data


to third-party storage.

ViewNewNotify
ViewNewNotify2

Notifies the client when a new view window is created of


the part document.

DrawingDoc Events
ActiveConfigChangeNotify

Pre-notifies the client program when the configuration is


changed.

ActiveConfigChangePostNotify

Post-notifies the client program when the configuration has


been changed.

AddCustomPropertyNotify

Notifies the client that a custom property has been added to


the part document.

AddItemNotify

Notifies the client that an Item has been added to the part
document.

ChangeCustomPropertyNotify

Notifies the client when a custom properties value is


changed.

DeleteCustomPropertyNotify

Notifies the client that a custom property has been deleted


from the part document.

DeleteItemNotify

Notifies the client when an item has been deleted from the
part document.

DeleteSelectionPreNotify

Pre-notifies the client that the selection is about to be


deleted.

344

Case Study: Using Notifications in .NET

API Fundamentals

Lesson 11
Notifications

DrawingDoc Events
DestroyNotify

Notifies the client that the part document is being


destroyed.

EndInContextEditNotify

Notifies the client that the user is done editing a part in


the assembly.

FeatureManagerTreeRebuildNotify

Notifies the client whenever the FeatureManager design tree


is rebuilt.

FileReloadNotify

Notifies the client when a part document is reloaded.

FileReloadPreNotify

Pre-notifies the client when a part document is reloaded.

FileSaveAsNotify
FileSaveAsNotify2

Notifies the client when a the part document is being saved


using the save as dialog.

FileSaveNotify

Notifies the client when a file is saved.

FileSavePostNotify

Post-notifies a client when a file is saved.

LoadFromStorageNotify

Post-Notifies the user program when it is safe to load data


from third-party storage.

LoadFromStorageStoreNotify

Post-notifies the user program when it is safe to load data


from third-party storage

ModifyNotify

Notifies the client program when the document made dirty.

NewSelectionNotify

Notifies the client when the selection list changes.

RegenNotify

Pre-Notifies the client when the part is about to be rebuilt.

RegenPostNotify

Post-Notifies the client after the part is rebuilt.

RenameItemNotify

Notifies the client when a feature has been renamed in the


FeatureManager design tree.

SaveToStorageNotify

Post-notifies the user program when it is safe to save data


to third-party storage.

SaveToStorageStoreNotify

Post-notifies the user program when it is safe to save data


to third-party storage.

ViewNewNotify
ViewNewNotify2

Notifies the client when a new view window is created of the


part document.

ModelView Events
BufferSwapNotify

This notification is sent from the ModelView immediately


BEFORE the buffers are swapped when rendering shaded
graphics in OpenGL.

DestroyNotify
DestroyNotify2

Pre-notifies the user program when a view is about to be


destroyed.

RepaintNotify

Pre-notifies the user program when a view is about to be


repainted and returns the paint type.

RepaintPostNotify

Post-notifies the user program once a view has been


repainted.

ViewChangeNotify

Post-notifies the user program when a view is altered.

Case Study: Using Notifications in .NET

345

Lesson 11

API Fundamentals

Notifications

FeatMgrView Events
ActivateNotify

Post-notifies the user program once a FeatureManager design


tree view is activated and returns the view handle.

DeactivateNotify

Post-notifies the user program once a FeatureManager design


tree view is deactivated and returns the view handle.

DestroyNotify

Pre-notifies the user program when a FeatureManager design


tree view is about to be destroyed and returns the view
handle.

SWPropertySheet Events
DestroyNotify

This notification is sent when the property sheet is in the


process of being destroyed.

HelpNotify

This notification is sent when the Help button is clicked


in the property sheet.

346

Case Study: Using Notifications in .NET

API Fundamentals

Exercise 19:
Handling Events Using the Add-in Wizard

Exercise 19:
Handling
Events Using
the Add-in
Wizard

Objective

A common use of event handlers is to eliminate user input when


automating a process. This exercise demonstrates how to eliminate the
missing reference dialog that appears when a file is missing from an
assembly. By eliminating the dialog, the add-in can continue without
any manual intervention from an end user to replace the missing file.
For this exercise, create an add-in application that listens to the
SldWorks::ReferenceNotFoundNotify notification. When this event is
triggered, replace the missing part in the supplied assembly with a new
one, with out halting the execution of the code. This event handler uses
another method that was designed to specifically for this purpose:
SldWorks::SetMissingReferencePathName is used to replace the
missing referenced file with another.

Procedure

1. Open the UJ_for_INT.SLDASM and notice the dialog box for


the missing reference appears.
2. Choose not to replace the file and close the assembly.
3. Run the SolidWorks VB.NET Addin wizard.
4. For the add-in event options, choose to create event handlers for
SldWorks.
5. Implement the ReferenceNotFoundNotify event handler.
6. Compile the project and test the notification event handler on the
supplied assembly.

347

Exercise 19:

API Fundamentals

Handling Events Using the Add-in Wizard

Solution

Navigate to the AttachSWEvents function and add the code to attach the
event handler.

Navigate to the DetachSWEvents function and add the code to remove


the handler.

In the Event Callbacks region, add the code to implement the


notifcation event handler.

348

API Fundamentals

Appendix

The examples in this appendix highlight additional ways of using the


SolidWorks API for building productivity tools. Although the concepts
used to build these applications may be more advanced, we have
provided them as a resource for your future development needs.
I

Macro Feature

Batch Conversion 1

Batch Conversion 2

Assembly Traversal

Custom Model View

349

API Fundamentals

Macro Feature

Module:
CounterBore

The MacroFeature or "COM" Feature allows the programmer to create


their own custom features in the SolidWorks.'
In this example we are creating a CounterBore feature that allows the
user to enter a diameter and a depth of a counter bore. When the user
accepts the values, the OnClose handler for the PropertyManager page
creates a Macro feature in the FeatureManager. The user at any time
can right-click on the new Macro feature and change the values, accept
them, and the feature will be rebuilt according to the changed input.
Sub main()
Dim MacroUI As New CMacroFeaturePropPage
MacroUI.PropPageMenuCallback
End Sub

350

Macro Feature

API Fundamentals

Module:
MacroFeature
Functions

This module contains the MacroFeature functions. This has been


separated from the PMP implementation code for clarity.
For comments on this code, open the macro
CounterBoreMacroFeature.swp
Public Function swmRegenCBore(app As Variant, swPart As _
Variant, feature As Variant) As Variant
Dim swMyFeature As SldWorks.feature
Dim swMacroFeatureData As SldWorks.MacroFeatureData
Dim dboxDimArray(7) As Double
Dim boxDimArray As Variant
Dim PartBody As Object
Dim ResultBodies As Variant
Dim errorCode As Long
Dim MyParamNames As Variant
Dim MyParamTypes As Variant
Dim MyParamValues As Variant
Set swMyFeature = feature
Set swMacroFeatureData = swMyFeature.GetDefinition
swMacroFeatureData.GetParameters _
MyParamNames, MyParamTypes, MyParamValues
Dim
Dim
Dim
Dim
Dim

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

Macro Feature

351

API Fundamentals

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
Public Function swmEditCBore(app As Variant, _
swPart As Variant, feature As Variant) As Variant
Dim MacroUI As New CMacroFeaturePropPage
MacroUI.m_IsEditing = True
Dim i_feature As SldWorks.feature
Set MacroUI.swMacroFeatureParent = feature
Set MacroUI.swMacroFeatureData = feature.GetDefinition
MacroUI.swMacroFeatureData.AccessSelections swPart, Nothing
Dim MyParamNames As Variant
Dim MyParamTypes As Variant
Dim MyParamValues As Variant
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

Batch
Conversion 1

In this example we are automating a note modification for several


drawings at one time.

Const FileDir As String = "C:\SolidWorks Training Files\API


Fundamentals\Appendix\BatchConversions\"
Const FileMask As String = "*.slddrw"
Const OldPostCode As String = "01741"
Const NewPostCode As String = "01742"
Private Sub DoReplaceText(ByRef NoteText As String)
NoteText = Replace(NoteText, OldPostCode, NewPostCode, _
1, -1, vbTextCompare)
End Sub
Sub main()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swDraw As SldWorks.DrawingDoc
Dim swView As SldWorks.view
Dim swNote As SldWorks.note
Dim
Dim
Dim
Dim
Dim
Dim

FileName As String
NoteText As String
TextCount As Long
errors As Long
warnings As Long
i As Long

Set swApp = Application.SldWorks


FileName = Dir(FileDir + FileMask, vbNormal)
Do While FileName <> ""
Set swModel = swApp.OpenDoc6(FileName, swDocDRAWING, _
swOpenDocOptions_Silent, "", errors, warnings)
Set swDraw = swModel
Set swView = swDraw.GetFirstView
Do While Not swView Is Nothing
Set swNote = swView.GetFirstNote
Do While Not swNote Is Nothing
If swNote.IsCompoundNote Then
TextCount = swNote.GetTextCount
For i = 1 To TextCount
NoteText = swNote.GetTextAtIndex(i)
DoReplaceText NoteText
swNote.SetTextAtIndex i, NoteText
Next i
Else

Batch Conversion 1

353

API Fundamentals

NoteText = swNote.GetText ' process the text


DoReplaceText NoteText
swNote.SetText NoteText
End If
Set swNote = swNote.GetNext
Loop
Set swView = swView.GetNextView
Loop
errors = swModel.Save2(True)
swApp.QuitDoc FileName
FileName = Dir
Loop
End Sub

354

Batch Conversion 1

API Fundamentals

Batch
Conversion 2

In this example we are automating the addition of a note in a specific


location for several drawings.

Const FileDir As String = "C:\SolidWorks Training Files\API


Fundamentals\Appendix\BatchConversions\"
Const
Const
Const
Const
Const
Const
Const

FileMask As String = "*.slddrw"


NewNote As String = "For Internal Use Only"
NotePt_X As Double = 0.2128516978344
NotePt_Y As Double = 0.04630161580401
Height As Double = 0.003704
Angle As Double = 0#
FontName As String = "Century Gothic"

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
Dim
Dim
Dim
Dim
Dim

FileName As String
NoteText As String
errors As Long
warnings As Long
i As Long

Set swApp = Application.SldWorks


FileName = Dir(FileDir + FileMask, vbNormal)
Do While FileName <> ""
Set swModel = swApp.OpenDoc6(FileName, swDocDRAWING, _
swOpenDocOptions_Silent, "", errors, warnings)
Set swDraw = swModel
swModel.SetAddToDB True
swDraw.EditTemplate
Set swNote = swDraw.CreateText2(NewNote, NotePt_X, _
NotePt_Y, 0#, Height, Angle)
Set swTextFormat = swNote.GetTextFormat
swTextFormat.TypeFaceName = FontName
swNote.SetTextFormat False, swTextFormat
swDraw.EditSheet
swModel.SetAddToDB False
errors = swModel.Save2(True)
swApp.QuitDoc FileName
FileName = Dir
Loop
End Sub

Batch Conversion 2

355

API Fundamentals

Assembly
Traversal

This example demonstrates how to traverse an assembly and create a


list of all its components. You could use this code to create a bill of
materials. This code also traverses all of the features in each component
and prints them underneath the component in the list.
In VBA, click View, Immediate Window when running this macro to
see the output.
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
Set swApp = Application.SldWorks 'Connect to SW
Set swModel = swApp.ActiveDoc ' Get the active assembly
Set swConf = swModel.GetActiveConfiguration
Set swRootComp = swConf.GetRootComponent
nStart = Timer
Debug.Print "File = " & swModel.GetPathName
'traverse all of the assembly features
TraverseModelFeatures swModel, 1
'Now traverse all of the components and sub assemblies
TraverseComponent swRootComp, 1
Debug.Print ""
Debug.Print "Time = " & Timer - nStart & " s"
End Sub
Sub TraverseModelFeatures(swModel As SldWorks.ModelDoc2, _
nLevel As Long)
'this code recursively traverses all of the features in a model
Dim swFeat As SldWorks.feature
Set swFeat = swModel.FirstFeature
TraverseFeatureFeatures swFeat, nLevel
End Sub
Sub TraverseFeatureFeatures(swFeat As SldWorks.feature, _
nLevel As Long)
'recursively traversing the feature's features
Dim swSubFeat
As SldWorks.feature
Dim swSubSubFeat
As SldWorks.feature
Dim swSubSubSubFeat
As SldWorks.feature
Dim sPadStr
As String
Dim i
As Long
For i = 0 To nLevel
sPadStr = sPadStr + " "
Next i
While Not swFeat Is Nothing
Debug.Print sPadStr + swFeat.Name + " [" + _
swFeat.GetTypeName + "]"
Set swSubFeat = swFeat.GetFirstSubFeature
While Not swSubFeat Is Nothing

356

Assembly Traversal

API Fundamentals

Debug.Print sPadStr + " " + swSubFeat.Name + " [" + _


swSubFeat.GetTypeName + "]"
Set swSubSubFeat = swSubFeat.GetFirstSubFeature
While Not swSubSubFeat Is Nothing
Debug.Print sPadStr + "
" + swSubSubFeat.Name + " _
[" + swSubSubFeat.GetTypeName + "]"
Set swSubSubSubFeat = swSubFeat.GetFirstSubFeature
While Not swSubSubSubFeat Is Nothing
Debug.Print sPadStr + "
" + _
swSubSubSubFeat.Name + " [" + _
swSubSubSubFeat.GetTypeName + "]"
Set swSubSubSubFeat = swSubSubSubFeat. _
GetNextSubFeature()
Wend
Set swSubSubFeat = swSubSubFeat.GetNextSubFeature()
Wend
Set swSubFeat = swSubFeat.GetNextSubFeature()
Wend
Set swFeat = swFeat.GetNextFeature
Wend
End Sub
Sub TraverseComponent(swComp As SldWorks.Component2, _
nLevel As Long)
'this recursively traverses all of the components in an assembly
and prints their name to the immediate window
Dim vChildComp
As Variant
Dim swChildComp
As SldWorks.Component2
Dim swCompConfig
As SldWorks.configuration
Dim sPadStr
As String
Dim i
As Long
For i = 0 To nLevel - 1
sPadStr = sPadStr + " "
Next i
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
Sub TraverseComponentFeatures(swComp As SldWorks.Component2, _
nLevel As Long)
'this recursively traverses all of the components features
Dim swFeat As SldWorks.feature
Set swFeat = swComp.FirstFeature
TraverseFeatureFeatures swFeat, nLevel
End Sub

Assembly Traversal

357

API Fundamentals

Custom Model
View

In this example we are creating a custom view on the model document.


It uses an Excel style ActiveX control embedded on the custom view.

Option Explicit
Private Sub cmdCancel_Click()
End
End Sub
Public Sub cmdDensity_Click()
Dim density As String
density = CDbl(txtdensity.text) * 100 * 100 * 100
Modelview1.modelviewmaker (density)
Me.Hide
End Sub

358

Custom Model View

API Fundamentals

Const sExcelTabName As String = "PartProperties"


Const CLSID1 As String = "{0002E510-0000-0000-C000000000000046}"
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Dim

swApp
swModel
swModelExt
swModViewMgr
materialProps
massProps
density
bRet
xl

As SldWorks.SldWorks
As SldWorks.ModelDoc2
As SldWorks.ModelDocExtension
As SldWorks.ModelViewManager
As Variant
As Variant
As Double
As Boolean
As OWC.Spreadsheet

Sub main()
UserForm1.Show
End Sub
Sub modelviewmaker(density As Double)
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
swModel.SetUserPreferenceIntegerValue swUnitsLinear, swCM
swModel.SetUserPreferenceDoubleValue
swMaterialPropertyDensity, (density / 1000)
Set swModViewMgr = swModel.ModelViewManager
materialProps = swModel.MaterialPropertyValues
Set xl = swModViewMgr.AddControl(sExcelTabName, CLSID1, "")
bRet = swModViewMgr.ActivateControlTab(sExcelTabName)
'column 1
xl.Range("A1").Select
xl.ActiveCell.Formula = "Red"
xl.Selection.Interior.Color = RGB(255, 0, 0)
xl.Range("A2").Select
xl.ActiveCell.Formula = "Green"
xl.Selection.Interior.Color = RGB(0, 255, 0)
xl.Range("A3").Select
xl.ActiveCell.Formula = "Blue"
xl.Selection.Interior.Color = RGB(0, 0, 255)
xl.Range("A4").Select
xl.ActiveCell.Formula = "Ambient"
xl.Range("A5").Select
xl.ActiveCell.Formula = "Diffuse"
xl.Range("A6").Select
xl.ActiveCell.Formula = "Specular"
xl.Range("A7").Select
xl.ActiveCell.Formula = "Shininess"
xl.Range("A8").Select
xl.ActiveCell.Formula = "Transparency"
xl.Range("A9").Select
xl.ActiveCell.Formula = "Emission"
xl.Columns("1").Select
xl.Selection.Font.Bold = True
xl.Selection.Font.Name = "Arial"
xl.Selection.Font.Size = 12
xl.Selection.ColumnWidth = 140#
xl.Selection.HAlignment = 3

Custom Model View

359

API Fundamentals

'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(0) * 255
= materialProps(1) * 255
= materialProps(2) * 255
= materialProps(3)
= 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

Set swModelExt = swModel.Extension


Dim status As Long
massProps = swModelExt.GetMassProperties(0, status)
'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

Custom Model View

API Fundamentals

'column 4
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

= density / 100 / 100 / 100

= massProps(0) * 100

= massProps(1) * 100

= massProps(2) * 100

= massProps(3) * 100 * 100 * 100

= massProps(4) * 100 * 100

= massProps(5) * 1000 'Mass (grams)

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

'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

Custom Model View

361

API Fundamentals

362

Custom Model View

API Fundamentals

Index

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

Face Traversal 185


FeatMgrView Events 346
FeatureByPositionReverse 197
FeatureExtrusion 133
FeatureManager 55
FeatureManager Traversal 192
FeatureRevolve 135
file types 5
FileNewNotify 315
FileOpenNotify 317
FirstFeature 192
forms
inserting 29
Frame 302
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

InsertNewPart 64
InsertNote 55, 59
InsertSketch2 55, 58
IntelliSense 49
IsCircle 151
IsOuter 151
ISwAddin Implementation 274
L
late binding 49
LoadFile2 47, 69
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

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
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
V
variables 5
ViewZoomtofit2 55
Visual Basic for Applications
(VBA) 19
W
WithEvents 315

Index

365

API Fundamentals

366

Index

Das könnte Ihnen auch gefallen