API Api2006 Draft

376
SolidWorks ® 2006 API Fundamentals SolidWorks Corporation 300 Baker Avenue Concord, Massachusetts 01742 Pre-Release Do not copy or distribute

description

solidworks

Transcript of API Api2006 Draft

Page 1: API Api2006 Draft

SolidWorks® 2006

API Fundamentals

SolidWorks Corporation

300 Baker Avenue

Concord, Massachusetts 01742

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 2: API Api2006 Draft

© 1995-2005, SolidWorks Corporation

300 Baker AvenueConcord, Massachusetts 01742 USAAll 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 © 1994-2002 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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 3: API Api2006 Draft

API Fundamentals

i

Table of Contents

IntroductionAbout This Course . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Course Design Philosophy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Using this Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Windows® XP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Conventions Used in this Book . . . . . . . . . . . . . . . . . . . . . . . . . . . 4About the CD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5File Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Option Explicit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Choosing Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6API Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6SolidWorks Constants Type Library . . . . . . . . . . . . . . . . . . . . . . . 7

Macro Recording Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8SolidWorks 2006 API Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8API Object Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Understanding API Interface Member Descriptions . . . . . . . . . . 10

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 4: API Api2006 Draft

API Fundamentals

ii

Lesson 1:Using the Macro Recorder

Macro Recording . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Macro Toolbar. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Understanding How Macro Code Works . . . . . . . . . . . . . . . . . . . . . . 20

Variable Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Entry Point Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20SolidWorks Application Object . . . . . . . . . . . . . . . . . . . . . . . . . . 20SolidWorks Document Object . . . . . . . . . . . . . . . . . . . . . . . . . . . 20SolidWorks API Calls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Procedure End. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

Understanding How to Call Members on API Interfaces . . . . . . . . . . 21Passing Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Cleaning Up Code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

Commenting Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Debugging Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

Adding Forms to a Macro. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28Exercise 1: Recording a Macro. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35Exercise 2: Adding Macro Code to a VBA Button Control . . . . . . . . 37Exercise 3: Adding User Input Fields on a VBA Form . . . . . . . . . . . 40

Lesson 2:The API Object Model

SolidWorks API Object Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45Visual Basic Automatic Type Casting . . . . . . . . . . . . . . . . . . . . . 46

Application Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47SldWorks Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47SolidWorks 2006 Type Library . . . . . . . . . . . . . . . . . . . . . . . . . . 48IntelliSense . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49Early vs. Late Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

Case Study: Connecting to New Documents . . . . . . . . . . . . . . . . . . . 51Macro Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54ModelDoc2 Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55ModelDoc Extension Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56PartDoc Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64AssemblyDoc Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64DrawingDoc Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

Case Study: Connecting to Existing Documents . . . . . . . . . . . . . . . . 69Exercise 4: Working with New Documents . . . . . . . . . . . . . . . . . . . . 77Exercise 5: Working with Existing Documents . . . . . . . . . . . . . . . . . 79

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 5: API Api2006 Draft

API Fundamentals

iii

Lesson 3:Setting System Options and Document Properties

User Preferences - System Options . . . . . . . . . . . . . . . . . . . . . . . . . . 83Setting Checkboxes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83Setting Textboxes with Integers . . . . . . . . . . . . . . . . . . . . . . . . . . 85Setting Textboxes with Doubles . . . . . . . . . . . . . . . . . . . . . . . . . . 86Setting Textboxes with String Values . . . . . . . . . . . . . . . . . . . . . 87Setting Listboxes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88Setting Radio Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88Setting Slider Bars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

User Preferences - Document Properties . . . . . . . . . . . . . . . . . . . . . . 90Locating the Correct APIs and Enumeration Values . . . . . . . . . . . . . 91UserPreference Tables For System Options . . . . . . . . . . . . . . . . . . . . 92UserPreference Tables For Document Properties . . . . . . . . . . . . . . . 111Exercise 6: Change Multiple System Options . . . . . . . . . . . . . . . . . 123Exercise 7: Change Multiple Document Properties . . . . . . . . . . . . . 125

Lesson 4:Automating Part Design

Case Study: Automation Tool for Parts . . . . . . . . . . . . . . . . . . . . . . 129Setting Material. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130Creating the Sketch Rectangle . . . . . . . . . . . . . . . . . . . . . . . . . . 131Adding Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131Selection on Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131Creating the Sketch Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133Creating Extruded Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133Enabling Contour Selection for the Extrusion . . . . . . . . . . . . . . 134Creating Revolved Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135Standard Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137View Commands. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137Sketch Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138Sketch Tools Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138Features Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139Sketch Relations Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . 139Reference Geometry Commands . . . . . . . . . . . . . . . . . . . . . . . . 139

Exercise 8: Automating the Part Creation Process . . . . . . . . . . . . . . 141Lesson 5:

Assembly AutomationCase Study: Automation Tool for Assemblies . . . . . . . . . . . . . . . . . 145

Transforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148Creating MathTransforms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148The Transformation Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148Activating Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149Invisible Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149Object Collections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150Establishing the Curve and Edge Collections. . . . . . . . . . . . . . . 150

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 6: API Api2006 Draft

API Fundamentals

iv

Establishing the Face Collection. . . . . . . . . . . . . . . . . . . . . . . . . 151Getting Adjacent Faces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152Establishing the Points Collection . . . . . . . . . . . . . . . . . . . . . . . 153Getting Curve Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153Adding and Mating the Knobs to the Chassis. . . . . . . . . . . . . . . 154Adding Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155Adding Mates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155

Exercise 9: Adding Components . . . . . . . . . . . . . . . . . . . . . . . . . . . 157Lesson 6:Drawing Automation

Case Study: Automating Drawing Creation . . . . . . . . . . . . . . . . . . . 161Getting Configuration Names. . . . . . . . . . . . . . . . . . . . . . . . . . . 163Creating Sheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164Creating Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166Inserting Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167Traversing Drawing Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169Saving Drawings in Different Formats . . . . . . . . . . . . . . . . . . . . 170Drawing Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172Annotation Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172Layer Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172Line Format Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172

Exercise 10: Drawing Automation . . . . . . . . . . . . . . . . . . . . . . . . . . 173Lesson 7:Selection and Traversal Techniques

Case Study: Programming With a Selected Object . . . . . . . . . . . . . 179SelectionManager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180Accessing the Selection Manager . . . . . . . . . . . . . . . . . . . . . . . . 180Counting Selected Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180Accessing Selected Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181Getting Selected Object Types . . . . . . . . . . . . . . . . . . . . . . . . . . 181Getting Feature Type Names . . . . . . . . . . . . . . . . . . . . . . . . . . . 181Feature Data Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182Accessing the Feature Data Object . . . . . . . . . . . . . . . . . . . . . . . 182Accessing Selections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182Releasing Selections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183Modifying Feature Data Properties. . . . . . . . . . . . . . . . . . . . . . . 183Modify the Object Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . 184

The SolidWorks BREP Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185Traversing Topology and Geometry. . . . . . . . . . . . . . . . . . . . . . 186

Case Study: Body and Face Traversal . . . . . . . . . . . . . . . . . . . . . . . 187Returning a List of Body Pointers . . . . . . . . . . . . . . . . . . . . . . . 188Face Material Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 7: API Api2006 Draft

API Fundamentals

v

Case Study: Feature Manager Traversal . . . . . . . . . . . . . . . . . . . . . . 192Traversing the FeatureManager from the Top . . . . . . . . . . . . . . 192Displaying Feature Names and Types . . . . . . . . . . . . . . . . . . . . 193Setting Feature Suppression . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194Setting Feature UI State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196Obtaining a Feature by FeatureManager Position . . . . . . . . . . . 197

Exercise 11: Handling Preselection 1 . . . . . . . . . . . . . . . . . . . . . . . . 199Exercise 12: Handling Preselection 2 . . . . . . . . . . . . . . . . . . . . . . . . 201Exercise 13: Traversing the FeatureManager . . . . . . . . . . . . . . . . . . 203

Lesson 8:

Adding Custom Properties and AttributesCase Study: Custom Properties. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207

Adding Custom Properties to a SolidWorks Document . . . . . . . 208Setting and Getting Custom Property Values . . . . . . . . . . . . . . . 209Getting Custom Property Names . . . . . . . . . . . . . . . . . . . . . . . . 210Getting the Custom Property Count . . . . . . . . . . . . . . . . . . . . . . 210

Case Study: Configurations With Custom Properties. . . . . . . . . . . . 211Returning Mass Properties From a SolidWorks Model . . . . . . . 213Using the API to Return the Mass Properties . . . . . . . . . . . . . . . 213

Case Study: File Summary Information . . . . . . . . . . . . . . . . . . . . . . 216Adding Summary Information . . . . . . . . . . . . . . . . . . . . . . . . . . 216

Case Study: Document Attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . 217Naming Attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218

The Attribute Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218AttributeDef Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218Attribute Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219Parameter Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219

Case Study: Face Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221Finding the Cylindrical Faces and Attaching Attributes . . . . . . 223Displaying Callouts in the Model View . . . . . . . . . . . . . . . . . . . 225Callout Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225Creating the CNC Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226Types of Attribute Traversal. . . . . . . . . . . . . . . . . . . . . . . . . . . . 226A Final Word about Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . 229

Exercise 14: Adding Mass Properties as Custom Properties . . . . . . 231Exercise 15: Adding Attributes to Edges . . . . . . . . . . . . . . . . . . . . . 233

Lesson 9:

The SolidWorks API SDKThe API SDK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239

Installing the SDK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239Case Study: Creating a VB.NET Add-In. . . . . . . . . . . . . . . . . . . . . . 244

References. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246Comparing Addin DLLs and Stand-Alone Executables. . . . . . . 249Loading and Running an Add-in Application. . . . . . . . . . . . . . . 250

Case Study: Creating a C# Add-in . . . . . . . . . . . . . . . . . . . . . . . . . . 252

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 8: API Api2006 Draft

API Fundamentals

vi

Case Study: C++ Add-Ins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255Compiling a C++ Add-In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257Loading the C++ Add-In. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259Debugging the C++ Add-in . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260

Choosing a Programming Language. . . . . . . . . . . . . . . . . . . . . . . . . 263Lesson 10:Customizing the SolidWorks User Interface

Case Study: Customizing the UI With VB.NET. . . . . . . . . . . . . . . . 267Debugging the DLL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270Debugger Keyboard Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . 271

Understanding The Add-in Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 272Importing Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273The Add-in Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273Understanding the GUID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274Connecting to Solidworks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275Bidirectional Communication. . . . . . . . . . . . . . . . . . . . . . . . . . . 276Setting Callback Information . . . . . . . . . . . . . . . . . . . . . . . . . . . 276Custom Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277Custom Menu Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279Creating and Adding Custom Toolbars to an Add-in . . . . . . . . . 281Creating the Toolbar Bitmaps. . . . . . . . . . . . . . . . . . . . . . . . . . . 282Adding Toolbar Bitmaps to a VB.NET Solution . . . . . . . . . . . . 283The Bitmap Handler Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284Adding Toolbars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285Adding Toolbar Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287

Property Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289PropertyPage Members. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289Add-In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290SldWorks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290UserPMPage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290SldWorks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290Add-In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290ppage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290handler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290PropertyManager Page2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290PropertyManager Page2Handler2. . . . . . . . . . . . . . . . . . . . . . . . 290Creating a PropertyManager Page . . . . . . . . . . . . . . . . . . . . . . . 291

Property Page Groups and Controls . . . . . . . . . . . . . . . . . . . . . . . . . 292Adding Group Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293Group and control IDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293Adding Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294Adding Picture Labels to Controls . . . . . . . . . . . . . . . . . . . . . . . 297

Removing Menus and Toolbars . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 9: API Api2006 Draft

API Fundamentals

vii

Other Areas of Customization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302Custom Status Bars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302Custom Pop-up Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303Custom ModelView Windows . . . . . . . . . . . . . . . . . . . . . . . . . . 303

Exercise 16: Implement a New Menu. . . . . . . . . . . . . . . . . . . . . . . . 305Exercise 17: Implement Toolbar Buttons . . . . . . . . . . . . . . . . . . . . . 307Exercise 18: Implement Controls on a Property Manager Page. . . . 309

Lesson 11:Notifications

Notifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315Notifications in VBA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315Case Study: Simple Notification. . . . . . . . . . . . . . . . . . . . . . . . . . . . 316

The Class Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316Case Study: Using Notifications in .NET. . . . . . . . . . . . . . . . . . . . . 318

The AddHandler Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321The AddressOf Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321The Event Handler Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322The Document Event Handler Class. . . . . . . . . . . . . . . . . . . . . . 323Attaching the DocumentEvent Handlers . . . . . . . . . . . . . . . . . . 324Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326Polymorphism. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326The Derived Event Handler Classes . . . . . . . . . . . . . . . . . . . . . . 328The DocView Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330Detaching the Document and Model View Event Handlers. . . . 333Detaching the SolidWorks Event Handlers . . . . . . . . . . . . . . . . 337Interfaces That Support Notifications. . . . . . . . . . . . . . . . . . . . . 340

Exercise 19: Handling Events Using the Add-in Wizard . . . . . . . . . 347Solution. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348

AppendixMacro Feature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350Batch Conversion 1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353Batch Conversion 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355Assembly Traversal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356Custom Model View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 10: API Api2006 Draft

API Fundamentals

viii

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 11: API Api2006 Draft

API Fundamentals

1

Introduction

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 12: API Api2006 Draft

API FundamentalsIntroduction

2

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 13: API Api2006 Draft

API FundamentalsIntroduction

About This Course 3

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:

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 14: API Api2006 Draft

API FundamentalsIntroduction

4 About This Course

Conventions Used in this Book

This manual uses the following typographic conventions:

About the CD 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.

Convention Meaning

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

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

Release

Do not copy o

r distr

ibute

Page 15: API Api2006 Draft

API FundamentalsIntroduction

Getting Started 5

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 16: API Api2006 Draft

API FundamentalsIntroduction

6 Getting Started

Choosing Data Types

Visual Basic supports these standard types of data:

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

Integer - holds numeric values between -32,768 and +32,767. To make sure a variable is of this type, use (%) after the variable name.

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

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

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

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.

Date - 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 (# #)

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 swApp As Object 'Generic objectDim swApp As SldWorks.SldWorks 'Specific objectDim filename As String 'Simple stringDim dvarArray(2) As Double '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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 17: API Api2006 Draft

API FundamentalsIntroduction

Getting Started 7

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 18: API Api2006 Draft

API FundamentalsIntroduction

8 Macro Recording Tips

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.

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 19: API Api2006 Draft

API FundamentalsIntroduction

Macro Recording Tips 9

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.

Programmer’s 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 it’s 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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 20: API Api2006 Draft

API FundamentalsIntroduction

10 Macro Recording Tips

Understanding API Interface Member

Descriptions

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

1

2

3

4

5

6 7

8

9

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 21: API Api2006 Draft

API FundamentalsIntroduction

Macro Recording Tips 11

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 22: API Api2006 Draft

API FundamentalsIntroduction

12 Macro Recording Tips

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 Longstyle = 1swApp.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. Pre-Rele

ase

Do not copy o

r distr

ibute

Page 23: API Api2006 Draft

API Fundamentals

13

Lesson 1

Using the Macro Recorder

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

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 24: API Api2006 Draft

Lesson 1 API FundamentalsUsing the Macro Recorder

14

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 25: API Api2006 Draft

API Fundamentals Lesson 1Using the Macro Recorder

Macro Recording 15

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.

Run launches the Run Macro dialog box, where the user selects the macro to execute.

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

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.

Edit launches the Edit Macro dialog box for selecting the macro to view or modify.

Custom allows the user to customize a button on the Macro toolbar. An image is selected, a file path to a macro is set, and the custom button is dragged onto the Macro toolbar for use.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 26: API Api2006 Draft

Lesson 1 API FundamentalsUsing the Macro Recorder

16 Macro Toolbar

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

3 Click Record .

4 Select the Front plane.

5 Click Sketch .

6 Click Circle .

Use an approximate radius of 40 millimeters, then enter the exact value of 40 mm in the PropertyManager.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 27: API Api2006 Draft

API Fundamentals Lesson 1Using the Macro Recorder

Macro Toolbar 17

7 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 Click Stop .

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 28: API Api2006 Draft

Lesson 1 API FundamentalsUsing the Macro Recorder

18 Macro Toolbar

Automation Review Let’s take a look at how much we’ve 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 Custom macro buttons can be placed on any toolbar, not just the Macro toolbar.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 29: API Api2006 Draft

API Fundamentals Lesson 1Using the Macro Recorder

Macro Toolbar 19

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 30: API Api2006 Draft

Lesson 1 API FundamentalsUsing the Macro Recorder

20 Understanding How Macro Code Works

Understanding How Macro Code Works

First thing to do is follow the code from top to bottom. Let’s examine our macro code more closely to understand how easy and powerful macros are:

Variable DeclarationThe 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.

Option Explicit'**********************************************************' Macro1.swb - macro recorded on ##/##/##'**********************************************************Dim swApp As ObjectDim Part As ObjectDim SelMgr As ObjectDim boolstatus As BooleanDim longstatus As Long, longwarnings As LongDim Feature As Object

Entry Point ProcedureThis is the beginning of our

functionality. Every macro

must establish an entry point

procedure.

Sub main()

SolidWorks Application ObjectThis line of code will start an

instance of SolidWorks or

connect to a running instance of

SolidWorks. Without it, your

program will not run.

Set swApp = Application.SldWorks

SolidWorks Document ObjectIn 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

Set Part = swApp.ActiveDoc

SolidWorks API CallsAn 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

Set SelMgr = Part.SelectionManagerboolstatus = Part.Extension.SelectByID2("Front Plane", _ "PLANE", 0, 0, 0, False, 0, Nothing, 0)Part.InsertSketch2 TruePart.ClearSelection2 TruePart.CreateCircle 0, 0, 0, 0.043409,-0.003803, 0Part.ShowNamedView2 "*Trimetric", 8Part.ClearSelection2 Trueboolstatus = 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, FalsePart.SelectionManager.EnableContourSelection = 0

Procedure End End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 31: API Api2006 Draft

API Fundamentals Lesson 1Using the Macro Recorder

Understanding How to Call Members on API Interfaces 21

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)

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 32: API Api2006 Draft

Lesson 1 API FundamentalsUsing the Macro Recorder

22 Passing Parameters

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. Let’s explore one of our lengthy calls, FeatureManager::FeatureExtrusion, which has 20 parameters.

FeatureManager::FeatureExtrusion2pFeat = 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.swEndCondBlindswEndCondThroughAll swEndCondThroughNextswEndCondUpToVertexswEndCondUpToSurface swEndCondOffsetFromSurfaceswEndCondMidPlaneswEndCondUpToBody

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 TRUE allows draft angle in first direction, FALSE does not allow drafting.

Input: dchk2 TRUE allows draft angle in second direction, FALSE does not allow drafting.

Input: ddir1 TRUE for first draft angle to be inward, FALSE to be outward.

Input: ddir2 TRUE 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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 33: API Api2006 Draft

API Fundamentals Lesson 1Using the Macro Recorder

Passing Parameters 23

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 34: API Api2006 Draft

Lesson 1 API FundamentalsUsing the Macro Recorder

24 Cleaning Up Code

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.

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. That’s 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.

Option Explicit

These comments are not

functional and can be deleted.

'**********************************************************' Macro1.swb - macro recorded on ##/##/##'**********************************************************

Dim swApp As ObjectDim 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 LongDim Feature As Object

Sub main()

Set swApp = Application.SldWorksSet 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 TruePart.ClearSelection2 True

See Note below. Part.CreateCircle 0, 0, 0, 0.03394, 0.02555, 0

These calls are unnecessary. Part.ShowNamedView2 "*Trimetric", 8Part.ClearSelection2 Trueboolstatus = 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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 35: API Api2006 Draft

API Fundamentals Lesson 1Using the Macro Recorder

Cleaning Up Code 25

Tip As you study the API help file, you’ll 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 don’t 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 we’ve 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 ExplicitDim swApp As ObjectDim Part As ObjectDim boolstatus As Boolean

Sub main()‘Connect to SolidWorksSet swApp = Application.SldWorksSet Part = swApp.ActiveDoc

‘Create a cylinder on the front planeboolstatus = Part.Extension.SelectByID2("Front Plane", _

"PLANE", 0, 0, 0, False, 0, Nothing, 0)Part.InsertSketch2 TruePart.CreateCircleByRadius2 0, 0, 0, 0.04Part.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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 36: API Api2006 Draft

Lesson 1 API FundamentalsUsing the Macro Recorder

26 Cleaning Up Code

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:

18 Debug the macro.

Press F5 to start debugging. The macro stops at the breakpoint to allow the programmer to step through the code.

Breakpoint

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 37: API Api2006 Draft

API Fundamentals Lesson 1Using the Macro Recorder

Cleaning Up Code 27

19 Begin stepping into code.

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

20 Press F8.

21 Press F8.

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 38: API Api2006 Draft

Lesson 1 API FundamentalsUsing the Macro Recorder

28 Adding Forms to a Macro

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 39: API Api2006 Draft

API Fundamentals Lesson 1Using the Macro Recorder

Adding Forms to a Macro 29

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): frmMacro1aCaption: CylindersStartup Position: 2 - CenterScreenShowModal: False

Tip If the properties window is not showing in your code editor press the F4 key to display it. You can also display it by clicking View, Properties Window... from the menu.

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): cmd100mmCaption: 100 mm

CommandButton2:(Name): cmd500mmCaption: 500 mm

CommandButton3:(Name): cmd1mCaption: 1 m

CommandButton4:(Name): cmd5mCaption: 5 m

CommandButton5:(Name): cmdExitCaption: Exit

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 40: API Api2006 Draft

Lesson 1 API FundamentalsUsing the Macro Recorder

30 Adding Forms to a Macro

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 ObjectDim Part As ObjectDim boolstatus As Boolean‘Connect to SolidWorksSet swApp = Application.SldWorksSet Part = swApp.ActiveDoc‘Create a cylinder on the front planeboolstatus = Part.Extension.SelectByID2("Front Plane", _

"PLANE", 0, 0, 0, False, 0, Nothing, 0)Part.InsertSketch2 TruePart.CreateCircleByRadius2 0, 0, 0, 0.04Part.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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 41: API Api2006 Draft

API Fundamentals Lesson 1Using the Macro Recorder

Adding Forms to a Macro 31

Private Sub cmd500mm_Click()Dim swApp As ObjectDim Part As ObjectDim boolstatus As Boolean‘Connect to SolidWorksSet swApp = Application.SldWorksSet Part = swApp.ActiveDoc‘Create a cylinder on the front planeboolstatus = Part.Extension.SelectByID2("Front Plane", _

"PLANE", 0, 0, 0, False, 0, Nothing, 0)Part.InsertSketch2 TruePart.CreateCircleByRadius2 0, 0, 0, 0.04Part.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 ObjectDim Part As ObjectDim boolstatus As Boolean‘Connect to SolidWorksSet swApp = Application.SldWorksSet Part = swApp.ActiveDoc‘Create a cylinder on the front planeboolstatus = Part.Extension.SelectByID2("Front Plane", _

"PLANE", 0, 0, 0, False, 0, Nothing, 0)Part.InsertSketch2 TruePart.CreateCircleByRadius2 0, 0, 0, 0.04Part.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 ObjectDim Part As ObjectDim boolstatus As Boolean‘Connect to SolidWorksSet swApp = Application.SldWorksSet Part = swApp.ActiveDoc‘Create a cylinder on the front planeboolstatus = Part.Extension.SelectByID2("Front Plane", _

"PLANE", 0, 0, 0, False, 0, Nothing, 0)Part.InsertSketch2 TruePart.CreateCircleByRadius2 0, 0, 0, 0.04Part.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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 42: API Api2006 Draft

Lesson 1 API FundamentalsUsing the Macro Recorder

32 Adding Forms to a Macro

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

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): frmMacro1bCaption: Custom CylinderStartup Position: 2 - CenterScreenShowModal: False

100mm

500mm

1m

5m

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 43: API Api2006 Draft

API Fundamentals Lesson 1Using the Macro Recorder

Adding Forms to a Macro 33

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): txtDiameterText: <leave blank>

TextBox2:(Name): txtDepthText: <leave blank>

CommandButton1:(Name): cmdBuildCaption: Build

CommandButton2:(Name): cmdExitCaption: 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 ObjectDim Part As ObjectDim boolstatus As BooleanDim diameter As DoubleDim depth As Double

diameter = CDbl(txtDiameter.Text) / 1000depth = CDbl(txtDepth.Text) / 1000

‘Connect to SolidWorksSet swApp = Application.SldWorksSet Part = swApp.ActiveDoc

‘Create a cylinder on the front planeboolstatus = 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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 44: API Api2006 Draft

Lesson 1 API FundamentalsUsing the Macro Recorder

34 Adding Forms to a Macro

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.ShowEnd Sub

38 Save and run the macro.

39 Exit the macro.

10

50

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 45: API Api2006 Draft

API Fundamentals Exercise 1:Recording a Macro

35

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 � Recording, saving, and playing a macro.� Customizing the Macro toolbar.

APIs Used SldWorks.ActiveDocModelDocExtension.SelectByID2ModelDoc2.InsertSketch2ModelDoc2.CreateCircleFeatureManager.FeatureExtrusion2

Procedure 1. Open a new part file in SolidWorks.2. Display the Macro toolbar.3. Click Record Macro.4. Perform the steps to extrude a cylinder: R20 mm x 80 mm (see

case study).5. Click Stop Macro.6. Save the macro in a temporary location.7. Customize the Macro toolbar to run the macro.8. Open a new part file in SolidWorks.9. Play custom macro.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 46: API Api2006 Draft

Exercise 1: API FundamentalsRecording a Macro

36

Solution Option Explicit

Dim swApp As ObjectDim Part As ObjectDim SelMgr As ObjectDim boolstatus As BooleanDim longstatus As Long, longwarnings As LongDim 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 = 0End SubPre-

Release

Do not copy o

r distr

ibute

Page 47: API Api2006 Draft

API Fundamentals Exercise 2:Adding Macro Code to a VBA Button Control

37

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 � 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.ActiveDocModelDocExtension.SelectByID2ModelDoc2.InsertSketch2ModelDoc2.CreateCircleByRadius2FeatureManager.FeatureExtrusion2

Procedure 1. Open a new part file in SolidWorks.2. From the Macro toolbar, click Edit Macro.3. Select the macro from the previous exercise.4. Insert a userform.5. 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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 48: API Api2006 Draft

Exercise 2: API FundamentalsAdding Macro Code to a VBA Button Control

38

Solution Option Explicit

Sub main()frmMacro1a.Show

End Sub---------------------------------------------------------------

Option Explicit

Private Sub cmd10mm_Click()Dim swApp As ObjectDim Part As ObjectDim boolstatus As Boolean

Set swApp = Application.SldWorksSet Part = swApp.ActiveDocboolstatus = Part.Extension.SelectByID2("Front Plane", _

"PLANE", 0, 0, 0, False, 0, Nothing, 0)Part.InsertSketch2 TruePart.CreateCircleByRadius2 0, 0, 0, 0.04Part.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 ObjectDim Part As ObjectDim boolstatus As Boolean

Set swApp = Application.SldWorksSet Part = swApp.ActiveDocboolstatus = Part.Extension.SelectByID2("Front Plane", _

"PLANE", 0, 0, 0, False, 0, Nothing, 0)Part.InsertSketch2 TruePart.CreateCircleByRadius2 0, 0, 0, 0.04Part.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 ObjectDim Part As ObjectDim boolstatus As Boolean

Set swApp = Application.SldWorksSet Part = swApp.ActiveDocboolstatus = Part.Extension.SelectByID2("Front Plane", _

"PLANE", 0, 0, 0, False, 0, Nothing, 0)Part.InsertSketch2 TruePart.CreateCircleByRadius2 0, 0, 0, 0.04Part.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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 49: API Api2006 Draft

API Fundamentals Exercise 2:Adding Macro Code to a VBA Button Control

39

Private Sub cmd40mm_Click()Dim swApp As ObjectDim Part As ObjectDim boolstatus As Boolean

Set swApp = Application.SldWorksSet Part = swApp.ActiveDocboolstatus = Part.Extension.SelectByID2("Front Plane", _

"PLANE", 0, 0, 0, False, 0, Nothing, 0)Part.InsertSketch2 TruePart.CreateCircleByRadius2 0, 0, 0, 0.04Part.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

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 50: API Api2006 Draft

Exercise 3: API FundamentalsAdding User Input Fields on a VBA Form

40

Exercise 3:Adding User Input Fields on a VBA Form

Objective To automate the feature creation process while allowing for user-defined 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 � Adding textbox controls to a form.� Declaring variables and converting values from a text box.� Debugging code.

APIs Used SldWorks.ActiveDocModelDocExtension.SelectByID2ModelDoc2.InsertSketch2ModelDoc2.CreateCircleByRadius2FeatureManager.FeatureExtrusion2

Procedure 1. Open a new part file in SolidWorks.2. Edit the macro from the previous exercise.3. Insert a second userform.4. Drag and drop five labels, two textboxes and two command buttons

onto the form. 5. 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.

6. Modify the entry point procedure to display the second form.7. Add code that converts values from the text boxes and inserts them

into the methods for creating a circle and extruding a boss.8. Add a breakpoint on the click event procedure for Build.9. Step through the macro in debug mode. Test to see if the second

form loads and the textboxes and command buttons work.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 51: API Api2006 Draft

API Fundamentals Exercise 3:Adding User Input Fields on a VBA Form

41

Solution Option Explicit

Sub main()frmMacro1b.Show

End Sub---------------------------------------------------------------

Option Explicit

Dim swApp As ObjectDim Part As ObjectDim boolstatus As BooleanDim radius As DoubleDim depth As Double

Private Sub cmdBuild_Click()radius = CDbl(txtRadius.Text) / 1000depth = CDbl(txtDepth.Text) / 1000

Set swApp = Application.SldWorksSet Part = swApp.ActiveDocboolstatus = Part.Extension.SelectByID2("Front", "Front _

Plane", 0, 0, 0, False, 0, Nothing)Part.InsertSketch2 TruePart.CreateCircleByRadius2 0, 0, 0, radiusPart.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---------------------------------------------------------------

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 52: API Api2006 Draft

Exercise 3: API FundamentalsAdding User Input Fields on a VBA Form

42

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 53: API Api2006 Draft

API Fundamentals

43

Lesson 2The API Object Model

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

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 54: API Api2006 Draft

Lesson 2 API FundamentalsThe API Object Model

44

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 55: API Api2006 Draft

API Fundamentals Lesson 2The API Object Model

SolidWorks API Object Model 45

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.

These next macros are 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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 56: API Api2006 Draft

Lesson 2 API FundamentalsThe API Object Model

46 SolidWorks 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 it’s 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 it’s 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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 57: API Api2006 Draft

API Fundamentals Lesson 2The API Object Model

Application Objects 47

Application Objects

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 we’ll explore is the top level API interface called SldWorks.

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

SldWorks Object(swApp)

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 58: API Api2006 Draft

Lesson 2 API FundamentalsThe API Object Model

48 Application Objects

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 59: API Api2006 Draft

API Fundamentals Lesson 2The API Object Model

Application Objects 49

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

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 object’s 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 object’s contents at design time. The programmer can also see it’s 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 don’t 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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 60: API Api2006 Draft

Lesson 2 API FundamentalsThe API Object Model

50 Application Objects

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

� Late BindingDim swApp As ObjectDim swModel As Object

Sub main()Set swApp = Application.SldWorksSet swModel = swApp.ActiveDoc

End Sub

� Early BindingDim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2

Sub main()Set swApp = Application.SldWorksSet swModel = swApp.ActiveDoc

End Sub

Tip It is best to use early binding. Early binding helps to make your code understandable by other programmers and also it will make your application faster. Early binding also checks for coding errors at compile time. When the compiler is bound to an object at compile time, the compiler can check to see if the object supports the members that are called from it. If you late bind, the error will not be found until you run the code.

3 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

4 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.SldWorksswApp.setu

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 61: API Api2006 Draft

API Fundamentals Lesson 2The API Object Model

Case Study: Connecting to New Documents 51

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 haven’t 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.SldWorksswApp.SetUserPreferenceDoubleValue

End Sub

6 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. Double-click on frmNewDocs under the Forms folder to display the form in the editor.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 62: API Api2006 Draft

Lesson 2 API FundamentalsThe API Object Model

52 Case Study: Connecting to New Documents

2 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): frmNewDocsCaption: New DocumentsBorderStyle: 1 - fmBorderStyleSingleStartup Position: 2 - CenterScreenShowModal: FalseHeight: 300Width: 270

Frame1:(Name): fraSldWorksCaption: SldWorksHeight: 72Width: 252

CheckBox1:(Name): chkRevNumCaption: RevisionNumber

CheckBox2:(Name): chkDispStatBarCaption: DisplayStatusBar

CheckBox3:(Name): chkSWExpCaption: SolidWorksExplorer

CommandButton1:(Name): cmdConnectCaption: Connect to SolidWorks

3 Add the button click event.

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

Private Sub cmdConnect_Click()

End Sub

4 Connect to the SldWorks object.

Add the following lines of programming code within the event:

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

End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 63: API Api2006 Draft

API Fundamentals Lesson 2The API Object Model

Case Study: Connecting to New Documents 53

5 Add SldWorks methods and properties.

Continue adding code within the event for the checkboxes:

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

If chkRevNum.Value = True ThenDim retval As Stringretval = swApp.RevisionNumberMsgBox "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 ThenswApp.DisplayStatusBar True

ElseswApp.DisplayStatusBar False

End If

If chkSWExp.Value = True ThenswApp.SolidWorksExplorer

End IfEnd Sub

6 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

7 Save and run the macro.

Try each of the checkboxes separately to test how SolidWorks behaves. Follow this order:

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 64: API Api2006 Draft

Lesson 2 API FundamentalsThe API Object Model

54 Case Study: Connecting to New Documents

Macro Results

1. + .

2. + .

3. + .

8 Stop the macro.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 65: API Api2006 Draft

API Fundamentals Lesson 2The API Object Model

Case Study: Connecting to New Documents 55

Now let’s 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.

This is the dialog that allows us

to understand which methods

are available for successfully

connecting to objects further

down the Object Model.

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:

‘ option 1Dim swModel As SldWorks.ModelDoc2Set swModel = swApp.ActiveDoc‘ option 2Dim swModel As SldWorks.ModelDoc2Set swModel = swApp.NewDocument (TemplateName, PaperSize, _

Width, Height)‘ option 3Dim swModel As SldWorks.ModelDoc2Set 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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 66: API Api2006 Draft

Lesson 2 API FundamentalsThe API Object Model

56 Case Study: Connecting to New Documents

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.

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 it’s methods.

ModelDoc Extension

Object(swModelExt)

Use the ModelDoc2 property, Extension, to connect to the ModelDocExtension object:

‘ option 1 - get a pointer to the ModelDocExtension object

Dim swModelExt As SldWorks.ModelDocExtensionSet swModelExt = swModel.ExtensionswModelExt.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.ModelDoc2Set swModel = swApp.ActiveDocswModel.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 = CenterOfMassXreturnvalue1 = CenterOfMassYreturnvalue2 = CenterOfMassZreturnvalue3 = Volumereturnvalue4 = Areareturnvalue5 = Massreturnvalue6 = MomXXreturnvalue7 = MomYYreturnvalue8 = MomZZreturnvalue9 = MomXYreturnvalue10 = MomZXreturnvalue11 = MomYZreturnvalue12 = Accuracy

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 67: API Api2006 Draft

API Fundamentals Lesson 2The API Object Model

Case Study: Connecting to New Documents 57

9 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): fraModelDoc2Caption: ModelDoc2Height: 114Width: 252

OptionButton1:(Name): optPartCaption: PartValue: True

OptionButton2:(Name): optAssyCaption: AssemblyValue: False

OptionButton3:(Name): optDrawCaption: DrawingValue: False

CheckBox4:(Name): chkSketchCaption: InsertSketch2

CheckBox5:(Name): chkFamilyTableCaption: InsertFamilyTableNew

CheckBox6:(Name): chkNoteCaption: InsertNote

CommandButton2:(Name): cmdNewModelCaption: 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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 68: API Api2006 Draft

Lesson 2 API FundamentalsThe API Object Model

58 Case Study: Connecting to New Documents

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.SldWorksSet swApp = Application.SldWorks

Dim swModel As SldWorks.ModelDoc2Set 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.SldWorksSet swApp = Application.SldWorks

Dim swModel As SldWorks.ModelDoc2' Determine which option is selected ' and connect to the ModelDoc2 object

If optPart.Value = True ThenSet swModel = swApp.NewDocument(filedir + _

"APIPart.prtdot",0, 0#, 0#)End If

If optAssy.Value = True ThenSet swModel = swApp.NewDocument(filedir + _

"APIAssembly.asmdot", 0, 0#, 0#)End If

If optDraw.Value = True ThenSet 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 ThenswModel.InsertSketch2 True

End If

If chkFamilyTable.Value = True ThenswModel.InsertFamilyTableNew

End If

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 69: API Api2006 Draft

API Fundamentals Lesson 2The API Object Model

Case Study: Connecting to New Documents 59

If chkNote.Value = True ThenDim swNote As Sldworks.NoteDim swAnnotation As Sldworks.AnnotationDim text As String

text = "Sample Note"Set swNote = swModel.InsertNote(text)Set swAnnotation = swNote.GetAnnotationswAnnotation.SetPosition 0.01, 0.01, 0

End IfEnd Sub

14 Save and run the macro.

Try each of the option buttons first:

+

+

+

New document

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 70: API Api2006 Draft

Lesson 2 API FundamentalsThe API Object Model

60 Case Study: Connecting to New Documents

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

+ +

+ +

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

+ +

+ +

New sketch

New design table

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 71: API Api2006 Draft

API Fundamentals Lesson 2The API Object Model

Case Study: Connecting to New Documents 61

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

+ +

+ +

+ +

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 )

New note

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 72: API Api2006 Draft

Lesson 2 API FundamentalsThe API Object Model

62 Case Study: Connecting to New Documents

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.ViewDim drawname As StringDim errors As LongDim warnings As Long

drawname = swModel.GetTitleswApp.OpenDoc6 filedir + "BlockwithDesignTable.SLDPRT", 1, _0, "", errors, warningsSet 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.ViewIf chkSketch.Value = True Then If optDraw.Value = True Then

Set swView = preparedrawingView(swApp, swModel)swView.FocusLocked = True

ElseswModel.InsertSketch2 True

End IfEnd If

If chkFamilyTable.Value = True ThenIf optDraw.Value = True ThenSet swView = preparedrawingView(swApp, swModel)swModel.SelectByID swView.Name, "DRAWINGVIEW", 0, 0, 0swModel.InsertFamilyTableNew

ElseswModel.InsertFamilyTableNew

End IfEnd If

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 73: API Api2006 Draft

API Fundamentals Lesson 2The API Object Model

Case Study: Connecting to New Documents 63

18 Save and run the macro.

Now our macro should prepare a sample drawing appropriately before trying to insert a sketch or design table:

+ +

+ +

19 Stop the macro.

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

Sketch mode is

now active in view

Design table is inserted into view

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 74: API Api2006 Draft

Lesson 2 API FundamentalsThe API Object Model

64 Case Study: Connecting to New Documents

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 swModel As SldWorks.ModelDoc2Dim swPart As SldWorks.PartDocDim swAssy As SldWorks.AssemblyDocDim swDraw As SldWorks.DrawingDoc

Set swModel = swApp.ActiveDoc

If (swModel.GetType = swDocPART) ThenSet swPart = swModel

End If

If (swModel.GetType = swDocASSEMBLY) ThenSet swAssy = swModel

End If

If (swModel.GetType = swDocDRAWING) ThenSet swDraw = swModel

End If

If swModel Is Nothing ThenswApp.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)

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 75: API Api2006 Draft

API Fundamentals Lesson 2The API Object Model

Case Study: Connecting to New Documents 65

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): fraPartCaption: PartDocHeight: 66Width: 78

CommandButton3:(Name): cmdPartCaption: New Model

CheckBox7:(Name): chkRollbackCaption: EditRollback-----------------------------frame4:(Name): fraAssyCaption: AssemblyDocHeight: 66Width: 84

CommandButton4:(Name): cmdAssyCaption: New Assembly

CheckBox8:(Name): chkComponentCaption: AddComponent-----------------------------Frame5:(Name): fraDrawCaption: DrawingDocHeight: 66Width: 78

CommandButton5:(Name): cmdDrawCaption: New Drawing

CheckBox9:(Name): chkFormatCaption: 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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 76: API Api2006 Draft

Lesson 2 API FundamentalsThe API Object Model

66 Case Study: Connecting to New Documents

22 Connect to the SldWorks object.

Add the following lines of programming code within each event:

Private Sub cmdPart_Click()Dim swApp As SldWorks.SldWorksSet swApp = Application.SldWorks

End SubPrivate Sub cmdAssy_Click()Dim swApp As SldWorks.SldWorksSet swApp = Application.SldWorks

End SubPrivate Sub cmdDraw_Click()Dim swApp As SldWorks.SldWorksSet swApp = Application.SldWorks

End Sub

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

Add the following code:

Private Sub cmdPart_Click()Dim swApp As SldWorks.SldWorksSet swApp = Application.SldWorksDim swModel As SldWorks.ModelDoc2Set swModel = swApp.NewDocument(filedir + "APIPart.prtdot", _0, 0#, 0#)Dim swPart As SldWorks.PartDocSet swPart = swModelswModel.InsertSketch2 TrueswModel.SketchRectangle 0, 0, 0, 0.1, 0.1, 0, 1swModel.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 ThenswPart.EditRollback

End IfEnd Sub

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

Add the following code:

Private Sub cmdAssy_Click()Dim swApp As SldWorks.SldWorksSet swApp = Application.SldWorksDim fileerror As LongDim filewarning As LongswApp.OpenDoc6 filedir + "Sample.sldprt", swDocPART, _swOpenDocOptions_ViewOnly, "", fileerror, filewarningDim swModel As SldWorks.ModelDoc2Set swModel = swApp.NewDocument(filedir + _"APIAssembly.asmdot", 0, 0#, 0#)

Dim swAssy As SldWorks.AssemblyDocSet swAssy = swModelIf chkComponent.value = True ThenswAssy.AddComponent2 filedir + "Sample.sldprt", 0, 0, 0swModel.FeatureManager.UpdateFeatureTree

End IfEnd Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 77: API Api2006 Draft

API Fundamentals Lesson 2The API Object Model

Case Study: Connecting to New Documents 67

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

Add the following code:

Private Sub cmdDraw_Click()Dim swApp As SldWorks.SldWorksSet swApp = Application.SldWorksDim swDraw As SldWorks.DrawingDocSet 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 IfEnd Sub

Save and run the macro.

26 Test each of the following:

+

Rollback

Before

After

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 78: API Api2006 Draft

Lesson 2 API FundamentalsThe API Object Model

68 Case Study: Connecting to New Documents

+

+

27 Stop the macro..

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

Before

After

New component

Before

After

Edit sheet format is

now active in drawing

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 79: API Api2006 Draft

API Fundamentals Lesson 2The API Object Model

Case Study: Connecting to Existing Documents 69

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.SldWorksSet swApp = Application.SldWorks

If chkOpen.value = True ThenDim fileerror As LongDim filewarning As LongswApp.OpenDoc6 filedir + "Sample.sldprt", swDocPART, _

swOpenDocOptions_ViewOnly, "", fileerror, filewarningEnd If

If chkLoad.value = True ThenswApp.LoadFile2 filedir + "Sample.igs", ""

End If

If chkNewWindow.value = True ThenswApp.CreateNewWindowswApp.ArrangeWindows 1

End IfEnd Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 80: API Api2006 Draft

Lesson 2 API FundamentalsThe API Object Model

70 Case Study: Connecting to Existing Documents

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

Set swApp = Application.SldWorksSet swModel = swApp.ActiveDoc' Check to see if a document is loadedIf swModel Is Nothing ThenswApp.SendMsgToUser "Open a part, assembly or drawing."Exit Sub

End If

If chkToolbars.value = True ThenswModel.SetToolbarVisibility swFeatureToolbar, TrueswModel.SetToolbarVisibility swMacroToolbar, TrueswModel.SetToolbarVisibility swMainToolbar, TrueswModel.SetToolbarVisibility swSketchToolbar, TrueswModel.SetToolbarVisibility swSketchToolsToolbar, TrueswModel.SetToolbarVisibility swStandardToolbar, TrueswModel.SetToolbarVisibility swStandardViewsToolbar, TrueswModel.SetToolbarVisibility swViewToolbar, True

End If

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 81: API Api2006 Draft

API Fundamentals Lesson 2The API Object Model

Case Study: Connecting to Existing Documents 71

If chkToolbars.value = False ThenswModel.SetToolbarVisibility swFeatureToolbar, FalseswModel.SetToolbarVisibility swMacroToolbar, FalseswModel.SetToolbarVisibility swMainToolbar, FalseswModel.SetToolbarVisibility swSketchToolbar, FalseswModel.SetToolbarVisibility swSketchToolsToolbar, FalseswModel.SetToolbarVisibility swStandardToolbar, FalseswModel.SetToolbarVisibility swStandardViewsToolbar, FalseswModel.SetToolbarVisibility swViewToolbar, False

End If

If chkCustomInfo.value = True ThenDim retval As Booleanretval = 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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 82: API Api2006 Draft

Lesson 2 API FundamentalsThe API Object Model

72 Case Study: Connecting to Existing Documents

+ .

+

Toolbars visible

Custom Property

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 83: API Api2006 Draft

API Fundamentals Lesson 2The API Object Model

Case Study: Connecting to Existing Documents 73

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.SldWorksDim swModel As SldWorks.ModelDoc2Dim swPart As SldWorks.PartDoc

Set swApp = Application.SldWorksSet swModel = swApp.ActiveDocSet swPart = swModel 'Explicit Type Cast

' Check to see if a part is loadedIf swModel Is Nothing ThenswApp.SendMsgToUser "Please open a part."Exit Sub

End If

If chkMirror.value = True ThenDim boolstatus As Booleanboolstatus = swModel.Extension.SelectByID2("Top", "PLANE", _ 0, 0, 0, False, 0, Nothing, 0)'Next method called from specific PartDoc object.swPart.MirrorPart

Set swModel = swApp.ActiveDocswModel.ShowNamedView2 "*Isometric", 7swModel.ViewZoomtofit2swApp.ArrangeWindows 1Dim retval As BooleanDim errors As LongSet swModel = swApp.ActivateDoc2("sheetmetalsample.SLDPRT",_True, errors)retval = swModel.DeSelectByID("Top", "PLANE", 0, 0, 0)

End IfEnd Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 84: API Api2006 Draft

Lesson 2 API FundamentalsThe API Object Model

74 Case Study: Connecting to Existing Documents

37 Run the macro.

Use the part file: SheetMetalSample.sldprt

+ .

38 Stop the macro..

Return to the VBA editor.

39 Review method available only to AssemblyDoc.

Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swAssy As SldWorks.AssemblyDocSet swApp = Application.SldWorksSet swModel = swApp.ActiveDocSet swAssy = swModel 'Explicit Type Cast!' Check to see if an assembly is loadedIf swModel Is Nothing ThenswApp.SendMsgToUser "Please open an assembly."Exit Sub

End If

If chkCavity.value = True ThenDim boolstatus As Booleanboolstatus = _swModel.Extension.SelectByID2( _"sheetmetalsample-1@sheetmetalsample", "COMPONENT", 0, 0, _ 0, False, 0, Nothing, 0)swAssy.EditPartswModel.ClearSelectionboolstatus = swModel.Extension.SelectByID2( _"plug-1@sheetmetalsample", "COMPONENT", 0, 0, 0, True, _0 ,Nothing, 0)swAssy.InsertCavity4 10, 10, 10, 1, 1, -1swAssy.EditAssemblyboolstatus = swModel.Extension.SelectByID2( _"plug-1@sheetmetalsample", "COMPONENT", 0, 0, 0, _True, 0,Nothing, 0)swAssy.EditSuppress2

End If

Mirrored part

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 85: API Api2006 Draft

API Fundamentals Lesson 2The API Object Model

Case Study: Connecting to Existing Documents 75

40 Run macro.

Use the assembly file: SheetMetalSample.sldasm

+ .

Suppress part to

Return to edit

Insert cavity

Select component

Edit part

view cavity

assembly mode

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 86: API Api2006 Draft

Lesson 2 API FundamentalsThe API Object Model

76 Case Study: Connecting to Existing Documents

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.SldWorksDim swDraw As SldWorks.DrawingDoc

Set swApp = Application.SldWorksSet swDraw = swApp.ActiveDoc

'Check to see if a drawing is loadedIf swDraw Is Nothing ThenswApp.SendMsgToUser "Please open a drawing."Exit Sub

End If

If chkLayer.value = True Then'Notice automatic type cast.swDraw.ClearSelectionDim retval As Booleanretval = swDraw.CreateLayer("MyRedLayer", "Red", RGB(255, _0,0), swLineSTITCH, swLW_THICK, True)

End IfEnd Sub

43 Run macro.

Use the drawing file: SheetMetalSample.slddrw

+ .

44 Exit macro.

New layer

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 87: API Api2006 Draft

API Fundamentals Exercise 4:Working with New Documents

77

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 � 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.NewDocumentModelDoc2.InsertSketch2 ModelDoc2.CreateCircleByRadius2ModelDoc2.ViewZoomtofit2

Procedure 1. Open SolidWorks with no files created.2. Create a new macro named NewDocs.swp.3. Add a userform to the macro.4. Program the entry point procedure to show the userform.5. Use the image as a guide for designing each control.6. Program the click event for each button.7. Use the methods listed above in your code.8. Save and test the macro.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 88: API Api2006 Draft

Exercise 4: API FundamentalsWorking with New Documents

78

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

Private Sub cmdSldWorks_Click()Set swApp = Application.SldWorks

If chkMessage.Value = True ThenswApp.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 ThenSet swModel = swApp.NewDocument(filedir + _

"APIPart.prtdot", 0, 0#, 0#)End If

If optAssy.Value = True ThenSet swModel = swApp.NewDocument(filedir + _

"APIAssembly.asmdot", 0, 0#, 0#)End If

If chkCircle.Value = True ThenswModel.InsertSketch2 TrueswModel.CreateCircleByRadius2 0, 0, 0, 0.05swModel.ViewZoomtofit2

End If

End Sub---------------------------------------------------------------

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 89: API Api2006 Draft

API Fundamentals Exercise 5:Working with Existing Documents

79

Exercise 5:Working with Existing Documents

Objective To open specific document types and connect to existing documents already open.

Skills Learned � 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.ActiveDocModelDoc2.AddLightSource ModelDoc2.SetLightSourcePropertyValuesVBModelDoc2.LockLightToModelModelDoc2.GraphicsRedraw

Procedure 1. Open SolidWorks with no files created.2. Create a new macro named ExistingDocs.swp.3. Add a userform to the macro.4. Program the entry point procedure to show the userform.5. Use the image as a guide for designing each control.6. Program the click event for each button.7. Use the methods listed above in your code.8. Save and test the macro.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 90: API Api2006 Draft

Exercise 5: API FundamentalsWorking with Existing Documents

80

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

Private Sub cmdSldWorks_Click()Set swApp = Application.SldWorks

If chkOpen.Value = True ThenDim fileerror As LongDim filewarning As Long

If optPart.Value = True ThenswApp.OpenDoc6 filedir + "sample.sldprt", swDocPART, _

swOpenDocOptions_Silent, "", fileerror, filewarningEnd If

If optAssy.Value = True ThenswApp.OpenDoc6 filedir + "sample.sldasm", swDocASSEMBLY, _

swOpenDocOptions_Silent, "", fileerror, filewarningEnd If

End If

End Sub

Private Sub cmdModel_Click()Set swApp = Application.SldWorksSet swModel = swApp.ActiveDoc

' Check to see if a document is loadedIf swModel Is Nothing ThenswApp.SendMsgToUser "Please open a part or assembly."Exit Sub

End If If chkSpot.Value = True ThenswModel.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, 0swModel.LockLightToModel 2, FalseswModel.GraphicsRedraw

End If

End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 91: API Api2006 Draft

API Fundamentals

81

Lesson 3

Setting System Options andDocument Properties

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

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 92: API Api2006 Draft

Lesson 3 API Fundamentals

82

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 93: API Api2006 Draft

API Fundamentals Lesson 3

User Preferences - System Options 83

User Preferences - System Options

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::SetUserPreferenceToggleSldWorks.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 FALSE = toggle the item off

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 94: API Api2006 Draft

Lesson 3 API Fundamentals

84 User Preferences - System Options

1 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

3 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.SldWorksswApp.SetUserPreferenceToggle _

swConst.swInputDimValOnCreate, TrueswApp.SetUserPreferenceToggle _

swConst.swSingleCommandPerPick, TrueswApp.SetUserPreferenceToggle _

swConst.swShowDimensionNames, TrueswApp.SetUserPreferenceToggle _

swConst.swShowErrorsEveryRebuild, TrueEnd Sub

4 Save and run the macro.

Test to see if the checkboxes are enabled.

Return to VBA when finished.

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 95: API Api2006 Draft

API Fundamentals Lesson 3

User Preferences - System Options 85

Setting Textboxes with Integers

Call the SldWorks::SetUserPreferenceIntegerValue method to enter values for textbox items that require integer values.

5 Add code to change viewport color.

On the Colors page, change the Viewport Background color value.

Dim swApp As SldWorks.SldWorksDim viewportColor As LongSub main()Set swApp = Application.SldWorksswApp.SetUserPreferenceToggle _

swConst.swInputDimValOnCreate, TrueswApp.SetUserPreferenceToggle _

swConst.swSingleCommandPerPick, TrueswApp.SetUserPreferenceToggle _

swConst.swShowDimensionNames, TrueswApp.SetUserPreferenceToggle _

swConst.swShowErrorsEveryRebuild,TrueviewportColor = RGB(128, 255, 128) ‘sets color to greenswApp.SetUserPreferenceIntegerValue _

swConst.swSystemColorsViewportBackground, viewportColorEnd Sub

6 Save and run macro.

Test to see if the textbox values have changed.

Return to VBA when finished.

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

Output: retval TRUE if the successful, FALSE if not.

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

Release

Do not copy o

r distr

ibute

Page 96: API Api2006 Draft

Lesson 3 API Fundamentals

86 User Preferences - System Options

Setting Textboxes with Doubles

Call the SldWorks::SetUserPreferenceDoubleValue method to enter values for textbox items that require numeric values with decimal points.

7 Add code to change the detail view scale.

On the Drawings page, change the Detail View Scaling value.

Set swApp = Application.SldWorksswApp.SetUserPreferenceToggle _

swConst.swInputDimValOnCreate, TrueswApp.SetUserPreferenceToggle _

swConst.swSingleCommandPerPick, TrueswApp.SetUserPreferenceToggle _

swConst.swShowDimensionNames, TrueswApp.SetUserPreferenceToggle _

swConst.swShowErrorsEveryRebuild,Truecolor = RGB(128, 255, 128) ‘sets color to greenswApp.SetUserPreferenceIntegerValue _

swConst.swSystemColorsViewportBackground, colorswApp.SetUserPreferenceDoubleValue _

swConst.swDrawingDetailViewScale, 1.5End Sub

8 Save and run macro.

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

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

Output: retval TRUE if the successful, FALSE if not.

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

Release

Do not copy o

r distr

ibute

Page 97: API Api2006 Draft

API Fundamentals Lesson 3

User Preferences - System Options 87

Setting Textboxes with String Values

Call the SldWorks::SetUserPreferenceStringValue method to enter values for textbox items that require characters.

9 Add code to change backup directory string value.

On the Backups page, change the Save Backup Copies in Directory string value.

Dim value As StringSub main()Set swApp = Application.SldWorksswApp.SetUserPreferenceToggle _

swConst.swInputDimValOnCreate, TrueswApp.SetUserPreferenceToggle _

swConst.swSingleCommandPerPick, TrueswApp.SetUserPreferenceToggle _

swConst.swShowDimensionNames, TrueswApp.SetUserPreferenceToggle _

swConst.swShowErrorsEveryRebuild, Truecolor = RGB(128, 255, 128) ‘sets color to greenswApp.SetUserPreferenceIntegerValue _

swConst.swSystemColorsViewportBackground, colorswApp.SetUserPreferenceDoubleValue _

swConst.swDrawingDetailViewScale, 1.5value = ("D:\Temp")swApp.SetUserPreferenceStringValue _

swConst.swBackupDirectory, valueEnd Sub

10 Save and run macro.

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

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

Output: retval TRUE if the successful, FALSE if not.

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 98: API Api2006 Draft

Lesson 3 API Fundamentals

88 User Preferences - System Options

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

Release

Do not copy o

r distr

ibute

Page 99: API Api2006 Draft

API Fundamentals Lesson 3

User Preferences - System Options 89

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 LongDim value As String

Sub main()Set swApp = Application.SldWorksswApp.SetUserPreferenceToggle _

swConst.swInputDimValOnCreate, TrueswApp.SetUserPreferenceToggle _

swConst.swSingleCommandPerPick, TrueswApp.SetUserPreferenceToggle _

swConst.swShowDimensionNames, TrueswApp.SetUserPreferenceToggle _

swConst.swShowErrorsEveryRebuild,Truecolor = RGB(128, 255, 128) ‘sets color to greenswApp.SetUserPreferenceIntegerValue _

swConst.swSystemColorsViewportBackground, colorswApp.SetUserPreferenceDoubleValue _

swConst.swDrawingDetailViewScale, 1.5value = ("D:\Temp")swApp.SetUserPreferenceStringValue _

swConst.swBackupDirectory, valueswApp.SetUserPreferenceIntegerValue _

swConst.swEdgesHiddenEdgeDisplay, _swConst.swEdgesHiddenEdgeDisplayDashed

‘ View Rotation - Mouse Speed‘ 0 = Slow ‘ 100 = FastswApp.SetUserPreferenceIntegerValue _

swConst.swViewRotationMouseSpeed, 50

‘ View Rotation - ViewAnimationSpeed‘ 0 = Off‘ 0.5 = Fast‘ 1.0‘ 1.5‘ 2.0‘ 2.5‘ 3.0 = SlowswApp.SetUserPreferenceDoubleValue _

swConst.swViewAnimationSpeed, 1.5End Sub

12 Save and run macro.

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

13 Exit macro.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 100: API Api2006 Draft

Lesson 3 API Fundamentals

90 User Preferences - Document Properties

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.

1 Create a new part.

2 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

ModelDoc2::SetUserPreferenceToggleModelDoc2.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 FALSE = toggle the item off

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 101: API Api2006 Draft

API Fundamentals Lesson 3

Locating the Correct APIs and Enumeration Values 91

4 Connect to ModelDoc2.

Add the following lines of code:

Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2

Sub main()Set swApp = Application.SldWorksSet swModel = swApp.ActiveDoc

End Sub

5 Add code to change toggle value.

On the Document Properties, Detailing page enable the checkbox for Dual Dimension Display.

Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2

Sub main()Set swApp = Application.SldWorksSet swModel = swApp.ActiveDocswModel.SetUserPreferenceToggle _

swConst.swDetailingDualDimensions, TrueEnd Sub

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

1 Record a new macro.

Click the Record button from the Macro toolbar

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 102: API Api2006 Draft

Lesson 3 API Fundamentals

92 UserPreference Tables For System Options

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

4 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 SpeedswApp.SetUserPreferenceIntegerValue _

swViewRotationMouseSpeed, 100‘Fast value of View Rotation SpeedswApp.SetUserPreferenceDoubleValue swViewAnimationSpeed, 0.5‘Slow value of Mouse SpeedswApp.SetUserPreferenceIntegerValue swViewRotationMouseSpeed, 0‘Slow value of View animation speed.swApp.SetUserPreferenceDoubleValue swViewAnimationSpeed, 3End 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:

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 103: API Api2006 Draft

API Fundamentals Lesson 3

UserPreference Tables For System Options 93

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 104: API Api2006 Draft

Lesson 3 API Fundamentals

94 UserPreference Tables For System Options

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 Not Supported

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 105: API Api2006 Draft

API Fundamentals Lesson 3

UserPreference Tables For System Options 95

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 106: API Api2006 Draft

Lesson 3 API Fundamentals

96 UserPreference Tables For System Options

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 swDrawingAreaHatchAnglePre-Rele

ase

Do not copy o

r distr

ibute

Page 107: API Api2006 Draft

API Fundamentals Lesson 3

UserPreference Tables For System Options 97

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 108: API Api2006 Draft

Lesson 3 API Fundamentals

98 UserPreference Tables For System Options

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 109: API Api2006 Draft

API Fundamentals Lesson 3

UserPreference Tables For System Options 99

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 110: API Api2006 Draft

Lesson 3 API Fundamentals

100 UserPreference Tables For System Options

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 111: API Api2006 Draft

API Fundamentals Lesson 3

UserPreference Tables For System Options 101

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 112: API Api2006 Draft

Lesson 3 API Fundamentals

102 UserPreference Tables For System Options

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 113: API Api2006 Draft

API Fundamentals Lesson 3

UserPreference Tables For System Options 103

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 114: API Api2006 Draft

Lesson 3 API Fundamentals

104 UserPreference Tables For System Options

External References

Setting Type Enumeration / Values

Open referenced documents with read-only access Toggle swExtRefOpenReadOnly

Don’t 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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 115: API Api2006 Draft

API Fundamentals Lesson 3

UserPreference Tables For System Options 105

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 116: API Api2006 Draft

Lesson 3 API Fundamentals

106 UserPreference Tables For System Options

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 117: API Api2006 Draft

API Fundamentals Lesson 3

UserPreference Tables For System Options 107

Spelling Folders String Not Supported

Scene Folders String swFileLocationsScenes

Light Folders String swFileLocationsLights

Spin Box Increments

Setting Type Enumeration / Values

English Units Double swSpinBoxEnglishLengthIncrement

Metric Units Double swSpinBoxMetricLengthIncrement

Angle increments Double swSpinBoxAngleIncrementPre-Rele

ase

Do not copy o

r distr

ibute

Page 118: API Api2006 Draft

Lesson 3 API Fundamentals

108 UserPreference Tables For System Options

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)

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 119: API Api2006 Draft

API Fundamentals Lesson 3

UserPreference Tables For System Options 109

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 swBackupDirectoryPre-Rele

ase

Do not copy o

r distr

ibute

Page 120: API Api2006 Draft

Lesson 3 API Fundamentals

110 UserPreference Tables For System Options

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 121: API Api2006 Draft

API Fundamentals Lesson 3

UserPreference Tables For Document Properties 111

UserPreference Tables For Document Properties

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 122: API Api2006 Draft

Lesson 3 API Fundamentals

112 UserPreference Tables For Document Properties

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 123: API Api2006 Draft

API Fundamentals Lesson 3

UserPreference Tables For Document Properties 113

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 124: API Api2006 Draft

Lesson 3 API Fundamentals

114 UserPreference Tables For Document Properties

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 125: API Api2006 Draft

API Fundamentals Lesson 3

UserPreference Tables For Document Properties 115

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 126: API Api2006 Draft

Lesson 3 API Fundamentals

116 UserPreference Tables For Document Properties

Virtual Sharps

Setting Type Enumeration / Values

Virtual Sharps Style Int swDetailingVirtualSharpStyle

swDetailingVirtualSharp_e

Annotations Display

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 127: API Api2006 Draft

API Fundamentals Lesson 3

UserPreference Tables For Document Properties 117

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 128: API Api2006 Draft

Lesson 3 API Fundamentals

118 UserPreference Tables For Document Properties

Grid / Snap

Setting 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 swSnapPointsPerMinorPre-Rele

ase

Do not copy o

r distr

ibute

Page 129: API Api2006 Draft

API Fundamentals Lesson 3

UserPreference Tables For Document Properties 119

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 130: API Api2006 Draft

Lesson 3 API Fundamentals

120 UserPreference Tables For Document Properties

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 131: API Api2006 Draft

API Fundamentals Lesson 3

UserPreference Tables For Document Properties 121

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 132: API Api2006 Draft

Lesson 3 API Fundamentals

122 UserPreference Tables For Document Properties

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

Plane Display

Setting Type Enumeration / Values

Transparency Int swPlaneDisplayTransparency

Range = 0 - 100

Show Intersections Toggle swPlaneDisplayShowIntersections

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 133: API Api2006 Draft

API Fundamentals Exercise 6:Change Multiple System Options

123

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 � Programming system options in SolidWorks.

APIs Used SldWorks.SetUserPreferenceToggleSldWorks.SetUserPreferenceIntegerValueSldWorks.SetUserPreferenceStringValue

Procedure 1. Open SolidWorks with no files created.2. Create a new macro named SystemOptions.swp.3. Add code to fit the description above.4. Save and test the macro.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 134: API Api2006 Draft

Exercise 6: API FundamentalsChange Multiple System Options

124

Solution Option Explicit

Dim swApp As SldWorks.SldWorksDim value As String

Sub main()Set swApp = Application.SldWorksvalue = "D:\Temp"swApp.SetUserPreferenceToggle swThumbnailGraphics, TrueswApp.SetUserPreferenceIntegerValue _

swEdgesHiddenEdgeDisplay, swEdgesHiddenEdgeDisplayDashedswApp.SetUserPreferenceIntegerValue _

swEdgesInContextEditTransparencyType, _swInContextEditTransparencyForce

swApp.SetUserPreferenceIntegerValue _swEdgesInContextEditTransparency, 50

swApp.SetUserPreferenceStringValue swBackupDirectory, valueEnd Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 135: API Api2006 Draft

API Fundamentals Exercise 7:Change Multiple Document Properties

125

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 � Setting document properties in SolidWorks with the API.

APIs Used SldWorks.SetUserPreferenceDoubleValueSldWorks.SetUserPreferenceIntegerValueSldWorks.SetUserPreferenceStringValue

Procedure 1. Open a new part file in SolidWorks.2. Create a new macro named DocumentProperties.swp.3. Add code to fit the description above.4. Save and test the macro.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 136: API Api2006 Draft

Exercise 7: API FundamentalsChange Multiple Document Properties

126

Solution Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2

Sub main()Set swApp = Application.SldWorksSet swModel = swApp.ActiveDocswModel.SetUserPreferenceIntegerValue _

swDetailingDimensionStandard, swDetailingStandardANSIswModel.SetUserPreferenceDoubleValue _

swDetailingArrowHeight, 0.15 * 0.0254swModel.SetUserPreferenceDoubleValue _

swDetailingArrowWidth, 0.42 * 0.0254swModel.SetUserPreferenceDoubleValue _

swDetailingArrowLength, 1.5 * 0.0254swModel.SetUserPreferenceIntegerValue swUnitsLinear, swINCHESswModel.SetUserPreferenceIntegerValue _

swUnitsLinearDecimalPlaces, 3End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 137: API Api2006 Draft

API Fundamentals

127

Lesson 4

Automating Part Design

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

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 138: API Api2006 Draft

Lesson 4 API FundamentalsAutomating Part Design

128

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 139: API Api2006 Draft

API Fundamentals Lesson 4Automating Part Design

Case Study: Automation Tool for Parts 129

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

1 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.SldWorksSet swModel = swApp.NewPart swModel.SetAddToDB TrueswModel.SetUserPreferenceIntegerValue swUnitsLinear, swMMswModel.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 it’s parameter list.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 140: API Api2006 Draft

Lesson 4 API FundamentalsAutomating Part Design

130 Case Study: Automation Tool for Parts

Setting Material For the first tab, call ModelDoc2::SetUserPreferenceDoubleValue to set the material density and crosshatch pattern.

3 Add code to set the material.Private Sub cmdBuild_Click()Set swApp = Application.SldWorksSet swModel = swApp.NewPartswModel.SetAddToDB TrueswModel.SetUserPreferenceIntegerValue swUnitsLinear, swMM‘MATERIALIf optAl.Value = True ThenswModel.SetUserPreferenceDoubleValue _

swConst.swMaterialPropertyDensity, 2700swModel.SetUserPreferenceStringValue _

swConst.swMaterialPropertyCrosshatchPattern, _"ISO (Aluminum)" ElseswModel.SetUserPreferenceDoubleValue _swConst.swMaterialPropertyDensity, 8600

swModel.SetUserPreferenceStringValue _swConst.swMaterialPropertyCrosshatchPattern, _

"ISO (Bronze Brass)"End If‘PROFILE‘MACHINE OPERATIONswModel.SetAddToDB False

End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 141: API Api2006 Draft

API Fundamentals Lesson 4Automating Part Design

Case Study: Automation Tool for Parts 131

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.

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.

1. Create rectangle 2. Create offset 3. Add axis

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 142: API Api2006 Draft

Lesson 4 API FundamentalsAutomating Part Design

132 Case Study: Automation Tool for Parts

4 Add code to sketch and dimension a rectangle.

Add code to sketch and dimension the profiles.

swModel.InsertSketch2 FalseIf optRectangular.Value = True Then

txtRadius.enabled = FalseDim Height As DoubleDim Width As DoubleHeight = CDbl(txtHeight.text) / 1000Width = CDbl(txtWidth.text) / 1000'Turn off dimension dialogsswApp.SetUserPreferenceToggle swInputDimValonCreate, False'Create the first line in the profileswModel.CreateLine2 0.05, 0.05, 0, 0.05, 0.05 + Height, 0'Add a dimension to the selected entityswModel.AddDimension2 0, 0.05 + Height / 2, 0swModel.CreateLine2 0.05, 0.05 + Height, 0, 0.05 + Width, _

0.05 + Height, 0swModel.CreateLine2 0.05 + Width, 0.05 + Height, 0, _

0.05 + Width, 0.05, 0swModel.CreateLine2 0.05 + Width, 0.05, 0, 0.05, 0.05, 0swModel.AddDimension2 0.05 + Width / 2, 0, 0swModel.ClearSelection'Select the originswModel.Extension.SelectByID2 "", "EXTSKETCHPOINT", _

0, 0, 0, False, 0, Nothing, 0'Select an end point on the profileswModel.Extension.SelectByID2 "", "SKETCHPOINT", _

0.05, 0.05, 0, True, 0, Nothing, 0'Add a vertical dimensionswModel.AddVerticalDimension2 0, 0.025, 0swModel.ClearSelection'Select the originswModel.Extension.SelectByID2 "", "EXTSKETCHPOINT", _

0, 0, 0, False, 0, Nothing, 0'Select an end point on the profileswModel.Extension.SelectByID2 "", "SKETCHPOINT", _

0.05, 0.05, 0, True, 0, Nothing, 0'Add a horizontal dimension to fully constrain the sketchswModel.AddHorizontalDimension2 0.025, 0, 0swModel.ClearSelection'Select all four profile edgesswModel.Extension.SelectByID2 "Line1", "SKETCHSEGMENT", _

0, 0, 0, False, 0, Nothing, 0swModel.Extension.SelectByID2 "Line2", "SKETCHSEGMENT", _

0, 0, 0, True, 0, Nothing, 0swModel.Extension.SelectByID2 "Line3", "SKETCHSEGMENT", _

0, 0, 0, True, 0, Nothing, 0swModel.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, 1swModel.ViewZoomtofit2

ElseEnd ifswModel.CreateLine2 _

(0, 0, 0, 0, 0.05, 0).ConstructionGeometry = TrueswModel.ViewZoomtofit2

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 143: API Api2006 Draft

API Fundamentals Lesson 4Automating Part Design

Case Study: Automation Tool for Parts 133

Creating the Sketch Circle

Call ModelDoc2::CreateCircleByRadius2 to create the second profile.

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

ElseDim Radius As DoubleRadius = CDbl(txtRadius.text) / 1000swModel.CreateCircleByRadius2 _

0.05 + Radius, 0.05 + Radius, 0, RadiusswModel.SketchOffset2 0.002, 0, 1swModel.ViewZoomtofit2

End IfswModel.CreateLine2 _

(0, 0, 0, 0, 0.05, 0).ConstructionGeometry = TrueswModel.ViewZoomtofit2

Creating Extruded

Features

Call FeatureManager::FeatureExtrusion to create the extrude feature.

1. Create circle 2. Create offset 3. Use axis fromprevious step

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 144: API Api2006 Draft

Lesson 4 API FundamentalsAutomating Part Design

134 Case Study: Automation Tool for Parts

6 Add code to create an extruded feature.‘MACHINE OPERATIONDim swFeatMgr As SldWorks.FeatureManagerIf optExtrude.Value = True ThenDim Depth As DoubleDepth = CDbl(txtDepth.text) / 1000Set swFeatMgr = swModel.FeatureManagerswFeatMgr.FeatureExtrusion True, False, True, 0, 0, Depth, _

0, False, False, False, False, 0, 0, 0, 0, 0, 0, _False, False, False

swModel.ViewZoomtofit2End 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.Pre-

Release

Do not copy o

r distr

ibute

Page 145: API Api2006 Draft

API Fundamentals Lesson 4Automating Part Design

Case Study: Automation Tool for Parts 135

7 Add code to enable contour selection.‘MACHINE OPERATIONDim swFeatMgr As SldWorks.FeatureManagerIf optExtrude.Value = True ThenDim Depth As DoubleDepth = CDbl(txtDepth.text) / 1000Set swFeatMgr = swModel.FeatureManagerIf optRectangular.Value = True ThenIf chkContour1.Value = True ThenswModel.SelectionManager.EnableContourSelection = 1swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _

0.05, 0.05, 0, True, 4, Nothing, 0End IfIf chkContour2.Value = True ThenswModel.SelectionManager.EnableContourSelection = 1swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _

0.05 - 0.002, 0.05, 0, True, 4, Nothing, 0End If

ElseIf chkContour1.Value = True ThenswModel.SelectionManager.EnableContourSelection = 1swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _

0.05 + Radius, 0.05, 0, True, 4, Nothing, 0End IfIf chkContour2.Value = True ThenswModel.SelectionManager.EnableContourSelection = 1swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _

0.05 + Radius, 0.05 - 0.002, 0, True, 4, Nothing, 0End If

End IfswFeatMgr.FeatureExtrusion True, False, True, 0, 0, Depth, _

0, False, False, False, False, 0, 0, 0, 0, 0, 0, _False, False, False

swModel.SelectionManager.EnableContourSelection = 0swModel.ViewZoomtofit2

End If

Creating Revolved Features

Call FeatureManager::FeatureRevolve to create the revolve feature.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 146: API Api2006 Draft

Lesson 4 API FundamentalsAutomating Part Design

136 Case Study: Automation Tool for Parts

8 Add code to create revolved feature.‘MACHINE OPERATIONDim swFeatMgr As SldWorks.FeatureManagerIf optExtrude.Value = True ThenDim Depth As DoubleDepth = CDbl(txtDepth.text) / 1000Set swFeatMgr = swModel.FeatureManagerIf optRectangular.Value = True ThenIf chkContour1.Value = True ThenswModel.SelectionManager.EnableContourSelection = 1swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _

0.05, 0.05, 0, True, 4, Nothing, 0End IfIf chkContour2.Value = True ThenswModel.SelectionManager.EnableContourSelection = 1swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _

0.05 - 0.002, 0.05, 0, True, 4, Nothing, 0End If

ElseIf chkContour1.Value = True ThenswModel.SelectionManager.EnableContourSelection = 1swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _

0.05 + Radius, 0.05, 0, True, 4, Nothing, 0End IfIf chkContour2.Value = True ThenswModel.SelectionManager.EnableContourSelection = 1swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _

0.05 + Radius, 0.05 - 0.002, 0, True, 4, Nothing, 0End If

End IfswFeatMgr.FeatureExtrusion True, False, True, 0, 0, Depth, _

0, False, False, False, False, 0, 0, 0, 0, 0, 0, _False, False, False

swModel.SelectionManager.EnableContourSelection = 0swModel.ViewZoomtofit2

ElseDim Angle As DoubleAngle = CDbl(txtAngle.text * 3.14 / 180)Set swFeatMgr = swModel.FeatureManagerswFeatMgr.FeatureRevolve Angle, True, 0, 0, 0, True, _

False, TrueEnd If

9 Save and run macro.

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 147: API Api2006 Draft

API Fundamentals Lesson 4Automating Part Design

Case Study: Automation Tool for Parts 137

Use the tables on the next few pages as a quick reference for identifying which methods are used for sketching, feature and viewing commands.

Note Also available through the API:

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

Standard Commands

NewDocument PrintDirectPrintOut

OpenDoc6LoadFile2

RebuildEditRebuild3ForceRebuild3

Save3SaveAs4SaveBMP

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

View Commands

TranslateBy ViewDisplayWireframe

ViewOrientationUndo ViewDisplayHiddengreyed

ViewZoomtofit2 ViewDisplayHiddenremoved

ViewZoomTo2 HlrQuality = 1

ZoomByFactor HlrQuality = 0

ViewZoomToSelection ViewDisplayShaded

RotateAboutCenter AddPerspective

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 148: API Api2006 Draft

Lesson 4 API FundamentalsAutomating Part Design

138 Case Study: Automation Tool for Parts

Sketch Commands

SelectByID2SelectByRay

Insert3DSketch2

GridOptions SketchModifyFlipSketchModifyRotateSketchModifyScaleSketchModifyTranslate

InsertSketch2 AutoSolveToggle

Sketch Tools Commands

CreateLine2 SketchUseEdge2

CreateArc2 Sketch3DIntersections

CreateTangentArc2 InsertProjectedSketch2

Create3PointArc

SketchMirror

CreateCircle2CreateCircleByRadius2

SketchFillet2

CreateEllipse2CreateEllipticalArc2

SketchChamfer

SketchParabola

SketchOffset2

SketchSplineCreateSplineInsert3DSplineCurve

MakeStyledCurves

SketchPolygon

SketchTrim, 1

SketchRectangle

SketchTrim, 2

SketchRectangleAtAnyAngle SplitOpenSegmentSplitClosedSegment

CreatePoint2

CreateLinearSketchStepAndRepeat

CreateCenterLineCreateLine2.ConstructionGeometry

CreateCircularSketchStepAndRepeat

InsertSketchText InsertSketchPicture

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 149: API Api2006 Draft

API Fundamentals Lesson 4Automating Part Design

Case Study: Automation Tool for Parts 139

Features Commands

FeatureExtrusionFeatureExtrusionThinFeatureBoss

InsertDome

FeatureRevolveFeatureRevolveThin

InsertRip

FeatureCutFeatureCutThin

EditUnsuppress2

FeatureRevolveCutFeatureRevolveThinCut

EditUnsuppressDependent2

InsertProtrusionSweptInsertCutSwept

EditSuppress2

InsertProtrusionBlendInsertCutBlend

FeatureLinearPattern

FeatureFillet FeatureCirularPattern

FeatureChamferFeatureChamferType

MirrorFeature

InsertRib2 InsertRip

Scale SplitBody

InsertFeatureShellInsertFeatureShellAddThickness

InsertCombineFeature

InsertMfDraft2 InsertDeleteBody

SimpleHole2 InsertMoveCopyBody

Sketch Relations Commands

AddDimension2AddHorizontalDimension2AddVerticalDimension2

GetConstraints

SketchAddConstraints Autodimension

Reference Geometry Commands

CreatePlaneAtAngle3CreatePlaneAtOffset3CreatePlaneAtSurface3CreatePlaneFixed2CreatePlanePerCurveAndPassPoint3CreatePlaneThru3Points3CreatePlaneThruLineAndPtCreatePlaneThruPtParallelToPlane

InsertCoordinateSystem

InsertAxis2

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 150: API Api2006 Draft

Lesson 4 API FundamentalsAutomating Part Design

140 Case Study: Automation Tool for Parts

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 151: API Api2006 Draft

API Fundamentals Exercise 8:Automating the Part Creation Process

141

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 � Automating sketch entities and dimensions� Automating features and set user preferences.

APIs Used ModelDoc2.SetUserPreferenceDoubleValueModelDoc2.SetUserPreferenceStringValueSldWorks.SetUserPreferenceToggleModelDoc2.CreateLine2ModelDoc2.ViewZoomtofit2ModelDoc2.AddDimension2FeatureManager.FeatureExtrusionThinFeatureManager.FeatureRevolveThin

Procedure 1. Open the macro AutomatingPartDesign.swp.2. Add missing controls to the form.3. Program the click event for the Build Part command button.4. Use the APIs listed above to automate the design of an L bracket.5. Save and run macro.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 152: API Api2006 Draft

Exercise 8: API FundamentalsAutomating the Part Creation Process

142

Solution Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swFeatMgr As SldWorks.FeatureManager

Private Sub cmdBuild_Click()Set swApp = Application.SldWorksSet swModel = swApp.NewPartswModel.SetUserPreferenceIntegerValue swConst.swUnitsLinear,_swConst.swMETER

If chkSteel.Value = True ThenswModel.SetUserPreferenceDoubleValue _

swConst.swMaterialPropertyDensity, 7800swModel.SetUserPreferenceStringValue _

swConst.swMaterialPropertyCrosshatchPattern, _"ISO (Steel)"

End If

swModel.InsertSketch2 False

Dim Height As DoubleDim Width As DoubleHeight = CDbl(txtHeight.text) / 1000Width = CDbl(txtWidth.text) / 1000swApp.SetUserPreferenceToggle swConst.swInputDimValOnCreate,_FalseswModel.CreateLine2 0.01, 0.01, 0, 0.01, 0.01 + Height, 0swModel.ViewZoomtofit2swModel.AddDimension2 0, 0.01 + Height / 2, 0swModel.CreateLine2 0.01, 0.01, 0, 0.01 + Width, 0.01, 0swModel.ViewZoomtofit2swModel.AddDimension2 0.01 + Width / 2, 0, 0swModel.CreateLine2(0, 0, 0, 0, 0.01, 0). _ConstructionGeometry = True

swModel.ClearSelectionswModel.ViewZoomtofit2

Dim Thick As DoubleThick = CDbl(txtThick.text) / 1000If optExtrude.Value = True ThenDim Depth As DoubleDepth = CDbl(txtDepth.text) / 1000Set swFeatMgr = swModel.FeatureManagerswFeatMgr.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.ViewZoomtofit2ElseDim Angle As DoubleAngle = CDbl(txtAngle.text * 3.14 / 180)Set swFeatMgr = swModel.FeatureManagerswFeatMgr.FeatureRevolveThin Angle, 0, 0, 0, Thick, 0, 0, _

1, 1, 1End IfswModel.ShowNamedView2 "Isometric", 7swModel.ViewZoomtofit2

End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 153: API Api2006 Draft

API Fundamentals

143

Lesson 5

Assembly Automation

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

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 154: API Api2006 Draft

Lesson 5 API FundamentalsAssembly Automation

144

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 155: API Api2006 Draft

API Fundamentals Lesson 5Assembly Automation

Case Study: Automation Tool for Assemblies 145

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 156: API Api2006 Draft

Lesson 5 API FundamentalsAssembly Automation

146 Case Study: Automation Tool for Assemblies

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

� 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.SldWorksSet swMathUtility = swApp.GetMathUtility() Set swModel = swApp.ActiveDoc If Not swModel Is Nothing Then ElseMsgBox ("Open an assembly to run this macro.")Exit Sub

End IfAssemblyTitle = 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 To navigate quickly to the UserForm_Activate event, double-click on an empty grey area on the user form. This will automatically display the form’s code and set the cursor on the first line of code in the event handler.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 157: API Api2006 Draft

API Fundamentals Lesson 5Assembly Automation

Case Study: Automation Tool for Assemblies 147

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

� 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 ThenElseMsgBox ("Open an Assembly to run this macro on!")Exit Sub

End IfSet swSelFace = swSelMgr.GetSelectedObject3(1) Dim swEntity As SldWorks.entity Set swEntity = swSelFaceSet swSafeSelFace = swEntity.GetSafeEntityIf Not swSelFace Is Nothing Then ' ElseMsgBox ("You did not select a face.")Exit Sub

End IfCall EstablishTargetComponentsTransformCall OpenComponentModelToAddToAssembly("control knob.SLDPRT")Call EstablishCircularCurveAndEdgeCollectionsCall EstablishCylindricalFaceCollectionCall EstablishPointsCollectionCall 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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 158: API Api2006 Draft

Lesson 5 API FundamentalsAssembly Automation

148 Case Study: Automation Tool for Assemblies

Transforms To determine or move a component’s 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 assembly’s 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 assembly’s origin.

In this case study we are trying to add control knobs to the chassis. If the chassis component’s origin was not aligned and coincident to the assembly’s 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 assembly’s 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 component’s transformation data.

The MathTransform object manages the transformation matrix data and provides methods and properties for manipulating this data.

The Transformation Matrix

The SolidWorks transformation matrix is represented as an array of 16 elements:

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

Tip The Component2 Interface supports the Component2::Transform2 property that returns it’s transformation matrix values.

MathUtility::CreateTransformretval = MathUtility.CreateTransform (ArrayData)

Return: retval Pointer to the newly created MathTransform object.

Input: ArrayData Sixteen components of the transform.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 159: API Api2006 Draft

API Fundamentals Lesson 5Assembly Automation

Case Study: Automation Tool for Assemblies 149

4 Add code to establish a transform.

Find the transform of the chassis component.

� 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.Component2Set 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.

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.

SldWorks::ActivateDoc2retval = 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: ErrorsswGenericActivateError = An unspecified error was

encountered, and the document was not activated.

swDocNeedsRebuildWarning = The document that was activated needs to be rebuilt.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 160: API Api2006 Draft

Lesson 5 API FundamentalsAssembly Automation

150 Case Study: Automation Tool for Assemblies

5 Open component.

Add the following code to the OpenComponentModelToAddToAssembly sub program.

The following code:

� Turns off visibility for any newly opened documents.� Opens the component’s 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, warningsSet 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.

SldWorks::DocumentVisible

retval = SldWorks.DocumentVisible (visible, type)

Return: void There is no return value.

Input: visible True to show this document type, False to hide it.

Input: type Any of the 3 SolidWorks document types use the enumerations swDocumentTypes_e for valid values.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 161: API Api2006 Draft

API Fundamentals Lesson 5Assembly Automation

Case Study: Automation Tool for Assemblies 151

Here is the pseudo code for the EstablishCircularCurveAndEdgeCollections sub program:

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

6 Establish curve and edge collections.

Add the following code to the EstablishCircularCurveAndEdgeCollections sub program.

Public Sub EstablishCircularCurveAndEdgeCollections()Dim swLoop As SldWorks.Loop2Set swLoop = swSelFace.GetFirstLoop While Not swLoop Is Nothing If swLoop.IsOuter Then ‘ Don't do anything if it is the outer loop

ElseDim swEdges As VariantswEdges = swLoop.GetEdges() For i = 0 To UBound(swEdges) Dim swCurve As SldWorks.CurveSet swCurve = swEdges(i).GetCurve If swCurve.IsCircle Then CircularEdgeCollection.Add swEdges(i) CircularCurveCollection.Add swCurve

End IfNext i

End IfSet swLoop = swLoop.GetNext

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 162: API Api2006 Draft

Lesson 5 API FundamentalsAssembly Automation

152 Case Study: Automation Tool for Assemblies

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:

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

Getting Adjacent

Faces

Use the Edge::GetTwoAdjacentFaces method to return the two adjacent faces of an edge.

7 Establish face collection.

Add the following code to the EstablishCylindricalFaceCollection sub program.

Public Sub EstablishCylindricalFaceCollection()For i = 1 To CircularEdgeCollection.CountDim swFaces As VariantswFaces = 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.surfaceDim swEntity As SldWorks.entityIf swSurface1.IsCylinder Then 'Determine which one is the cylindrical surfaceSet swTempSurf = swSurface1Set swEntity = swFaces(0)

Edge::GetTwoAdjacentFacesEdge.GetTwoAdjacentFaces (Face1, Face2)

Output: Face1 Pointer to the first adjacent face.

Output: Face2 Pointer to the second adjacent face.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 163: API Api2006 Draft

API Fundamentals Lesson 5Assembly Automation

Case Study: Automation Tool for Assemblies 153

ElseSet swTempSurf = swSurface2Set swEntity = swFaces(1)

End IfIf Not swTempSurf Is Nothing Then'When the cylindrical Face is found....Dim swSafeFace As SldWorks.entitySet swSafeFace = swEntity.GetSafeEntitySafeCylindricalFaceCollection.Add swSafeFace

End IfNext 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.

When the center point is retrieved from the circular edge, it needs to be multiplied by the target components transform (the chassis). If the component’s origin is not aligned with the assembly’s 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.

Curve::CircleParamsretval = Curve.CircleParams ( )

Return: retval SafeArray of seven doubles:center.x, center.y, center.z, axis.x, axis.y, axis.z and radius Pre-

Release

Do not copy o

r distr

ibute

Page 164: API Api2006 Draft

Lesson 5 API FundamentalsAssembly Automation

154 Case Study: Automation Tool for Assemblies

The pseudo code for the EstablishPointsCollection is:

� Traverse every circular curve and get it’s 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.

8 Establish point collection.

Add the following code to the EstablishPointsCollection sub program.

Public Sub EstablishPointsCollection()For i = 1 To CircularCurveCollection.Count() Dim circleParams As VariantcircleParams = 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 iEnd 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:

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 165: API Api2006 Draft

API Fundamentals Lesson 5Assembly Automation

Case Study: Automation Tool for Assemblies 155

Adding Components

Use the AssemblyDoc::AddComponent4 method to add a component or sub assembly to the current assembly.

Adding Mates Call the AssemblyDoc::AddMate method to create a new mate in an assembly.

AssemblyDoc::AddComponent4retval = 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 X coordinate of the component center.

Input: Y Y coordinate of the component center.

Input: Z Z coordinate of the component cente.r

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

Input: MateType swMateCOINCIDENTswMateCONCENTRICswMatePERPENDICULARswMatePARALLELswMateTANGENTswMateDISTANCEswMateANGLEswMateUNKNOWN

Input: Align swMateAlignALIGNEDswMateAlignANTI_ALIGNEDswMateAlignCLOSEST

Input: Flip TRUE to flip the component, FALSE otherwise.

Input: Dist Distance value used with swMateDISTANCE mate type.

Input: Angle Angle value used with swMateANGLE mate type.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 166: API Api2006 Draft

Lesson 5 API FundamentalsAssembly Automation

156 Case Study: Automation Tool for Assemblies

9 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.Component2Dim pointData As VariantpointData = PointCollection.Item(j).arrayData Set swComponent = swAssy.AddComponent4(strCompFullPath,””, _

pointData(0), pointData(1), pointData(2)) Dim strCompName As StringstrCompName = swComponent.Name2() swSafeSelFace.Select2 True, 0swModel.AndSelectByID "Top@" + strCompName & "@" + _

AssemblyName, "PLANE", 0, 0, 0 swAssy.AddMate swMateCOINCIDENT, 0, False, 0, 0 SafeCylindricalFaceCollection(j).Select2 True, 0swModel.AndSelectByID "Point1@Origin@" + strCompName + _

"@" + AssemblyName, "EXTSKETCHPOINT", 0, 0, 0 swAssy.AddMate swMateCONCENTRIC, 1, False, 0, 0

Next jEnd 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, swDocPARTSet swAssy = NothingSet CircularCurveCollection = NothingSet CircularEdgeCollection = NothingSet SafeCylindricalFaceCollection = NothingSet swModel = NothingSet PointCollection = NothingSet swSelFace = NothingSet swSelMgr = NothingSet swApp = NothingMe.Hide

End Sub

11 Save and run macro.

12 Exit macro.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 167: API Api2006 Draft

API Fundamentals Exercise 9:Adding Components

157

Exercise 9:Adding Components

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 � Debugging transforms.

� Positioning components correctly in assembly space with or without using mates.

Procedure 1. Open the assembly Transforms.sldasm.2. Open the macro Transforms.swp3. 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, 0swAssy.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.

Incorrect

Correct

component

positions

positions

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 168: API Api2006 Draft

Exercise 9: API FundamentalsAdding Components

158

Solution Private Sub cmdAddComponentsAndMate_Click()Set swSelFace = swSelMgr.GetSelectedObject3(1)Dim swEntity As SldWorks.entitySet swEntity = swSelFaceSet swSafeSelFace = swEntity.GetSafeEntityIf Not swSelFace Is Nothing ThenElseMsgBox ("You did not select a face.")Exit Sub

End IfCall EstablishTargetComponentsTransformCall OpenComponentModelToAddToAssembly("control knob.SLDPRT")Call EstablishCircularCurveAndEdgeCollectionsCall EstablishCylindricalFaceCollectionCall 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 VariantcircleParams = CircularCurveCollection(i).circleParamsDim arrayData(2) As DoubleDim swMathPoint As SldWorks.mathPointarrayData(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 iEnd Sub

Public Sub AddcomponentsToAssembly(ByVal _strCompFullPath As String)

For j = 1 To PointCollection.CountDim swComponent As Component2Dim pointData As VariantpointData = PointCollection.Item(j).arrayDataSet 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, 0Next j

End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 169: API Api2006 Draft

API Fundamentals

159

Lesson 6

Drawing Automation

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

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 170: API Api2006 Draft

Lesson 6 API FundamentalsDrawing Automation

160

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 171: API Api2006 Draft

API Fundamentals Lesson 6Drawing Automation

Case Study: Automating Drawing Creation 161

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.

1 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.SldWorksDim swModel As SldWorks.ModelDoc2Sub main()Set swApp = Application.SldWorksSet swModel = swApp.ActiveDoc

End Sub

3 Prompt user for projection type.

Use the intrinsic VBA MsgBox function to prompt the user for the projection type.

Dim Response As IntegerDim ThirdAngle As Boolean

Sub main()Response = MsgBox("Create third angle projection?", vbYesNo)If Response = vbYes ThenThirdAngle = True

ElseThirdAngle = False

End If

With Cut

Without Cut

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 172: API Api2006 Draft

Lesson 6 API FundamentalsDrawing Automation

162 Case Study: Automating Drawing Creation

4 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.swDwgPaperA1sizeConst ScaleNum As Double = 1Const ScaleDenom As Double = 2

Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim Response As IntegerDim ThirdAngle As Boolean

Sub main()Response = MsgBox("Create third angle projection?", vbYesNo)If Response = vbYes ThenThirdAngle = True

ElseThirdAngle = False

End If

5 Create new drawing.

Add the code to create a new drawing document.

Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim Response As IntegerDim ThirdAngle As BooleanDim swDraw As SldWorks.DrawingDoc

Sub main()Response = MsgBox("Create third angle projection?", vbYesNo)If Response = vbYes ThenThirdAngle = True

ElseThirdAngle = False

End If

Set swApp = Application.SldWorksSet swModel = swApp.ActiveDocSet swDraw = swApp.NewDocument(TemplateName, PaperSize, _

0#, 0#)End Sub

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 173: API Api2006 Draft

API Fundamentals Lesson 6Drawing Automation

Case Study: Automating Drawing Creation 163

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

7 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 VariantDim ConfigName As VariantDim i As LongSub main()Response = MsgBox("Create third angle projection?", vbYesNo)If Response = vbYes ThenThirdAngle = True

ElseThirdAngle = False

End IfSet swApp = Application.SldWorksSet swModel = swApp.ActiveDocSet swDraw = swApp.NewDocument(TemplateName, PaperSize, _

0#, 0#)ConfigNamesArray = swModel.GetConfigurationNamesFor i = 0 To UBound(ConfigNamesArray)ConfigName = ConfigNamesArray(i)

Next iEnd Sub

ModelDoc2::GetConfigurationNamesretval = ModelDoc2.GetConfigurationNames ( )

Return: retval Safearray of strings containing the names of the configurations in this part.Pre-

Release

Do not copy o

r distr

ibute

Page 174: API Api2006 Draft

Lesson 6 API FundamentalsDrawing Automation

164 Case Study: Automating Drawing Creation

Creating Sheets Call DrawingDoc::NewSheet3 to create new drawing sheets.

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

Return: retval TRUE if successful, FALSE if not.

Input: Name Name of the new sheet.

Input: PaperSize swDwgPaperAsizeswDwgPaperAsizeVerticalswDwgPaperBsizeswDwgPaperCsizeswDwgPaperDsizeswDwgPaperEsizeswDwgPaperA4sizeswDwgPaperA4sizeVerticalswDwgPaperA3sizeswDwgPaperA2sizeswDwgPaperA1sizeswDwgPaperA0sizeswDwgPapersUserDefined

Input: TemplateIn swDwgTemplateAsizeswDwgTemplateAsizeVerticalswDwgTemplateBsizeswDwgTemplateCsizeswDwgTemplateDsizeswDwgTemplateEsizeswDwgTemplateA4sizeswDwgTemplateA4sizeVerticalswDwgTemplateA3sizeswDwgTemplateA2sizeswDwgTemplateA1sizeswDwgTemplateA0sizeswDwgTemplateCustom

swDwgTemplateNone

Input: Scale1 Scale numerator.

Input: Scale2 Scale denominator.

Input: FirstAngle TRUE for first angle projection, FALSE otherwise.

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 175: API Api2006 Draft

API Fundamentals Lesson 6Drawing Automation

Case Study: Automating Drawing Creation 165

8 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.swDwgTemplateA1sizeConst PaperSize As Long = swConst.swDwgPaperA1sizeConst ScaleNum As Double = 1#Const ScaleDenom As Double = 2#

Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim Response As IntegerDim ThirdAngle As BooleanDim swDraw As SldWorks.DrawingDocDim ConfigNamesArray As VariantDim ConfigName As VariantDim i As LongDim retval As Boolean

9 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 iEnd 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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 176: API Api2006 Draft

Lesson 6 API FundamentalsDrawing Automation

166 Case Study: Automating Drawing Creation

Creating Views Call DrawingDoc::Create1st/3rdAngleViews2 to insert standard orthographic views (first or third angle projection).

Tip 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 ThenThirdAngle = True

ElseThirdAngle = False

End IfSet swApp = Application.SldWorksSet swModel = swApp.ActiveDocSet swDraw = swApp.NewDocument(TemplateName, PaperSize, _

0#, 0#)ConfigNamesArray = swModel.GetConfigurationNamesFor 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)

Elseretval = swDraw.Create1stAngleViews2(swModel.GetPathName)

End IfNext i

End Sub

DrawingDoc::Create1stAngleViews2retval = DrawingDoc.Create1stAngleViews2 (modelName)

DrawingDoc::Create3rdAngleViews2retval = DrawingDoc.Create3rdAngleViews2 (modelName)

Return: retval TRUE if successful, FALSE if not.

Input: modelName Name of the document to create views from.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 177: API Api2006 Draft

API Fundamentals Lesson 6Drawing Automation

Case Study: Automating Drawing Creation 167

Inserting Annotations

Call DrawingDoc::InsertModelAnnotations to insert model dimensions and annotations from the underlying model document.

Running the macro produces the projection views automatically.

DrawingDoc::InsertModelAnnotations3retval = 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 view1 = 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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 178: API Api2006 Draft

Lesson 6 API FundamentalsDrawing Automation

168 Case Study: Automating Drawing Creation

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 ThenThirdAngle = True

ElseThirdAngle = False

End IfSet swApp = Application.SldWorksSet swModel = swApp.ActiveDocSet swDraw = swApp.NewDocument(TemplateName, PaperSize, _

0#, 0#)ConfigNamesArray = swModel.GetConfigurationNamesFor i = 0 To UBound(ConfigNamesArray)ConfigName = ConfigNamesArray(i)retval = swDraw.NewSheet3(ConfigName, TemplateSize, _

PaperSize, ScaleNum, ScaleDenom, Not ThirdAngle, "", _0#, 0#, "")

If ThirdAngle = True Thenretval = swDraw.Create3rdAngleViews2(swModel.GetPathName)

Elseretval = swDraw.Create1stAngleViews2(swModel.GetPathName)

End If swDraw.InsertModelAnnotations3 0, _

SwConst.swInsertDimensionsMarkedForDrawing + _ SwConst.swInsertNotes, True, True, True, False

Next iEnd Sub

Running the macro inserts the annotations automatically.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 179: API Api2006 Draft

API Fundamentals Lesson 6Drawing Automation

Case Study: Automating Drawing Creation 169

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 swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim Response As IntegerDim ThirdAngle As BooleanDim swDraw As SldWorks.DrawingDocDim ConfigNamesArray As VariantDim ConfigName As VariantDim i As LongDim retval As BooleanDim swView As SldWorks.view

Sub main()Response = MsgBox("Create third angle projection?", vbYesNo)If Response = vbYes ThenThirdAngle = True

ElseThirdAngle = False

End IfSet swApp = Application.SldWorksSet swModel = swApp.ActiveDocSet swDraw = swApp.NewDocument(TemplateName, PaperSize, _

0#, 0#)ConfigNamesArray = swModel.GetConfigurationNamesFor i = 0 To UBound(ConfigNamesArray)ConfigName = ConfigNamesArray(i)retval = swDraw.NewSheet3(ConfigName, TemplateSize, _

PaperSize, ScaleNum, ScaleDenom, Not ThirdAngle, "", _0#, 0#, "")

If ThirdAngle = True Thenretval = swDraw.Create3rdAngleViews2(swModel.GetPathName)

Elseretval = swDraw.Create1stAngleViews2(swModel.GetPathName)

End Ifretval = swDraw.InsertModelAnnotations(0, False, _

swConst.swInsertDimensions + swConst.swInsertNotes, _True)

Set swView = swDraw.GetFirstViewDo While Not swView Is NothingswView.ReferencedConfiguration = ConfigNameSet swView = swView.GetNextView

LoopswDraw.ForceRebuildNext i

End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 180: API Api2006 Draft

Lesson 6 API FundamentalsDrawing Automation

170 Case Study: Automating Drawing Creation

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.

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 swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim Response As IntegerDim ThirdAngle As BooleanDim swDraw As SldWorks.DrawingDocDim ConfigNamesArray As VariantDim ConfigName As VariantDim i As LongDim retval As Boolean

Const SaveAsPath As String = _"C:\SolidWorks 2006 Training Files\API Fundamentals\Export\"

Dim errors As LongDim warnings As Long

ModelDoc2::SaveAs4retval = 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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 181: API Api2006 Draft

API Fundamentals Lesson 6Drawing Automation

Case Study: Automating Drawing Creation 171

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 Thenretval = swDraw.Create3rdAngleViews2(swModel.GetPathName)

Elseretval = swDraw.Create1stAngleViews2(swModel.GetPathName)

End Ifretval = swDraw.InsertModelAnnotations(0, False, _

swConst.swInsertDimensions + swConst.swInsertNotes, _True)

Set swView = swDraw.GetFirstViewDo While Not swView Is NothingswView.ReferencedConfiguration = ConfigNameSet swView = swView.GetNextView

LoopswDraw.ForceRebuildswDraw.SaveAs4 SaveAsPath & ConfigName & ".DXF", _

0, 0, errors, warningsswDraw.SaveAs4 SaveAsPath & ConfigName & ".DWG", _

0, 0, errors, warningsswDraw.SaveAs4 SaveAsPath & ConfigName & ".JPG", _

0, 0, errors, warningsswDraw.SaveAs4 SaveAsPath & ConfigName & ".TIF", _

0, 0, errors, warningsNext 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.

Running the macro creates the new drawing sheets for each configuration.

Configuration = “Cut” Configuration = “No Cut”

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 182: API Api2006 Draft

Lesson 6 API FundamentalsDrawing Automation

172 Case Study: Automating Drawing Creation

Drawing Commands

Create1stAngleViewsCreate3rdAngleViews

CreateAuxiliaryViewAt3

CreateDetailViewAt3 CreateBreakoutSection

CreateSectionView UpdateViewDisplayGeometry

CreateSectionViewAt4 InsertHatchedFace

CreateDrawViewFromModelView

Annotation Commands

CreateText2InsertNote

InsertCenterMark2

InsertSurfaceFinishSymbol2 InsertCenterLine

NewGtol AddHoleCallout2

InsertBOMBalloon2 InsertCosmeticThreadShowCosmeticThreadHideCosmeticThread

InsertDatumTargetSymbol InsertStackedBalloon

InsertWeldSymbol InsertMultiJogLeader

InsertBlock InsertDowelSymbol

InsertModelAnnotationsInsertModelDimensions

Layer Commands

CreateLayerChangeComponentLayerSetCurrentLayer

Line Format Commands

SetLineColor HideEdge

SetLineWidth ShowEdge

SetLineStyle

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 183: API Api2006 Draft

API Fundamentals Exercise 10:Drawing Automation

173

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 � Automating drawing and annotation commands.

� Working with multiple configurations in drawing views.

APIs Used SldWorks.NewDocumentModelDoc2.GetConfigurationNamesDrawingDoc.NewSheet3DrawingDoc.Create1stAngleViews2DrawingDoc.Create3rdAngleViews2DrawingDoc.CreateDrawViewFromModelViewDrawingDoc.ViewDisplayShadedDrawingDoc.InsertModelAnnoatationsDrawingDoc.GetFirstViewView.ReferencedConfiguration DrawingDoc.GetNextViewDrawingDoc.ForceRebuild

---- Challenge #1 ----DrawDoc.ActivateSheetDrawDoc.GetCurrentSheetSheet.SetName

---- Challenge #2 ----ModelDoc2.SaveAs4

Procedure 1. Open AutomationDrawings.sldasm.2. Open AutomationDrawings.swp.3. Use the APIs listed above to automate the drawing creation.4. Save and run macro.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 184: API Api2006 Draft

Exercise 10: API FundamentalsDrawing Automation

174

Solution Const TemplateName As String = "C:\SolidWorks 2006 Training Files\API Fundamentals\Templates\APIDrawing.drwdot"Const TemplateSize As Long = swConst.swDwgTemplateBsizeConst PaperSize As Long = swConst.swDwgPaperBsizeConst ScaleNum As Double = 1#Const ScaleDenom As Double = 2#

Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim Response As IntegerDim ThirdAngle As BooleanDim swDraw As SldWorks.DrawingDocDim ConfigNamesArray As VariantDim ConfigName As VariantDim i As LongDim retval As BooleanDim swView As SldWorks.view

Sub main()Response = MsgBox("Create third angle projection?", vbYesNo)If Response = vbYes ThenThirdAngle = True

ElseThirdAngle = False

End If

Set swApp = Application.SldWorksSet swModel = swApp.ActiveDocSet swDraw = swApp.NewDocument(TemplateName, PaperSize, _

0#, 0#)ConfigNamesArray = swModel.GetConfigurationNames

Dim isFirstSheet As BooleanisFirstSheet = TrueFor i = 0 To UBound(ConfigNamesArray)ConfigName = ConfigNamesArray(i)If isFirstSheet = True ThenswDraw.ActivateSheet "Sheet1"Dim swSheet As SheetSet swSheet = swDraw.GetCurrentSheetswSheet.SetName ConfigName

Elseretval = swDraw.NewSheet3(ConfigName, TemplateSize, _

PaperSize, ScaleNum, ScaleDenom, Not ThirdAngle, "", _0#, 0#, "")

End IfisFirstSheet = FalseIf ThirdAngle = True Thenretval = swDraw.Create3rdAngleViews2(swModel.GetPathName)

Elseretval = swDraw.Create1stAngleViews2(swModel.GetPathName)

End IfswDraw.CreateDrawViewFromModelView swModel.GetPathName, _

"*Isometric", 0.2635088599471, 0.1934578136726, 0swDraw.ViewDisplayShadedretval = swDraw.InsertModelAnnotations(0, False, _

swConst.swInsertDimensions + swConst.swInsertNotes, _True)

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 185: API Api2006 Draft

API Fundamentals Exercise 10:Drawing Automation

175

Set swView = swDraw.GetFirstViewDo While Not swView Is NothingswView.ReferencedConfiguration = ConfigNameSet swView = swView.GetNextView

LoopswDraw.ForceRebuild

Const SaveAsPath As String = "C:\SolidWorks 2006 Training _Files\API Fundamentals\"

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 iEnd Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 186: API Api2006 Draft

Exercise 10: API FundamentalsDrawing Automation

176

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 187: API Api2006 Draft

API Fundamentals

177

Lesson 7

Selection and TraversalTechniques

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

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 188: API Api2006 Draft

Lesson 7 API FundamentalsSelection and Traversal Techniques

178

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 189: API Api2006 Draft

API Fundamentals Lesson 7Selection and Traversal Techniques

Case Study: Programming With a Selected Object 179

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.

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

Set swApp = Application.SldWorksSet swModel = swApp.ActiveDoc

End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 190: API Api2006 Draft

Lesson 7 API FundamentalsSelection and Traversal Techniques

180 Case Study: Programming With a Selected Object

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.SelectionMgrSet SelMgr = ModelDoc2.SelectionManager.

Counting Selected

Objects

To determine the number of selected objects, use SelectionMgr::GetSelectedObjectCount.

3 Add the following code.

Connect to the Selection Manager and return the object count.

Private Sub cmdGenerate_Click()Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swSelMgr As SldWorks.SelectionMgrDim count As longSet swSelMgr = swModel.SelectionManagercount = swSelMgr.GetSelectedObjectCountIf count <> 1 ThenswApp.SendMsgToUser2 "Please select only Extrude1.", _

swMbWarning, swMbOkMe.HideExit Sub

End IfEnd Sub

ModelDoc2::SelectionManager

SelectionMgr = ModelDoc2.SelectionManager

Output: SelectionMgr Pointer a Dispatch object, the SelectionMgr object for this document

SelectionMgr::GetSelectedObjectCountretval = SelectionMgr.GetSelectedObjectCount ( )

Return: retval Number of currently selected objects.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 191: API Api2006 Draft

API Fundamentals Lesson 7Selection and Traversal Techniques

Case Study: Programming With a Selected Object 181

Accessing Selected Objects

To get an interface pointer to a currently selected object use SelectionMgr::GetSelectedObject5.

Getting Selected Object Types

To determine the selected object type use SelectionMgr::GetSelectedObjectType2.

Getting Feature Type Names

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

4 Declare a feature variable.

Add the variable in the button click event.

Private Sub cmdGenerate_Click()Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swSelMgr As SldWorks.SelectionMgrDim count As longDim Feature As SldWorks.Feature

Set swApp = Application.SldWorksSet swModel = swApp.ActiveDocSet swSelMgr = swModel.SelectionManagercount = swSelMgr.GetSelectedObjectCount

SelectionMgr::GetSelectedObject5retval = 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

SelectionMgr::GetSelectedObjectType2retval = 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

Feature::GetTypeNameretval = Feature.GetTypeName ( )

Return: retval Feature type. See API Help file for full list.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 192: API Api2006 Draft

Lesson 7 API FundamentalsSelection and Traversal Techniques

182 Case Study: Programming With a Selected Object

5 Return a pointer to the selected feature.

Scroll down and add the following code:

If count > 1 ThenswApp.SendMsgToUser2 "Please select only Extrude1.", _

swMbWarning, swMbOkMe.HideExit Sub

End IfSet Feature = swSelMgr.GetSelectedObject5(count)If Not Feature.GetTypeName = “Extrusion” ThenswApp.SendMsgToUser "Please select only Extrude1."Exit Sub

End IfEnd 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.

Accessing Selections

To allow access to the entities used to create the feature, use the FeatureData::AccessSelections method from any of the FeatureData types. Because this method puts the model into a rollback state, use it only when you need to access the entity selections used to create the feature. It is not needed to change simple exposed properties on a FeatureData object.

Feature::GetDefinitionretval = Feature.GetDefintion ( )

Return: retval Dispatch pointer to the feature definition object. See API Help file for full list of feature objects.

ExtrudeFeatureData2::AccessSelectionsaccessGained = ExtrudeFeatureData2.AccessSelections (TopDoc, Component)

Return: accessGained TRUE if the selections were accessed successfully, FALSE if not.

Input: TopDoc Top-level document.

Input: Component Component in which the feature is to be modified.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 193: API Api2006 Draft

API Fundamentals Lesson 7Selection and Traversal Techniques

Case Study: Programming With a Selected Object 183

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 feature’s data is not modified.

If the FeatureData object’s data is modified, another method is used to regenerate the feature with the new data. This method, Feature::ModifyDefinition, will be explained shortly.

6 Connect to a FeatureData object.

Add the following code to connect to the ExtrudeFeatureData object.

Private Sub cmdGenerate_Click()Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swSelMgr As SldWorks.SelectionMgrDim count As longDim Feature As SldWorks.FeatureDim ExtrudeFeatureData As Sldworks.ExtrudeFeatureData2Dim retval As Boolean

Set swApp = Application.SldWorksSet swModel = swApp.ActiveDocSet swSelMgr = swModel.SelectionManagercount = swSelMgr.GetSelectedObjectCountIf count > 1 ThenswApp.SendMsgToUser "Please select only Extrude1."Me.HideExit Sub

End IfSet Feature = swSelMgr.GetSelectedObject5(count)If Not Feature.GetTypeName = swTnExtrusion ThenswApp.SendMsgToUser2 "Please select the Extrude1.", _

swMbWarning, swMbOkExit Sub

End IfSet 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.

ExtrudeFeatureData2::ReleaseSelectionAccessvoid ExtrudeFeatureData2.ReleaseSelectionAccess ( )

Return: void No return value.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 194: API Api2006 Draft

Lesson 7 API FundamentalsSelection and Traversal Techniques

184 Case Study: Programming With a Selected Object

Modify the Object Definition

Finally, call Feature::ModifyDefinition to implement changes.

7 Modify extrude depth.

Add the following code entries to modify the depth of the extruded feature.

Private Sub cmdGenerate_Click()Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swSelMgr As SldWorks.SelectionMgrDim count As longDim Feature As SldWorks.FeatureDim ExtrudeFeatureData As SldWorks.ExtrudeFeatureData2Dim retval As BooleanDim Depth As DoubleDim Factor As Integer

Factor = CInt(txtDepth.Text)Set swApp = Application.SldWorksSet swModel = swApp.ActiveDocSet swSelMgr = swModel.SelectionManagercount = swSelMgr.GetSelectedObjectCountIf count > 1 ThenswApp.SendMsgToUser2 "Please select only Extrude1.", _

swMbWarning, swMbOkMe.HideExit Sub

End IfSet Feature = swSelMgr.GetSelectedObject5(count)If Not Feature.GetTypeName = swTnExtrusion ThenswApp.SendMsgToUser2 "Please select the Extrude1.", _

swMbWarning, swMbOkExit Sub

End IfSet ExtrudeFeatureData = Feature.GetDefinitionDepth = ExtrudeFeatureData.GetDepth(True)ExtrudeFeatureData.SetDepth True, Depth * Factorretval = Feature.ModifyDefinition _

(ExtrudeFeatureData, swModel, Nothing)End Sub

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

Return: retval TRUE if the feature is updated successfully, FALSE if not.

Input: Definition Dispatch pointer to the feature definition object.

Input: TopDoc Top-level document.

Input: Component Component for the feature.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 195: API Api2006 Draft

API Fundamentals Lesson 7Selection and Traversal Techniques

The SolidWorks BREP Model 185

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

� 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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 196: API Api2006 Draft

Lesson 7 API FundamentalsSelection and Traversal Techniques

186 The SolidWorks BREP Model

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 197: API Api2006 Draft

API Fundamentals Lesson 7Selection and Traversal Techniques

Case Study: Body and Face Traversal 187

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:

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

1 Open an existing part and create a new macro.

Open the part BodyFaceTraversal.sldprt.

Click and name the macro BodyFaceTraversal.swp.

2 Add code to Sub Main.

Connect to SolidWorks and the active document.

Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Sub main()Set swApp = Application.SldWorksIf Not swApp Is Nothing ThenSet swModel = swApp.ActiveDocIf Not swModel Is Nothing ThenEnd IfSet swModel = Nothing

End IfSet swApp = Nothing

End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 198: API Api2006 Draft

Lesson 7 API FundamentalsSelection and Traversal Techniques

188 Case Study: Body and Face Traversal

3 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.PartDocSub main()Set swApp = Application.SldWorksIf Not swApp Is Nothing ThenSet swModel = swApp.ActiveDocIf Not swModel Is Nothing Then'Notice the Explicit Type CastingSet swPart = swModelIf Not swPart Is Nothing Then

End IfSet swPart = Nothing

End IfSet swModel = Nothing

End IfSet 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::GetBodies2retval = PartDoc.GetBodies2 (BodyType, VisibleOnly)

Return: retval SafeArray of dispatch pointers to the bodies.

Input: BodyType swSolidBody - solid bodyswSheetBody - sheet bodyswWireBody - wire bodyswMinimumBody - point bodyswGeneralBody - general, non-manifold bodyswEmptyBody - NULL bodyswAllBodies - all solid bodies

Input: VisibleOnly TRUE gets only the visible bodies, FALSE gets all of the bodies in the part.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 199: API Api2006 Draft

API Fundamentals Lesson 7Selection and Traversal Techniques

Case Study: Body and Face Traversal 189

4 Return the array body object pointers.Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swPart As SldWorks.PartDocDim retval As Variant

Sub main()Set swApp = Application.SldWorksIf Not swApp Is Nothing ThenSet swModel = swApp.ActiveDocIf Not swModel Is Nothing ThenSet swPart = swModelIf Not swPart Is Nothing Thenretval = swPart.GetBodies2(swConst.swSolidBody, True)

End IfSet swPart = Nothing

End IfSet swModel = Nothing

End IfSet swApp = Nothing

End Sub

5 Declare an indexer and a face pointer.Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swPart As SldWorks.PartDocDim retval As VariantDim i As IntegerDim swFace As SldWorks.face2

6 Program a loop to traverse the faces.Sub main()Set swApp = Application.SldWorksIf Not swApp Is Nothing ThenSet swModel = swApp.ActiveDocIf Not swModel Is Nothing ThenSet swPart = swModelIf Not swPart Is Nothing Thenretval = swPart.GetBodies2(swSolidBody, True)For i = 0 To UBound(retval)Set swFace = retval(i).GetFirstFaceDo While Not swFace Is Nothing

LoopNext i

End IfSet swPart = Nothing

End IfSet swModel = Nothing

End IfSet swApp = Nothing

End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 200: API Api2006 Draft

Lesson 7 API FundamentalsSelection and Traversal Techniques

190 Case Study: Body and Face Traversal

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.

7 Declare an array to hold face material properties.Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swPart As SldWorks.PartDocDim retval As VariantDim i As IntegerDim swFace As SldWorks.face2Dim matProps(8) As Double

Face2::MaterialPropertyValuesMaterialPropertyValues = Face2.MaterialPropertyValues ‘ Gets propertyFace2.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) - RedMaterialPropertyValues(1) - GreenMaterialPropertyValues(2) - BlueMaterialPropertyValues(3) - AmbientMaterialPropertyValues(4) - DiffuseMaterialPropertyValues(5) - SpecularMaterialPropertyValues(6) - ShininessMaterialPropertyValues(7) - Transparency

MaterialPropertyValues(8) - Emission

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 201: API Api2006 Draft

API Fundamentals Lesson 7Selection and Traversal Techniques

Case Study: Body and Face Traversal 191

8 Set up an array of material properties.

Then add the code to pass the array to the current face.

Sub main()Set swApp = Application.SldWorksIf Not swApp Is Nothing ThenSet swModel = swApp.ActiveDocIf Not swModel Is Nothing ThenSet swPart = swModelIf Not swPart Is Nothing Thenretval = swPart.GetBodies2(swConst.swSolidBody, True)For i = 0 To UBound(retval)Set swFace = retval(i).GetFirstFacematProps(0) = 1matProps(1) = 0matProps(2) = 0matProps(3) = 1matProps(4) = 1matProps(5) = 0.3matProps(6) = 0.3matProps(7) = 0matProps(8) = 0Do While Not swFace Is NothingswFace.MaterialPropertyValues = ((matProps))

LoopNext i

End IfSet swPart = Nothing

End IfSet swModel = Nothing

End IfSet swApp = Nothing

End Sub

Important! 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.

9 Traverse remaining faces.Do While Not swFace Is NothingswFace.MaterialPropertyValues = ((matProps))swModel.GraphicsRedraw2Set swFace = swFace.GetNextFace

LoopNext i

End IfSet swPart = Nothing

End IfSet swModel = Nothing

End IfSet swApp = Nothing

End Sub

10 Save and run macro.

Return to VBA when finished.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 202: API Api2006 Draft

Lesson 7 API FundamentalsSelection and Traversal Techniques

192 Case Study: Feature Manager Traversal

Case Study: Feature Manager Traversal

This macro traverses the FeatureManager design tree and retrieves each feature’s screen and type name. The code sets each feature’s 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.

1 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:FirstFeatureretval = ModelDoc2.FirstFeature ( )

Return: retval Pointer to dispatch object for the 1st feature in the document.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 203: API Api2006 Draft

API Fundamentals Lesson 7Selection and Traversal Techniques

Case Study: Feature Manager Traversal 193

Consecutive calls to Feature::GetNextFeature in this loop would continue the traversal

2 Add the feature traversal code.Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swFeature As SldWorks.feature

Sub main()Set swApp = Application.SldWorksIf Not swApp Is Nothing ThenSet swModel = swApp.ActiveDocIf Not swModel Is Nothing ThenSet swFeature = swModel.FirstFeatureWhile Not swFeature Is NothingSet swFeature = swFeature.GetNextFeature

WendEnd IfSet swModel = Nothing

End IfSet 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 swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swFeature As SldWorks.featureDim FeatName As StringDim FeatType As String

Feature:GetNextFeatureretval = Feature.GetNextFeature ( )

Return: retval Dispatch pointer to the next feature.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 204: API Api2006 Draft

Lesson 7 API FundamentalsSelection and Traversal Techniques

194 Case Study: Feature Manager Traversal

4 Return the feature name and type to the user.Sub main()Set swApp = Application.SldWorksIf Not swApp Is Nothing ThenSet swModel = swApp.ActiveDocIf Not swModel Is Nothing ThenSet swFeature = swModel.FirstFeatureWhile Not swFeature Is NothingFeatName = swFeature.NameFeatType = swFeature.GetTypeNameMsgBox "Feature screen name = " & FeatName & vbCrLf & _

"Feature type name = " & FeatTypeSet swFeature = swFeature.GetNextFeature

WendEnd IfSet swModel = Nothing

End IfSet swApp = Nothing

End Sub

5 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::SetSuppressionsuppressSet = Feature.SetSuppression (suppressState)

Return: suppressSet TRUE if the suppression state was successfully set, FALSE if not.

Input: suppressState swSuppressFeatureswUnSuppressFeatureswUnSuppressDependent

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 205: API Api2006 Draft

API Fundamentals Lesson 7Selection and Traversal Techniques

Case Study: Feature Manager Traversal 195

6 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.SldWorksDim swModel As SldWorks.ModelDoc2Dim swFeature As SldWorks.featureDim FeatName As StringDim FeatType As StringDim swSubFeature As SldWorks.featureDim SubFeatName As StringDim SubFeatType As StringSub main()Set swApp = Application.SldWorksIf Not swApp Is Nothing ThenSet swModel = swApp.ActiveDocIf Not swModel Is Nothing ThenSet swFeature = swModel.FirstFeatureWhile Not swFeature Is NothingFeatName = swFeature.NameFeatType = swFeature.GetTypeNameIf FeatType = "Fillet" ThenDim suppressSet As BooleanDim suppressState As LongsuppressSet = swFeature.SetSuppression_

(swConst.swSuppressFeature)End If‘ MsgBox "Feature screen name = " & FeatName & vbCrLf & _

"Feature type name = " & FeatTypeSet swFeature = swFeature.GetNextFeature

WendEnd IfSet swModel = Nothing

End IfSet swApp = Nothing

End Sub

7 Save and run macro.

Return to VBA when finished.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 206: API Api2006 Draft

Lesson 7 API FundamentalsSelection and Traversal Techniques

196 Case Study: Feature Manager Traversal

Setting Feature UI State

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

8 Hide all features.

Edit the code to hide all of the features in the FeatureManager design tree.

Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swFeature As SldWorks.featureDim FeatName As StringDim FeatType As StringDim swSubFeature As SldWorks.featureDim SubFeatName As StringDim SubFeatType As String

Sub main()Set swApp = Application.SldWorksIf Not swApp Is Nothing ThenSet swModel = swApp.ActiveDocIf Not swModel Is Nothing ThenSet swFeature = swModel.FirstFeatureWhile Not swFeature Is NothingswFeature.SetUIState swConst.swIsHiddenInFeatureMgr, _TrueSet swFeature = swFeature.GetNextFeature

WendswModel.ForceRebuildEnd IfSet swModel = Nothing

End IfSet swApp = Nothing

End Sub

9 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 The Undo command will not work for UI settings.

Feature::SetUIStateFeature.SetUIState (StateType, Flag)

Input: StateType swIsHiddenInFeatureMgr

Input: Flag TRUE hides the display of the feature in the FeatureManager design tree, FALSE otherwise.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 207: API Api2006 Draft

API Fundamentals Lesson 7Selection and Traversal Techniques

Case Study: Feature Manager Traversal 197

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.

11 Modify code.

Remove the feature traversal code, and substitute the call to ModelDoc2::FeatureByPositionReverse.

Sub main()Set swApp = Application.SldWorksIf Not swApp Is Nothing ThenSet swModel = swApp.ActiveDocIf Not swModel Is Nothing ThenSet swFeature = swModel.FeatureByPositionReverse(2)FeatName = swFeature.NameFeatType = swFeature.GetTypeNameMsgBox "Feature screen name = " & FeatName & vbCrLf & _

"Feature type name = " & FeatTypeSet swModel = Nothing

End ifSet swApp = Nothing

End IfEnd Sub

12 Save and run macro.

13 Exit macro.

ModelDoc2::FeatureByPositionReverseretval = 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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 208: API Api2006 Draft

Lesson 7 API FundamentalsSelection and Traversal Techniques

198 Case Study: Feature Manager Traversal

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 209: API Api2006 Draft

API Fundamentals Exercise 11:Handling Preselection 1

199

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.SelectionManagerSelectionMgr.GetSelectedObjectType2SelectionMgr.GetSelectedObject5Face2.GetSurface

Procedure 1. Open bottomcase.sldprt.2. Open DistanceBetweenFaces.swp.3. Use the APIs listed above to handle the preselection.4. Save and run macro.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 210: API Api2006 Draft

Exercise 11: API FundamentalsHandling Preselection 1

200

Solution Const ParallelDistTolerance As Double = 0.0001

Function Sq(Num As Double) As DoubleSq = Num * Num

End Function

Sub main()Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swSelMgr As SldWorks.SelectionMgrDim SelType1 As LongDim SelType2 As LongDim swFace1 As SldWorks.face2Dim swFace2 As SldWorks.face2Dim swSurf1 As SldWorks.surfaceDim swSurf2 As SldWorks.surfaceDim varSelPt1 As VariantDim varSelPt2 As VariantDim varClosePt1 As VariantDim varClosePt2 As VariantDim Dist1 As DoubleDim Dist2 As DoubleDim bRet As Boolean

Set swApp = Application.SldWorksSet swModel = swApp.ActiveDocSet swSelMgr = swModel.SelectionManagerSelType1 = swSelMgr.GetSelectedObjectType2(1)SelType2 = swSelMgr.GetSelectedObjectType2(2)

If SelType1 <> swSelFACES Or SelType2 <> swSelFACES ThenExit Sub

End If

Set swFace1 = swSelMgr.GetSelectedObject5(1)Set swFace2 = swSelMgr.GetSelectedObject5(2)Set swSurf1 = swFace1.GetSurfaceSet swSurf2 = swFace2.GetSurfacevarSelPt1 = 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 ThenswApp.SendMsgToUser "Distance = " + _

Str(Round(Dist1 * 1000, 2)) + " mm"ElseswApp.SendMsgToUser "Faces not parallel"

End IfEnd Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 211: API Api2006 Draft

API Fundamentals Exercise 12:Handling Preselection 2

201

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.SelectionManagerSelectionMgr.GetSelectedObjectCountSelectionMgr.GetSelectedObjectType2SelectionMgr.GetSelectedObject5Edge.GetCurve

Procedure 1. Open bottomcase.sldprt.2. Open MultipleEdgeLength.swp.3. Use the APIs listed above to handle the preselection.4. Save and run macro.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 212: API Api2006 Draft

Exercise 12: API FundamentalsHandling Preselection 2

202

Solution Sub main()Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swPart As SldWorks.PartDocDim swSelMgr As SldWorks.SelectionMgrDim swSelObj As ObjectDim swEdge As SldWorks.EdgeDim swCurve As SldWorks.CurveDim varCurveParams As VariantDim SelType As LongDim SelCount As LongDim Length As DoubleDim bRet As BooleanDim i As LongDim retval As Double

Set swApp = CreateObject("SldWorks.Application")Set swModel = swApp.ActiveDocSet swSelMgr = swModel.SelectionManager

SelCount = swSelMgr.GetSelectedObjectCount

For i = 1 To SelCountSelType = swSelMgr.GetSelectedObjectType(i)If swSelEDGES = SelType ThenSet swSelObj = swSelMgr.GetSelectedObject5(i)Set swEdge = swSelObjSet swCurve = swEdge.GetCurvevarCurveParams = swEdge.GetCurveParams2retval = swCurve.GetLength(varCurveParams(6), _

varCurveParams(7))Length = Length + retval

End IfNext i

swApp.SendMsgToUser "Length = " + _Str(Round(Length * 1000, 2)) + " mm"

End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 213: API Api2006 Draft

API Fundamentals Exercise 13:Traversing the FeatureManager

203

Exercise 13:Traversing the FeatureManager

Objective To learn how to traverse a part and all it’s 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.FirstFeatureFeature.GetTypeNameFeature.GetDefinitionSimpleFilletFeatureData2.DefaultRadiusFeature.SelectSimpleFilletFeatureData2.FilletItemsCountSimpleFilletFeatureData2.AccessSelectionsFeature.ReleaseSelectionAccessFeature.GetNextFeature

Procedure 1. Open bottomcase.sldprt.2. Open CheckFillet.swp.3. Use the APIs listed above to handle the traversal.4. Save and run macro.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 214: API Api2006 Draft

Exercise 13: API FundamentalsTraversing the FeatureManager

204

Solution Const MinRadius = 0.005

Sub main()Dim swApp As SldWorks.SldWorksDim swPart As PartDocDim swFeat As featureDim FilletData As ObjectDim FilletItem As ObjectDim FeatTypeName As StringDim FilletCount As LongDim i As LongDim Radius As DoubleDim retval As BooleanDim SelFeat As Boolean

Set swApp = Application.SldWorksSet swPart = swApp.ActiveDocSet swFeat = swPart.FirstFeatureswPart.ClearSelectionDo While Not swFeat Is NothingFeatTypeName = swFeat.GetTypeNameIf FeatTypeName = "Fillet" ThenSet FilletData = swFeat.GetDefinitionRadius = FilletData.DefaultRadiusIf Radius <= MinRadius Thenretval = swFeat.Select(True)

End IfFilletCount = FilletData.FilletItemsCountIf FilletCount > 0 Thenretval = FilletData.AccessSelections(swPart, Nothing)For i = 0 To FilletCount - 1Set FilletItem = FilletData.GetFilletItemAtIndex(i)Radius = FilletData.GetRadius(FilletItem)If Radius <= MinRadius ThenSelFeat = TrueExit For

End IfNext iFilletData.ReleaseSelectionAccessIf SelFeat = True ThenSelFeat = Falseretval = swFeat.Select(True)

End IfEnd If

End IfSet swFeat = swFeat.GetNextFeature

LoopEnd Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 215: API Api2006 Draft

API Fundamentals

205

Lesson 8Adding Custom Properties

and Attributes

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

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 216: API Api2006 Draft

Lesson 8 API FundamentalsAdding Custom Properties and Attributes

206

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 217: API Api2006 Draft

API Fundamentals Lesson 8Adding Custom Properties and Attributes

Case Study: Custom Properties 207

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.

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

Sub main()Set swApp = Application.SldWorksSet swModel = swApp.ActiveDoc

End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 218: API Api2006 Draft

Lesson 8 API FundamentalsAdding Custom Properties and Attributes

208 Case Study: Custom Properties

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.

3 Add code to create a custom property.Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2

Sub main()Set swApp = Application.SldWorksSet swModel = swApp.ActiveDocswModel.AddCustomInfo3 ““, “MyTest”, swCustomInfoText, _

“This is a test.”End Sub

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

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

Return: retval TRUE if added, FALSE if not.

Input: Configuration Name of the configuration.

Input: FieldName Name of custom property.

Input: FieldType swCustomInfoUnknownswCustomInfoTextswCustomInfoDateswCustomInfoNumberswCustomInfoYesOrNo

Input: FieldValue Value of custom property.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 219: API Api2006 Draft

API Fundamentals Lesson 8Adding Custom Properties and Attributes

Case Study: Custom Properties 209

Setting and Getting Custom

Property Values

Use the ModelDoc2::CustomInfo2 method to get and set custom property information for the document.

5 Add code to return the custom property value to the user.Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim value As String

Sub main()Set swApp = Application.SldWorksSet swModel = swApp.ActiveDocswModel.AddCustomInfo3 ““, “MyTest”, swCustomInfoText, _

“This is a test.”‘ Retrieve the value of a custom property called MyTestvalue = swModel.CustomInfo2("", "MyTest")swApp.SendMsgToUser value‘ Change the value of a custom property called MyTestvalue = “Test has now changed!”swModel.CustomInfo2("", "MyTest") = valueswApp.SendMsgToUser swModel.CustomInfo2(““, “MyTest”)

End Sub

6 Save and run macro.

The custom information is returned, modified, and returned again to the user. Return to VBA when finished.

ModelDoc2::CustomInfo2value = ModelDoc2.CustomInfo2 (Configuration, FieldName) ‘ Gets custom infoModelDoc2.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.

Original Setting Modified Setting

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 220: API Api2006 Draft

Lesson 8 API FundamentalsAdding Custom Properties and Attributes

210 Case Study: Custom Properties

Getting Custom Property Names

Use the ModelDoc2::GetCustomInfoNames2 method to return the name list of the custom properties defined on the document.

Getting the Custom Property Count

Use the ModelDoc2::GetCustomInfoCount2 method to return the number of custom properties that have been added to the document.

7 Modify code.

Change the code to add multiple properties and then return their names to the user.

Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2

Sub main()Set swApp = Application.SldWorksSet swModel = swApp.ActiveDocswModel.AddCustomInfo3 "", "MyProp1", swCustomInfoNumber, "1"swModel.AddCustomInfo3 "", "MyProp2", swCustomInfoNumber, "2"swModel.AddCustomInfo3 "", "MyProp3", swCustomInfoNumber, "3"swModel.AddCustomInfo3 "", "MyProp4", swCustomInfoNumber, "4"

Dim retval() As StringDim i As Integer

retval = swModel.GetCustomInfoNames2("")For i = 0 To UBound(retval)swApp.SendMsgToUser2 retval(i), 0, 0

Next

Dim count As Longcount = swModel.GetCustomInfoCount2("")swApp.SendMsgToUser2 _

“You have “ & count & “ custom properties.”, 0, 0End Sub

ModelDoc2::GetCustomInfoNames2retval = ModelDoc2.GetCustomInfoNames2 (Configuration)

Return: retval Safearray containing an array of string values of the custom property names.

Input: Configuration Name of the configuration.

ModelDoc2::GetCustomInfoCount2count = ModelDoc2.GetCustomInfoCount2 (Configuration)

Output: count Number of custom information fields.

Input: Configuration Name of the configuration.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 221: API Api2006 Draft

API Fundamentals Lesson 8Adding Custom Properties and Attributes

Case Study: Configurations With Custom Properties 211

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

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 222: API Api2006 Draft

Lesson 8 API FundamentalsAdding Custom Properties and Attributes

212 Case Study: Configurations With Custom

1 Open part.

Open the file CustomProperties.sldprt. It has three configurations.

2 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.SldWorksSet swModel = swApp.ActiveDocretval = swModel.GetConfigurationNames()For i = 0 To UBound(retval)‘ swApp.SendMsgToUser2 retval(i), 0, 0swModel.ShowConfiguration2 retval(i)swModel.SetUserPreferenceIntegerValue _

swConst.swUnitsLinear, swConst.swCM

Dim density As Doubledensity = 2700swModel.SetUserPreferenceDoubleValue _

swConst.swMaterialPropertyDensity, densityswModel.SetUserPreferenceStringValue _

swConst.swMaterialPropertyCrosshatchPattern, _"ISO (Aluminum)"

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 223: API Api2006 Draft

API Fundamentals Lesson 8Adding Custom Properties and Attributes

Case Study: Configurations With Custom Properties 213

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::GetMassPropertiesretval = 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 is1 = default2 = maximum

Output: status Status of the mass property results as defined in swMassPropertiesStatus_e

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 224: API Api2006 Draft

Lesson 8 API FundamentalsAdding Custom Properties and Attributes

214 Case Study: Configurations With Custom

5 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 Doubledensity = 2700swModel.SetUserPreferenceDoubleValue _

SwConst.swMaterialPropertyDensity, densityswModel.SetUserPreferenceStringValue _

SwConst.swMaterialPropertyCrosshatchPattern, _"ISO (Aluminum)"

Dim massprops As VariantDim status As Longmassprops = 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")

NextEnd Sub

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 225: API Api2006 Draft

API Fundamentals Lesson 8Adding Custom Properties and Attributes

Case Study: Configurations With Custom Properties 215

6 Save and run the macro.

Check the custom properties of each configuration against the system results for mass properties. They will match.

Density:

2.70 g/cm3

Mass:

96.20 gVolume:

35.63 cm3

Area:

405.63 cm2

Configuration: 2 Hole

Density:

2.70 g/cm3

Mass:

95.99 gVolume:

35.55 cm3

Area:

405.08 cm2

Configuration: 3 Hole

Density:

2.70 g/cm3

Mass:

95.78 gVolume:

35.47 cm3

Area:

404.51 cm2

Configuration: 4 Hole

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 226: API Api2006 Draft

Lesson 8 API FundamentalsAdding Custom Properties and Attributes

216 Case Study: File Summary Information

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.

1 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.SldWorksDim swModel As SldWorks.ModelDoc2Dim text As String

Sub main()Set swApp = Application.SldWorksSet 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

ModelDoc2::SummaryInfovalue = 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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 227: API Api2006 Draft

API Fundamentals Lesson 8Adding Custom Properties and Attributes

Case Study: Document Attributes 217

2 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 attribute’s 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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 228: API Api2006 Draft

Lesson 8 API FundamentalsAdding Custom Properties and Attributes

218 The Attribute Objects

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: [email protected]

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

Sub main()Set swApp = Application.SldWorksSet swModel = swApp.ActiveDoc

End Sub

The Attribute Objects

There are three SolidWorks objects used when creating and working with custom attributes. These objects are highlighted in the tables below.

AttributeDef Object(swAttDef)

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.attributeDefSet swAttDef = swApp.DefineAttribute (UniqueName)

AttributeDef Methods

.AddParameter (NameIn, Type, DefaultValue, Options)

.Register

.CreateInstance3 (Doc, Comp, Ent, NameIn, Options, CfgOption)

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 229: API Api2006 Draft

API Fundamentals Lesson 8Adding Custom Properties and Attributes

The Attribute Objects 219

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.SldWorksDim swModel As SldWorks.ModelDoc2Dim swAttDef As SldWorks.attributeDef

Sub main()Set swApp = Application.SldWorksSet swModel = swApp.ActiveDocSet swAttDef = swApp.DefineAttribute(“pubMyDocAttributeDef”)

End Sub

Attribute Object(swAttr)

To create instances of the attribute definition to a SolidWorks document, connect to the attribute object using the AttributeDef::CreateInstance3, as the accessor:

Dim swAtt As SldWorks.AttributeSet swAtt = swAttDef.CreateInstance3 (Name)

Attribute Methods

.GetParameter (NameIn)

.GetName

.GetEntity

.GetBody

.Delete

Parameter Object(swParam)

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:

Dim swParam As SldWorks.ParameterSet swParam = swAtt.GetParameter (Name)

Parameter Methods

.GetName

.GetType

.GetDoubleValue & .SetDoubleValue

.GetStringValue & .SetStringValue

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 230: API Api2006 Draft

Lesson 8 API FundamentalsAdding Custom Properties and Attributes

220 The Attribute Objects

4 Add the attribute’s parameters and register it.Set swAttDef = swApp.DefineAttribute("pubMyDocAttributeDef")swAttDef.AddParameter "MyFirstParameter", _

swConst.swParamTypeDouble, 10, 0swAttDef.AddParameter "MySecondParameter", _

swConst.swParamTypeDouble, 20, 0swAttDef.Register

End Sub

5 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.attributeDefDim swAtt As SldWorks.AttributeSub main()Set swApp = Application.SldWorksSet swModel = swApp.ActiveDocSet swAttDef = swApp.DefineAttribute("pubMyDocAttributeDef")swAttDef.AddParameter "MyFirstParameter", _

swConst.swParamTypeDouble, 10, 0

swAttDef.AddParameter "MySecondParameter", _swConst.swParamTypeDouble, 20, 0

swAttDef.RegisterSet swAtt = swAttDef.CreateInstance5(swModel, Nothing, _

"MyDocAttribute", 0, SwConst.swAllConfiguration)End Sub

Note Creating an attribute directly on model geometry is demonstrated in the next case study.

6 Display the attribute’s parameter values.

The following code displays the attributes parameter values.

Dim swAttDef As SldWorks.attributeDefDim swAtt As SldWorks.AttributeDim swParam1 As SldWorks.ParameterDim swParam2 As SldWorks.ParameterSub main()Set swApp = Application.SldWorksSet swModel = swApp.ActiveDocSet swAttDef = swApp.DefineAttribute("pubMyDocAttributeDef")swAttDef.AddParameter "MyFirstParameter", _

swConst.swParamTypeDouble, 10, 0swAttDef.AddParameter "MySecondParameter", _

swConst.swParamTypeDouble, 20, 0swAttDef.RegisterSet 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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 231: API Api2006 Draft

API Fundamentals Lesson 8Adding Custom Properties and Attributes

Case Study: Face Attributes 221

7 Save and run macro.

Look at the FeatureManager design tree. The last feature is the attribute that was created by the macro.

8 Exit macro.

Case Study: Face Attributes

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:

� Feed Rate� Speed Rate� XPosition� YPosition� ZPosition� Hole Depth� Hole Diameter

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 232: API Api2006 Draft

Lesson 8 API FundamentalsAdding Custom Properties and Attributes

222 Case Study: Face Attributes

1 Open the part and macro.

Open the part Drillplate.sldprt and the macro FaceAttribute.swp.

In VBA, display UserForm1 by double-clicking on it from the Project Explorer

window.

2 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, 0swAttDef.AddParameter "SpeedRate", _

swConst.swParamTypeDouble,20, 0swAttDef.AddParameter "XPos", _

swConst.swParamTypeDouble,0, 0swAttDef.AddParameter "YPos", _

swConst.swParamTypeDouble,0, 0swAttDef.AddParameter "ZPos", _

swConst.swParamTypeDouble,0, 0swAttDef.AddParameter "Depth", _

swConst.swParamTypeDouble,0, 0swAttDef.AddParameter "HoleDiameter", _

swConst.swParamTypeDouble,0, 0swAttDef.Register

Important! 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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 233: API Api2006 Draft

API Fundamentals Lesson 8Adding Custom Properties and Attributes

Case Study: Face Attributes 223

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 model’s cylindrical faces.

Private Sub cmdGenerateMachiningInfo_Click()

Set swPart = swModelIf Not swPart Is Nothing Thenretval = swPart.GetBodies2(swConst.swSolidBody, True)For i = 0 To UBound(retval)Dim j As Integerj = 0Set swFace = retval(i).GetFirstFaceDo While Not swFace Is NothingDim swSurface As surfaceSet swSurface = swFace.GetSurfaceIf swSurface.IsCylinder Then Dim cylParams As VariantcylParams = swSurface.CylinderParamsSet swAtt = swAttDef.CreateInstance5(swModel, _

swFace, "MyFaceAttribute-" & j, 0, _swConst.swAllConfiguration)

j = j + 1End IfSet swFace = swFace.GetNextFace

LoopNext i

End IfSet swPart = Nothing

End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 234: API Api2006 Draft

Lesson 8 API FundamentalsAdding Custom Properties and Attributes

224 Case Study: Face Attributes

4 Set the attribute’s 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 ThenSet 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 = NothingEnd Ifj = j + 1

End IfSet swFace = swFace.GetNextFace

LoopNext i

End IfSet swPart = Nothing

End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 235: API Api2006 Draft

API Fundamentals Lesson 8Adding Custom Properties and Attributes

Case Study: Face Attributes 225

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.

5 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.SelectionMgrSet swSelMgr = swModel.SelectionManagerDim swCallout As SldWorks.CalloutSet swCallout = swSelMgr.CreateCalloutswCallout.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) * 2

swFace.Select3 True, 0, swCalloutSet swAtt = Nothing

Callouts Displayed on the Model

Callout Object(swCallOut)

To create instances of a Callout object, use SelectionMgr::CreateCallout, as the accessor:Dim swCallout As SldWorks.CalloutSet swCallout = swSelMgr.CreateCallout

Callout Members

.Label

.Target Style

.TextBoxPre-Rele

ase

Do not copy o

r distr

ibute

Page 236: API Api2006 Draft

Lesson 8 API FundamentalsAdding Custom Properties and Attributes

226 Case Study: Face 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.

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

6 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 BooleanFirstPass = TrueDim i As Integeri = 0swModel.ClearSelection2 (True)Dim swFeature As SldWorks.featureSet swFeature = swModel.FirstFeatureWhile Not swFeature Is NothingIf swFeature.GetTypeName = "Attribute" Then swFeature.Select2 True, 0Set swAtt = swFeature.GetSpecificFeature

Dim paramHoleDia As SldWorks.ParameterSet paramHoleDia = swAtt.GetParameter("HoleDiameter")

Dim paramFeedRate As SldWorks.ParameterSet paramFeedRate = swAtt.GetParameter("FeedRate")

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 237: API Api2006 Draft

API Fundamentals Lesson 8Adding Custom Properties and Attributes

Case Study: Face Attributes 227

Dim paramSpeedRate As SldWorks.ParameterSet paramSpeedRate = swAtt.GetParameter("SpeedRate")

Dim paramXPos As SldWorks.ParameterSet paramXPos = swAtt.GetParameter("XPos")

Dim paramYPos As SldWorks.ParameterSet paramYPos = swAtt.GetParameter("YPos")

Dim paramZPos As SldWorks.ParameterSet paramZPos = swAtt.GetParameter("ZPos")

Dim paramDepth As SldWorks.ParameterSet paramDepth = swAtt.GetParameter("Depth")

If paramHoleDia.GetDoubleValue <> DrillDiameter Then FirstPass = Truei = i + 1

End IfDrillDiameter = paramHoleDia.GetDoubleValue If FirstPass = True Then ListBox1.AddItem "// Drill Dia = " & _

paramHoleDia.GetDoubleValueListBox1.AddItem "G50 X0 Y0 Z0 // Go Home"ListBox1.AddItem "G00 G05 T0" & iListBox1.AddItem "M03 S" & paramSpeedRate.GetDoubleValueListBox1.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

ElseListBox1.AddItem "X" & paramXPos.GetDoubleValue & _

" Y" & paramYPos.GetDoubleValue End IfFirstPass = False

End IfSet swFeature = swFeature.GetNextFeature

WendListBox1.AddItem "G50 X0 Y0 Z0"ListBox1.AddItem "M30"

End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 238: API Api2006 Draft

Lesson 8 API FundamentalsAdding Custom Properties and Attributes

228 Case Study: Face Attributes

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

8 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.Pre-

Release

Do not copy o

r distr

ibute

Page 239: API Api2006 Draft

API Fundamentals Lesson 8Adding Custom Properties and Attributes

Case Study: Face Attributes 229

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.

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.

AttributeDef::CreateInstance5retval = 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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 240: API Api2006 Draft

Lesson 8 API FundamentalsAdding Custom Properties and Attributes

230 Case Study: Face Attributes

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 241: API Api2006 Draft

API Fundamentals Exercise 14:Adding Mass Properties as Custom Properties

231

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.GetConfigurationNamesModelDoc2.ShowConfiguration2ModelDoc2.SetUserPreferenceIntegerValueModelDoc2.SetUserPreferenceStringValueModelDoc2.GetMassPropertiesModelDoc2.AddCustomInfo3

Procedure 1. Open latchpin.sldprt.2. Create a new macro named CustPropsMassProps.swp.3. Use the APIs listed above to automate custom properties.4. Save and run macro.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 242: API Api2006 Draft

Exercise 14: API FundamentalsAdding Mass Properties as Custom Properties

232

Solution Option ExplicitDim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim retval() As StringDim i As Integer

Sub main()Set swApp = Application.SldWorksSet swModel = swApp.ActiveDocretval = swModel.GetConfigurationNames()For i = 0 To UBound(retval)swModel.ShowConfiguration2 retval(i)swModel.SetUserPreferenceIntegerValue _

swConst.swUnitsLinear, swConst.swCM

Dim density As Doubledensity = 2700swModel.SetUserPreferenceDoubleValue _

swConst.swMaterialPropertyDensity, densityswModel.SetUserPreferenceStringValue _

swConst.swMaterialPropertyCrosshatchPattern, _ "ISO (Aluminum)"

Dim massprops As VariantDim status As Longmassprops = 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")

NextEnd Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 243: API Api2006 Draft

API Fundamentals Exercise 15:Adding Attributes to Edges

233

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:

� Determine it’s 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

� Traversing bodies.� Checking curve types.� Returning the length of a curve� Adding attribute information.� Adding callouts.

APIs Used SldWorks.DefineAttributeSldWorks.AddParameterSldWorks.RegisterPartDoc.GetBodies2Body2.GetFirstFaceBody2.GetEdgesEdge.GetCurveCurve.IsLineAttributeDef.CreateInstance3SelectionMgr.CreateCallout

Procedure 1. Open latchpin.sldprt.2. Open the macro EdgeAttributes.swp.3. Use the APIs listed above to automate adding edge attributes.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 244: API Api2006 Draft

Exercise 15: API FundamentalsAdding Attributes to Edges

234

Solution Option ExplicitDim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swPart As SldWorks.PartDocDim swAttDef As SldWorks.attributeDefDim swAtt As SldWorks.AttributeDim swAttParam As SldWorks.ParameterDim retval As VariantDim i As IntegerDim j As IntegerDim k As IntegerDim swFace As SldWorks.face2Dim bRet As Boolean

Private Sub UserForm_Activate()Set swApp = Application.SldWorksSet swModel = swApp.ActiveDoc

If swModel Is Nothing ThenMsgBox "There is no open document to run this macro on."Exit Sub

End If

If swModel.GetType <> swDocPART ThenMsgBox "This code only works on a part document."Exit Sub

End If

Set swAttDef = swApp.DefineAttribute("pubLineAttributeDef")swAttDef.AddParameter "LineLength", _

swConst.swParamTypeDouble, 10, 0swAttDef.Register

End Sub

Private Sub btnCreateLineAttributes_Click()()’ Traverse the body to find all of the cylindrical surfacesSet swPart = swModelIf Not swPart Is Nothing Thenretval = swPart.GetBodies2(swConst.swSolidBody, True)For i = 0 To UBound(retval)Dim j As Integerj = 0Set swFace = retval(i).GetFirstFaceDo While Not swFace Is NothingDim i_Edges As Varianti_Edges = swFace.GetEdgesFor k = 0 To UBound(i_Edges)Dim i_curve As CurveSet i_curve = i_Edges(k).GetCurveIf i_curve.IsLine ThenSet swAtt = swAttDef.CreateInstance5(swModel, _

i_Edges(k), "LineAttribute" & j, 0, _swConst.swAllConfiguration)

If Not swAtt Is Nothing ThenSet swAttParam = swAtt.GetParameter("LineLength")Dim curveParams As VariantcurveParams = i_Edges(k).GetCurveParams2Dim linelength As Double

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 245: API Api2006 Draft

API Fundamentals Exercise 15:Adding Attributes to Edges

235

linelength = i_curve.GetLength2(curveParams(6), _curveParams(7))

linelength = Round(linelength, 5)bRet = swAttParam.SetDoubleValue2(linelength,_

swConst.swAllConfiguration, "")Dim swSelMgr As SelectionMgrSet swSelMgr = swModel.SelectionManager

’ Create a callout objectDim swCallout As SldWorks.CalloutSet swCallout = swSelMgr.CreateCalloutswCallout.TargetStyle = _

swConst.swCalloutTargetStyle_e. _swCalloutTargetStyle_Arrow

’Set the label with the values of the geometry.swCallout.Label = "Edge " & j & " =" & linelengthListBox1.AddItem swCallout.Label

’ Use Select3 to add the callout to the selectionswFace.Select3 True, 0, swCalloutSet swAtt = Nothing

End IfEnd Ifj = j + 1

Next kSet swFace = swFace.GetNextFace

LoopNext iSet swPart = Nothing

End IfEnd SubPre-

Release

Do not copy o

r distr

ibute

Page 246: API Api2006 Draft

Exercise 15: API FundamentalsAdding Attributes to Edges

236

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 247: API Api2006 Draft

API Fundamentals

237

Lesson 9The SolidWorks API SDK

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

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 248: API Api2006 Draft

Lesson 9 API FundamentalsThe SolidWorks API SDK

238

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 249: API Api2006 Draft

API Fundamentals Lesson 9The SolidWorks API SDK

The API SDK 239

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

2 Double-click the SDK hyper link.

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 250: API Api2006 Draft

Lesson 9 API FundamentalsThe SolidWorks API SDK

240 The API SDK

3 Open the file.

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

4 Install the SDK.

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

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

5 Continue with installation.

Click Next.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 251: API Api2006 Draft

API Fundamentals Lesson 9The SolidWorks API SDK

The API SDK 241

6 Accept the License Agreement.

7 Add the customer information.

8 Choose the Custom configuration.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 252: API Api2006 Draft

Lesson 9 API FundamentalsThe SolidWorks API SDK

242 The API SDK

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 253: API Api2006 Draft

API Fundamentals Lesson 9The SolidWorks API SDK

The API SDK 243

11 Click Next.

12 Click Install.

13 Installation Progress.

This installation progress dialog is displayed.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 254: API Api2006 Draft

Lesson 9 API FundamentalsThe SolidWorks API SDK

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

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.

C

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 255: API Api2006 Draft

API Fundamentals Lesson 9The SolidWorks API SDK

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

2 Set the add-in options as shown.

Click Finish to complete the wizard.

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

Release

Do not copy o

r distr

ibute

Page 256: API Api2006 Draft

Lesson 9 API FundamentalsThe SolidWorks API SDK

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

4 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! 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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 257: API Api2006 Draft

API Fundamentals Lesson 9The SolidWorks API SDK

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

5 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 theSldWorks 2006 Type Library to add it to the Selected

Components list.

Leave the dialog open to add other references.

7 Add the constants type library.

Scroll down the list of Components double-click the Sldworks 2006 Constant type library.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 258: API Api2006 Draft

Lesson 9 API FundamentalsThe SolidWorks API SDK

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

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

Important! The following step is only necessary if the reference to the System.Drawing.dll was not created automatically by the add-in wizard.

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 259: API Api2006 Draft

API Fundamentals Lesson 9The SolidWorks API SDK

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

10 Build the project.

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

Comparing Addin DLLs and Stand-Alone Executables

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

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 260: API Api2006 Draft

Lesson 9 API FundamentalsThe SolidWorks API SDK

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

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! If a release build is compiled, the DLL will be located in the projects \Release directory.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 261: API Api2006 Draft

API Fundamentals Lesson 9The SolidWorks API SDK

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

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 262: API Api2006 Draft

Lesson 9 API FundamentalsThe SolidWorks API SDK

252 Case Study: Creating a C# Add-in

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

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 263: API Api2006 Draft

API Fundamentals Lesson 9The SolidWorks API SDK

Case Study: Creating a C# Add-in 253

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

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 264: API Api2006 Draft

Lesson 9 API FundamentalsThe SolidWorks API SDK

254 Case Study: Creating a C# Add-in

3 Build the project.

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

4 Start SolidWorks and load the add-in.

Load the DLL named SwCSharpAddin.DLL from the projects obj\Debug directory.

5 Examine the new menus.

6 Create a Cube.

From the SwCSharpAddin1 menu, click Create Cube.

7 Show the Property Page.

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

8 Examine the custom toolbar.

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 265: API Api2006 Draft

API Fundamentals Lesson 9The SolidWorks API SDK

Case Study: C++ Add-Ins 255

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 266: API Api2006 Draft

Lesson 9 API FundamentalsThe SolidWorks API SDK

256 Case Study: C++ Add-Ins

2 Review the names of the add-in object.

Keep the default names.

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 267: API Api2006 Draft

API Fundamentals Lesson 9The SolidWorks API SDK

Case Study: C++ Add-Ins 257

4 Select the SwOptions.

Click on the SwOptions link.

Click all of the options on this page.

Click Finish.

Compiling a C++

Add-In

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 268: API Api2006 Draft

Lesson 9 API FundamentalsThe SolidWorks API SDK

258 Case Study: C++ Add-Ins

5 Change the project properties.

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

Click the C/C++ folder.

Click the General sub item.

6 Change the directories.

Change the Additional Include Directories path property to:

C:\Program Files\SolidWorks.

Click OK.

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 269: API Api2006 Draft

API Fundamentals Lesson 9The SolidWorks API SDK

Case Study: C++ Add-Ins 259

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

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 270: API Api2006 Draft

Lesson 9 API FundamentalsThe SolidWorks API SDK

260 Case Study: C++ Add-Ins

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

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 271: API Api2006 Draft

API Fundamentals Lesson 9The SolidWorks API SDK

Case Study: C++ Add-Ins 261

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 272: API Api2006 Draft

Lesson 9 API FundamentalsThe SolidWorks API SDK

262 Case Study: C++ Add-Ins

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 273: API Api2006 Draft

API Fundamentals Lesson 9The SolidWorks API SDK

Choosing a Programming Language 263

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 274: API Api2006 Draft

Lesson 9 API FundamentalsThe SolidWorks API SDK

264 Choosing a Programming Language

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 275: API Api2006 Draft

API Fundamentals

265

Lesson 10Customizing the SolidWorks

User Interface

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

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 276: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

266

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 277: API Api2006 Draft

API Fundamentals Lesson 10Customizing the SolidWorks User Interface

Case Study: Customizing the UI With VB.NET 267

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:

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

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

1 Create a new SolidWorks VB.NET Add-In.

Name the add-in CustomSWAddin.

Click OK.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 278: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

268 Case Study: Customizing the UI With VB.NET

2 Set the add-in properties.

Click Finish.

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

4 Save the project.

From the File menu, click Save All.

5 Compile the DLL.

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 279: API Api2006 Draft

API Fundamentals Lesson 10Customizing the SolidWorks User Interface

Case Study: Customizing the UI With VB.NET 269

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

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

9 Close SolidWorks.

Return to Visual Studio.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 280: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

270 Case Study: Customizing the UI With VB.NET

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 281: API Api2006 Draft

API Fundamentals Lesson 10Customizing the SolidWorks User Interface

Case Study: Customizing the UI With VB.NET 271

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

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:

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

Note These keyboard shortcuts are slightly different from the debugging keyboard shortcuts in VBA.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 282: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

272 Understanding The Add-in Code

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 283: API Api2006 Draft

API Fundamentals Lesson 10Customizing the SolidWorks User Interface

Understanding The Add-in Code 273

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.

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.

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 284: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

274 Understanding The Add-in Code

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 285: API Api2006 Draft

API Fundamentals Lesson 10Customizing the SolidWorks User Interface

Understanding The Add-in Code 275

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.

18 Expand the ConnectToSW Function.

Expand the ConnectToSW function.

Study the code and comments.

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

Output: IsConnected TRUE if the add-in connected successfully, FALSE if not

Input: ThisSW Pointer to the SldWorks Dispatch object.

Input: Cookie Add-in ID.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 286: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

276 Understanding The Add-in Code

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.SetAddinCallbackInfoStatus = SldWorks.SetAddinCallbackInfo ( ModuleHandle, AddinCallbacks, Cookie )

Output: Status TRUE if the add-in connected successfully, FALSE if not

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 287: API Api2006 Draft

API Fundamentals Lesson 10Customizing the SolidWorks User Interface

Understanding The Add-in Code 277

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::AddMenuretval = SldWorks.AddMenu ( docType, menu, position )

Output: retval TRUE if the add-in connected successfully, FALSE if not

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 288: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

278 Understanding The Add-in Code

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.

22 Review the AddMenus sub program.

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

Menu positions:

1 2 3 4 5 6

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 289: API Api2006 Draft

API Fundamentals Lesson 10Customizing the SolidWorks User Interface

Understanding The Add-in Code 279

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.

Setting Up

Callbacks

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.

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

Output: IsMenuItemAdded TRUE if menu item is added, FALSE if not.

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

Release

Do not copy o

r distr

ibute

Page 290: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

280 Understanding The Add-in Code

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 291: API Api2006 Draft

API Fundamentals Lesson 10Customizing the SolidWorks User Interface

Understanding The Add-in Code 281

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 292: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

282 Understanding The Add-in Code

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:

Large Bitmaps Guide:

Toolbar Index 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.

16

16 x Number of Buttons16 pixels

pixels

Single Button Multiple Buttons

16

24

24 x Number of Buttons24 pixels

pixels

Multiple ButtonsSingle Button

24

0 1 2

3

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 293: API Api2006 Draft

API Fundamentals Lesson 10Customizing the SolidWorks User Interface

Understanding The Add-in Code 283

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.

T

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 294: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

284 Understanding The Add-in Code

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 295: API Api2006 Draft

API Fundamentals Lesson 10Customizing the SolidWorks User Interface

Understanding The Add-in Code 285

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 296: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

286 Understanding The Add-in Code

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:

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

SldWorks::AddToolbar4NewToolBarID = 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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 297: API Api2006 Draft

API Fundamentals Lesson 10Customizing the SolidWorks User Interface

Understanding The Add-in Code 287

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.

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

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

Output: IsToolbarCommandAdded TRUE if successful, FALSE if unsuccessful.

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 298: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

288 Understanding The Add-in Code

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:

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 299: API Api2006 Draft

API Fundamentals Lesson 10Customizing the SolidWorks User Interface

Property Pages 289

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.

� PropertyManagerPage2

� PropertyManagerPage2Handler2

The add-ins UserPMPPage class has two members that are used to respectively represent these interfaces:

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 300: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

290 Property Pages

PropertyManagerPage2

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.

PropertyManagerPage2Handler2

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.

Add-In

SldWorks

UserPMPage

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

SldWorks

Add-In ppage

This class member implements the PropertyManagerPage2 interface.

handler

This class member implements the PropertyManagerPage2Handler2 interface.

Group1Group2Option1Option2Option3

Checkbox1List1Selection1Num1Combo1

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 301: API Api2006 Draft

API Fundamentals Lesson 10Customizing the SolidWorks User Interface

Property Pages 291

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.

Display the page using PropertyManagerPage2::Show.

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.

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.

PropertyManagerPage2::Show

retval = PropertyManagerPage2.Show ( )

Output: retval Status of page creation. 0 = success, other values = failure.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 302: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

292 Property Page Groups and Controls

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

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 303: API Api2006 Draft

API Fundamentals Lesson 10Customizing the SolidWorks User Interface

Property Page Groups and Controls 293

Adding Group Boxes

Use the API method PropertyManagerPage2::AddGroupBox to add a group box to a custom PropertyManager page.

Group and control IDs

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

.

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

Output: retval Pointer to the newly created group box.

Input: Id Resource ID of the group box.

Input: Caption Title of the group box.

Input: Options Options as defined in swAddGroupBoxOptions_e.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 304: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

294 Property Page Groups and Controls

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 305: API Api2006 Draft

API Fundamentals Lesson 10Customizing the SolidWorks User Interface

Property Page Groups and Controls 295

The following table is a list of the different types of controls that can be added to PropertyManager pages.

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.

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

Checkable BitmapButton

.Checked

.IsCheckable

.SetBitmaps

.SetBitmapsByName

.SetStandardBitmaps

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 306: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

296 Property Page Groups and Controls

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

Release

Do not copy o

r distr

ibute

Page 307: API Api2006 Draft

API Fundamentals Lesson 10Customizing the SolidWorks User Interface

Property Page Groups and Controls 297

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 308: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

298 Property Page Groups and Controls

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 309: API Api2006 Draft

API Fundamentals Lesson 10Customizing the SolidWorks User Interface

Removing Menus and Toolbars 299

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.

Use SldWorks::RemoveMenu to remove any custom menus created by the add-in.

SwAddin::DisconnectFromSW

IsDisconnected = SwAddin.DisconnectFromSW ( )

Output: IsDisconnected TRUE if the add-in disconnected successfully, FALSE if not.

SldWorks::RemoveMenu

retval = SldWorks.RemoveMenu ( DocType, MenuItemString, CallbackFcnAndModule)

Output: retval TRUE if the menu item was removed successfully, FALSE if not.

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 .

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 310: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

300 Removing Menus and Toolbars

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

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.

SldWorks::RemoveToolbar2Status = 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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 311: API Api2006 Draft

API Fundamentals Lesson 10Customizing the SolidWorks User Interface

Removing Menus and Toolbars 301

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 312: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

302 Other Areas of Customization

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 313: API Api2006 Draft

API Fundamentals Lesson 10Customizing the SolidWorks User Interface

Other Areas of Customization 303

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 314: API Api2006 Draft

Lesson 10 API FundamentalsCustomizing the SolidWorks User Interface

304 Other Areas of Customization

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 315: API Api2006 Draft

API Fundamentals Exercise 16:Implement a New Menu

305

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. Run the SolidWorks VB.NET Addin Wizard.2. Create a Property Page when selecting the add-in options.3. Add a new menu item to the custom menu created by the add-in.4. Implement the callback method for the new menu item.5. The callback method creates an extruded cylinder.6. Compile the project and test the new menu item.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 316: API Api2006 Draft

Exercise 16: API FundamentalsImplement a New Menu

306

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 317: API Api2006 Draft

API Fundamentals Exercise 17:Implement Toolbar Buttons

307

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 318: API Api2006 Draft

Exercise 17: API FundamentalsImplement Toolbar Buttons

308

Solution

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 319: API Api2006 Draft

API Fundamentals Exercise 18:Implement Controls on a Property Manager Page

309

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. Remove all of the controls from the first group box2. Remove second group box3. Add a combobox and a button control to the first group box4. Implement the OnButtonPress event for the button.5. 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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 320: API Api2006 Draft

Exercise 18: API FundamentalsImplement Controls on a Property Manager Page

310

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 321: API Api2006 Draft

API Fundamentals Exercise 18:Implement Controls on a Property Manager Page

311

New user variable on the PMPageHandler object.

Code for the OnComboboxSelectionChanged event handler.

Code for the OnButtonPress event handler.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 322: API Api2006 Draft

Exercise 18: API FundamentalsImplement Controls on a Property Manager Page

312

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 323: API Api2006 Draft

API Fundamentals

313

Lesson 11Notifications

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

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 324: API Api2006 Draft

Lesson 11 API FundamentalsNotifications

314

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 325: API Api2006 Draft

API Fundamentals Lesson 11Notifications

Notifications 315

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:

� SldWorks

� PartDoc

� AssemblyDoc

� DrawingDoc

� ModelView

� FeatMgrView

� SwPropertySheet

Notifications in VBA

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 Procedure Pull Down Menu

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 326: API Api2006 Draft

Lesson 11 API FundamentalsNotifications

316 Case Study: Simple Notification

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 Add a class module.

From the Insert menu, click Class Module.

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

5 Select the swApp variable.

Select swApp from the Object pull down menu.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 327: API Api2006 Draft

API Fundamentals Lesson 11Notifications

Case Study: Simple Notification 317

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

7 Review the code for the notification.

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

8 Add code to the handler.

Add the following line of code within the notifications handler.

9 Add code to the class module.

Add the following lines of code to the class module.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 328: API Api2006 Draft

Lesson 11 API FundamentalsNotifications

318 Case Study: Using Notifications in .NET

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 329: API Api2006 Draft

API Fundamentals Lesson 11Notifications

Case Study: Using Notifications in .NET 319

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

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 330: API Api2006 Draft

Lesson 11 API FundamentalsNotifications

320 Case Study: Using Notifications in .NET

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

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

5 Examine the code.

The AttachSWEvents function attaches notification event handlers to four different notifications sent by the SolidWorks application object.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 331: API Api2006 Draft

API Fundamentals Lesson 11Notifications

Case Study: Using Notifications in .NET 321

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.

7 Add the code to the delegate function.

Add the following code to the FileNewNotify2 delegate function.

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 332: API Api2006 Draft

Lesson 11 API FundamentalsNotifications

322 Case Study: Using Notifications in .NET

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

� PartEventHandler

� AssemblyEventHandler

� DrawingEventHandler

Another class is a wrapper for a SolidWorks model view object.

� DocView

Finally, a base class for all of the document level event handlers is created.

� DocumentEventHandler

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 333: API Api2006 Draft

API Fundamentals Lesson 11Notifications

Case Study: Using Notifications in .NET 323

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 add-in 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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 334: API Api2006 Draft

Lesson 11 API FundamentalsNotifications

324 Case Study: Using Notifications in .NET

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 table’s 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.

Attaching the DocumentEvent

Handlers

There are two occurrences where an add-in will create document event handlers.

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

The openDocs hash table manages all of the DocumentEventHandlers.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 335: API Api2006 Draft

API Fundamentals Lesson 11Notifications

Case Study: Using Notifications in .NET 325

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:

� Initialize the object.� Attach the event handlers to its corresponding document.

After these methods are called, the DocumentEventHandler is added to the add-in’s openDocs hash table member.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 336: API Api2006 Draft

Lesson 11 API FundamentalsNotifications

326 Case Study: Using Notifications in .NET

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:

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

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 337: API Api2006 Draft

API Fundamentals Lesson 11Notifications

Case Study: Using Notifications in .NET 327

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:

� 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.Pre-

Release

Do not copy o

r distr

ibute

Page 338: API Api2006 Draft

Lesson 11 API FundamentalsNotifications

328 Case Study: Using Notifications in .NET

The Derived Event Handler Classes

The next part of this case study examines the three classes derived from the DocumentEventHandler class.

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 339: API Api2006 Draft

API Fundamentals Lesson 11Notifications

Case Study: Using Notifications in .NET 329

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 340: API Api2006 Draft

Lesson 11 API FundamentalsNotifications

330 Case Study: Using Notifications in .NET

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

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 341: API Api2006 Draft

API Fundamentals Lesson 11Notifications

Case Study: Using Notifications in .NET 331

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 342: API Api2006 Draft

Lesson 11 API FundamentalsNotifications

332 Case Study: Using Notifications in .NET

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

Release

Do not copy o

r distr

ibute

Page 343: API Api2006 Draft

API Fundamentals Lesson 11Notifications

Case Study: Using Notifications in .NET 333

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 344: API Api2006 Draft

Lesson 11 API FundamentalsNotifications

334 Case Study: Using Notifications in .NET

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:

� The event handlers are removed from the model view.� The model views hash table entries are removed.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 345: API Api2006 Draft

API Fundamentals Lesson 11Notifications

Case Study: Using Notifications in .NET 335

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 346: API Api2006 Draft

Lesson 11 API FundamentalsNotifications

336 Case Study: Using Notifications in .NET

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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 347: API Api2006 Draft

API Fundamentals Lesson 11Notifications

Case Study: Using Notifications in .NET 337

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 348: API Api2006 Draft

Lesson 11 API FundamentalsNotifications

338 Case Study: Using Notifications in .NET

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 349: API Api2006 Draft

API Fundamentals Lesson 11Notifications

Case Study: Using Notifications in .NET 339

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

Release

Do not copy o

r distr

ibute

Page 350: API Api2006 Draft

Lesson 11 API FundamentalsNotifications

340 Case Study: Using Notifications in .NET

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 351: API Api2006 Draft

API Fundamentals Lesson 11Notifications

Case Study: Using Notifications in .NET 341

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 352: API Api2006 Draft

Lesson 11 API FundamentalsNotifications

342 Case Study: Using Notifications in .NET

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.

PartDoc Events

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 353: API Api2006 Draft

API Fundamentals Lesson 11Notifications

Case Study: Using Notifications in .NET 343

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 component’s 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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 354: API Api2006 Draft

Lesson 11 API FundamentalsNotifications

344 Case Study: Using Notifications in .NET

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.

AssemblyDoc Events

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 355: API Api2006 Draft

API Fundamentals Lesson 11Notifications

Case Study: Using Notifications in .NET 345

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.

DrawingDoc Events

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 356: API Api2006 Draft

Lesson 11 API FundamentalsNotifications

346 Case Study: Using Notifications in .NET

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 357: API Api2006 Draft

API Fundamentals Exercise 19:Handling Events Using the Add-in Wizard

347

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 358: API Api2006 Draft

Exercise 19: API FundamentalsHandling Events Using the Add-in Wizard

348

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.

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 359: API Api2006 Draft

API Fundamentals

349

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.

� Macro Feature

� Batch Conversion 1

� Batch Conversion 2

� Assembly Traversal

� Custom Model View

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 360: API Api2006 Draft

API Fundamentals

350 Macro Feature

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 CMacroFeaturePropPageMacroUI.PropPageMenuCallback

End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 361: API Api2006 Draft

API Fundamentals

Macro Feature 351

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.featureDim swMacroFeatureData As SldWorks.MacroFeatureDataDim dboxDimArray(7) As DoubleDim boxDimArray As VariantDim PartBody As ObjectDim ResultBodies As VariantDim errorCode As LongDim MyParamNames As VariantDim MyParamTypes As VariantDim MyParamValues As Variant

Set swMyFeature = featureSet swMacroFeatureData = swMyFeature.GetDefinitionswMacroFeatureData.GetParameters _

MyParamNames, MyParamTypes, MyParamValues

Dim swCicularFace As SldWorks.face2Dim SelObjects As VariantDim SelObjectTypes As VariantDim SelMarks As VariantDim SelDrViews As Variant

swMacroFeatureData.GetSelections2 _SelObjects, SelObjectTypes, SelMarks, SelDrViews

Set swCircularFace = SelObjects(0)Dim swSurface As SldWorks.SurfaceSet swSurface = swCircularFace.GetSurfaceDim Edges As VariantEdges = swCircularFace.GetEdgesDim swCurve As SldWorks.CurveSet swCurve = Edges(0).GetCurveDim CircleParams As VariantCircleParams = swCurve.CircleParamsDim FaceODRadius As DoubleFaceODRadius = CircleParams(6)Dim FaceNormal As VariantFaceNormal = swCircularFace.NormalDim TparamValues(9) As DoubleTparamValues(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.0254TparamValues(7) = MyParamValues(1) * 0.0254TparamValues(8) = 0TparamValues(9) = 0

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 362: API Api2006 Draft

API Fundamentals

352 Macro Feature

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) / 2dboxDimArray(7) = TparamValues(7)boxDimArray = dboxDimArray

Dim swModeler As SldWorks.ModelerSet swModeler = app.GetModelerDim TempCylOut As SldWorks.body2Set TempCylOut = swModeler.CreateBodyFromCyl(boxDimArray)TempCylOut.Display swPart, RGB(1, 0, 0)Set PartBody = swMacroFeatureData.editBodyDim ResultBodiesPerm As VariantResultBodiesPerm = 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 CMacroFeaturePropPageMacroUI.m_IsEditing = TrueDim i_feature As SldWorks.featureSet MacroUI.swMacroFeatureParent = featureSet MacroUI.swMacroFeatureData = feature.GetDefinitionMacroUI.swMacroFeatureData.AccessSelections swPart, Nothing

Dim MyParamNames As VariantDim MyParamTypes As VariantDim MyParamValues As Variant

MacroUI.swMacroFeatureData.GetParameters _MyParamNames, MyParamTypes, MyParamValues

MacroUI.m_dDiameter = MyParamValues(0)MacroUI.m_dDepth = MyParamValues(1)MacroUI.PropPageMenuCallback

End Function

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 363: API Api2006 Draft

API Fundamentals

Batch Conversion 1 353

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.SldWorksDim swModel As SldWorks.ModelDoc2Dim swDraw As SldWorks.DrawingDocDim swView As SldWorks.viewDim swNote As SldWorks.note

Dim FileName As StringDim NoteText As StringDim TextCount As LongDim errors As LongDim warnings As LongDim i As Long

Set swApp = Application.SldWorksFileName = Dir(FileDir + FileMask, vbNormal) Do While FileName <> ""Set swModel = swApp.OpenDoc6(FileName, swDocDRAWING, _

swOpenDocOptions_Silent, "", errors, warnings)Set swDraw = swModelSet swView = swDraw.GetFirstViewDo While Not swView Is NothingSet swNote = swView.GetFirstNoteDo While Not swNote Is NothingIf swNote.IsCompoundNote Then TextCount = swNote.GetTextCountFor i = 1 To TextCountNoteText = swNote.GetTextAtIndex(i) DoReplaceText NoteTextswNote.SetTextAtIndex i, NoteText

Next iElse

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 364: API Api2006 Draft

API Fundamentals

354 Batch Conversion 1

NoteText = swNote.GetText ' process the textDoReplaceText NoteTextswNote.SetText NoteText

End IfSet swNote = swNote.GetNext

LoopSet swView = swView.GetNextView

Looperrors = swModel.Save2(True) swApp.QuitDoc FileName FileName = Dir

LoopEnd Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 365: API Api2006 Draft

API Fundamentals

Batch Conversion 2 355

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 FileMask As String = "*.slddrw"Const NewNote As String = "For Internal Use Only"Const NotePt_X As Double = 0.2128516978344Const NotePt_Y As Double = 0.04630161580401Const Height As Double = 0.003704Const Angle As Double = 0#Const FontName As String = "Century Gothic"

Sub main()Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swDraw As SldWorks.DrawingDocDim swNote As SldWorks.noteDim swTextFormat As SldWorks.textFormat

Dim FileName As StringDim NoteText As StringDim errors As LongDim warnings As LongDim i As Long

Set swApp = Application.SldWorksFileName = Dir(FileDir + FileMask, vbNormal) Do While FileName <> ""Set swModel = swApp.OpenDoc6(FileName, swDocDRAWING, _

swOpenDocOptions_Silent, "", errors, warnings)Set swDraw = swModelswModel.SetAddToDB TrueswDraw.EditTemplateSet swNote = swDraw.CreateText2(NewNote, NotePt_X, _

NotePt_Y, 0#, Height, Angle)Set swTextFormat = swNote.GetTextFormatswTextFormat.TypeFaceName = FontNameswNote.SetTextFormat False, swTextFormatswDraw.EditSheetswModel.SetAddToDB Falseerrors = swModel.Save2(True)swApp.QuitDoc FileNameFileName = Dir

LoopEnd Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 366: API Api2006 Draft

API Fundamentals

356 Assembly Traversal

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.SldWorksDim swModel As SldWorks.ModelDoc2Dim swAssy As SldWorks.AssemblyDocDim swConf As SldWorks.configurationDim swRootComp As SldWorks.Component2Dim nStart As SingleDim bRet As Boolean

Set swApp = Application.SldWorks 'Connect to SWSet swModel = swApp.ActiveDoc ' Get the active assemblySet swConf = swModel.GetActiveConfiguration Set swRootComp = swConf.GetRootComponent nStart = TimerDebug.Print "File = " & swModel.GetPathName

'traverse all of the assembly featuresTraverseModelFeatures swModel, 1

'Now traverse all of the components and sub assembliesTraverseComponent 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 modelDim swFeat As SldWorks.featureSet swFeat = swModel.FirstFeatureTraverseFeatureFeatures swFeat, nLevel

End Sub

Sub TraverseFeatureFeatures(swFeat As SldWorks.feature, _nLevel As Long)

'recursively traversing the feature's featuresDim swSubFeat As SldWorks.featureDim swSubSubFeat As SldWorks.featureDim swSubSubSubFeat As SldWorks.featureDim sPadStr As StringDim i As Long

For i = 0 To nLevelsPadStr = sPadStr + " "

Next iWhile Not swFeat Is NothingDebug.Print sPadStr + swFeat.Name + " [" + _

swFeat.GetTypeName + "]"Set swSubFeat = swFeat.GetFirstSubFeatureWhile Not swSubFeat Is Nothing

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 367: API Api2006 Draft

API Fundamentals

Assembly Traversal 357

Debug.Print sPadStr + " " + swSubFeat.Name + " [" + _swSubFeat.GetTypeName + "]"

Set swSubSubFeat = swSubFeat.GetFirstSubFeatureWhile Not swSubSubFeat Is NothingDebug.Print sPadStr + " " + swSubSubFeat.Name + " _

[" + swSubSubFeat.GetTypeName + "]"Set swSubSubSubFeat = swSubFeat.GetFirstSubFeatureWhile Not swSubSubSubFeat Is NothingDebug.Print sPadStr + " " + _

swSubSubSubFeat.Name + " [" + _swSubSubSubFeat.GetTypeName + "]"

Set swSubSubSubFeat = swSubSubSubFeat. _GetNextSubFeature()

WendSet swSubSubFeat = swSubSubFeat.GetNextSubFeature()

WendSet swSubFeat = swSubFeat.GetNextSubFeature()

WendSet swFeat = swFeat.GetNextFeature

WendEnd 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 windowDim vChildComp As VariantDim swChildComp As SldWorks.Component2Dim swCompConfig As SldWorks.configurationDim sPadStr As StringDim i As Long

For i = 0 To nLevel - 1sPadStr = sPadStr + " "

Next i vChildComp = swComp.GetChildrenFor i = 0 To UBound(vChildComp)Set swChildComp = vChildComp(i)Debug.Print sPadStr & "+" & swChildComp.Name2 & " <" & _

swChildComp.ReferencedConfiguration & ">"TraverseComponentFeatures swChildComp, nLevelTraverseComponent swChildComp, nLevel + 1

Next iEnd Sub

Sub TraverseComponentFeatures(swComp As SldWorks.Component2, _nLevel As Long)

'this recursively traverses all of the components featuresDim swFeat As SldWorks.featureSet swFeat = swComp.FirstFeatureTraverseFeatureFeatures swFeat, nLevel

End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 368: API Api2006 Draft

API Fundamentals

358 Custom Model View

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() EndEnd Sub

Public Sub cmdDensity_Click()Dim density As String

density = CDbl(txtdensity.text) * 100 * 100 * 100Modelview1.modelviewmaker (density)Me.Hide

End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 369: API Api2006 Draft

API Fundamentals

Custom Model View 359

Const sExcelTabName As String = "PartProperties"Const CLSID1 As String = "{0002E510-0000-0000-C000-000000000046}"

Dim swApp As SldWorks.SldWorksDim swModel As SldWorks.ModelDoc2Dim swModelExt As SldWorks.ModelDocExtensionDim swModViewMgr As SldWorks.ModelViewManagerDim materialProps As VariantDim massProps As VariantDim density As DoubleDim bRet As BooleanDim xl As OWC.Spreadsheet

Sub main() UserForm1.ShowEnd 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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 370: API Api2006 Draft

API Fundamentals

360 Custom Model View

'column 2 xl.Range("B1").Select xl.ActiveCell.Formula = materialProps(0) * 255 xl.Range("B2").Select xl.ActiveCell.Formula = materialProps(1) * 255 xl.Range("B3").Select xl.ActiveCell.Formula = materialProps(2) * 255 xl.Range("B4").Select xl.ActiveCell.Formula = materialProps(3) xl.Range("B5").Select xl.ActiveCell.Formula = materialProps(4) xl.Range("B6").Select xl.ActiveCell.Formula = materialProps(5) xl.Range("B7").Select xl.ActiveCell.Formula = materialProps(6) xl.Range("B8").Select xl.ActiveCell.Formula = materialProps(7) xl.Range("B9").Select xl.ActiveCell.Formula = 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 = "CenterOfMassX" xl.Range("C4").Select xl.ActiveCell.Formula = "CenterOfMassY" xl.Range("C5").Select xl.ActiveCell.Formula = "CenterOfMassZ" xl.Range("C6").Select xl.ActiveCell.Formula = "Volume" xl.Range("C7").Select xl.ActiveCell.Formula = "Surface Area" xl.Range("C8").Select xl.ActiveCell.Formula = "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

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 371: API Api2006 Draft

API Fundamentals

Custom Model View 361

'column 4

xl.Range("D1").Select xl.ActiveCell.Formula = density / 100 / 100 / 100 'Density (grams/cm^3) xl.Range("D3").Select xl.ActiveCell.Formula = massProps(0) * 100 'CenterOfMassX (cm) xl.Range("D4").Select xl.ActiveCell.Formula = massProps(1) * 100 'CenterOfMassY (cm) xl.Range("D5").Select xl.ActiveCell.Formula = massProps(2) * 100 'CenterOfMassZ (cm) xl.Range("D6").Select xl.ActiveCell.Formula = massProps(3) * 100 * 100 * 100 'Volume (cm^3) xl.Range("D7").Select xl.ActiveCell.Formula = massProps(4) * 100 * 100 'Surface Area (cm^2) xl.Range("D8").Select xl.ActiveCell.Formula = massProps(5) * 1000 'Mass (grams) xl.Range("D9").Select 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 = "cm" xl.Range("E4").Select xl.ActiveCell.Formula = "cm" xl.Range("E5").Select xl.ActiveCell.Formula = "cm" xl.Range("E6").Select xl.ActiveCell.Formula = "cubic cm" xl.Range("E7").Select xl.ActiveCell.Formula = "square cm" xl.Range("E8").Select xl.ActiveCell.Formula = "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 = 1End Sub

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 372: API Api2006 Draft

API Fundamentals

362 Custom Model View

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 373: API Api2006 Draft

API Fundamentals

Index 363

Index

A

Accessors 55AccessSelections 182ActivateDoc2 47, 149ActiveDoc 47, 55AddComponent2 64, 66, 155AddControl 294AddCustomInfo3 55, 71, 208AddDimension2 131AddGroupBox 293AddHandler 321AddHorizontalDimension2 131Add-in 249Add-in applications 249adding

code to controls 30, 52, 57, 65, 129–130, 132–136

controls to a form 29, 57, 65custom properties 207, 211face attributes 221forms to a macro 29user interaction code to controls 33

Add-Inssetting callback information 276

AddMate 64, 155AddMenu 277AddMenuItem2 279AddMenuPopupItem2 303AddParameter 218AddPMP 291AddressOf 321AddToolbar4 285AddToolbarCommand2 282, 287AddVerticalDimenion2 131API SDK 239Application objects 47Application.SldWorks 47ArrangeWindows 47ArrayData 156Assembly Traversal 356AssemblyDoc Events 343AssemblyDoc Object 64AssemblyEventHandler 329AttachEventHandlers 320AttachModelDocEventHandler 325AttachSWEvents 320Attribute Object 219, 225AttributeDef Object 218

B

Batch Conversions 353, 355binding

early vs. late 49BitmapHandler 284button commands

annotations 172drawing 172features 139layer 172line format 172reference geometry 139sketch 138sketch relations 139sketch tools 138standard 137standard view 137view 137

C

C# 252C# Add-In Wizard 252C++ add-in application 255callback 279choosing data types 6CircleParams 153Class Module - VBA 316Class View 284CloseDoc 47Collections 151–154Compiling a C# Application 254Compiling a C++ Addin 257ConnectModelViews 327ConnectToSW 275ConstructionGeometry 131Contour Selection 134cookie 276Create1stAngleViews2 166Create3rdAngleViews2 166CreateCallout 225CreateCircle2 55CreateCircleByRadius2 133CreateFileFromResourceString 284CreateInstance3 218CreateLayer 76CreateLine2 131CreateNewBody 64CreateNewWindow 47, 69CreatePage 292CreatePoint 154

CreatePropertyManagerPage 291CreateTransform 148creating a macro 15Custom FeatureManager Tabs 303Custom Menus

adding 277Custom Menus Items 279Custom ModelView Windows 303Custom Pop-up Menus 303Custom Properties 207, 211Custom Status Bars 302Custom Toolbars

adding commands 287adding toolbars 285resource editor 283toolbar index 282tooltips 283

CustomInfo2 209customizing the Macro toolbar 18

D

data types 6debug build 250declaring variables 5, 20DestroyNotify 333DetachEventHandlers 334Detaching Event Handlers 333DIM statement 5, 20DisconnectFromSW 299DisplayStatusBar 47, 53Document Attributes 217DocumentEventHandler 323DocumentLoadNotify 324DocumentVisible 47, 150DocView 330DrawingDoc Events 344DrawingDoc Object 64DrawingEventHandler 330

E

early binding 49EditFormat 67editing a macro 15, 19EditRebuild3 55EditRollback 64, 66EnableContourSelection 134ExitApp 47

F

Face Attributes 221

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 374: API Api2006 Draft

API Fundamentals

364 Index

Face Traversal 185FeatMgrView Events 346FeatureByPositionReverse 197FeatureExtrusion 133FeatureManager 55FeatureManager Traversal 192FeatureRevolve 135file types 5FileNewNotify 315FileOpenNotify 317FirstFeature 192forms

inserting 29Frame 302

G

GetBodies2 188GetConfigurationNames 163GetCurve 151GetCustomInfoCount2 210GetCustomInfoNames2 210GetDefinition 182GetDoubleValue 219GetEdges 151GetEntity 219GetFirstFace 189GetFirstLoop 151GetFirstView 64GetMassProperties 56GetMathUtility 146GetName 219, 225GetNextFace 191GetNextFeature 193GetParameter 219, 225GetSelectedObject3 181GetSelectedObjectCount 180GetSelectedObjectType2 181GetStatusBarPane 302GetStringValue 219GetSurface 152GetTitle 146GetTwoAdjacentFaces 152GetType 64, 219GetTypeName 181, 194GetUserPreference 83GUID 274

H

Hash tables 323help file

Contents tab 9examples 9Index tab 9objects 9Release Notes 9Search tab 9

I

Image Editor 282Inheritance 326InsertCavity4 74InsertFamilyTableNew 55, 58InsertFeatureShell 55InsertModelAnnotations 64, 167, 170

InsertNewPart 64InsertNote 55, 59InsertSketch2 55, 58IntelliSense 49IsCircle 151IsOuter 151ISwAddin Implementation 274

L

late binding 49LoadFile2 47, 69

M

Macro Feature 350Macro toolbar 15macros

creating 15editing 15playing 15recording 15recording tips 8

MaterialPropertyValues 64, 190MathPoint 154MathUtility Object 146MirrorPart 64, 73ModelDoc Extension Object 56ModelDoc2 Object 55ModelView Events 345ModifyDefinition 184MultiplyTransform 154

N

NewDocument 47, 55, 58NewSheet3 64, 164Notifications 315Notifications in .NET 318

O

OpenDoc6 47, 55, 69Option Explicit 5

P

Parameter Object 219PartDoc Events 341PartDoc Object 64PartEventHandler 328playing a macro 15PMPageHandler 290Polymorphism 326Preselection 179PrintOut 56Property Pages 289PropertyManager Page2 290PropertyManager Page2Handler2 290

Q

QuitDoc 47

R

recording a macro 15references 246Register 218registry 251release build 250

ReleaseSelectionAccess 183RemoveMenu 299RemoveToolbar2 300Resource Editor 283RevisionNumber 47, 53

S

Safe entities 147SaveAs4 55SDK 239SelectByID 56SelectionManager 146, 180SendMsgToUser 47SetAddinCallbackInfo 276SetAddToDB 129SetDoubleValue 219SetPictureLabelByName 297SetStandardPictureLabel 297SetStringValue 219SetSuppression 194SetToolbarVisibility 55, 70SetUIState 196SetUserPreference 83SetUserPreferenceDoubleValue 86SetUserPreferenceIntegerValue 85SetUserPreferenceStringValue 87SetUserPreferenceToggle 83Show 291SketchOffset2 131SketchRectangle 131SldWorks Events 340SldWorks Object 47SldWorks_FileNewNotify2 321SolidWorks 2005 Type Library 48SolidWorks COM AddIn 255SolidWorks VB.NET Add-In 244SolidWorksExplorer 47, 53Stand-alone applications 249StatusBarPane 302SummaryInfo 216swApp 47swAssy 64swAttDef 218swAttr 219, 225swDocASSEMBLY 64swDocDRAWING 64swDocPART 64swDraw 64swMateCOINCIDENT 156swMateCONCENTRIC 156swModel 55swModelExt 56swParam 219swPart 64SWPropertySheet Events 346

T

TargetStyle 225tips for recording a macro 8Toolbar Bitmaps 282Toolbars 281ToolsCheckInterference2 64Transforms 148traversal

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 375: API Api2006 Draft

API Fundamentals Index

Index 365

assembly 356face 185FeatureManager 192

U

units 6UserForm 29UserPMPPage 290using data types 6

V

variables 5ViewZoomtofit2 55Visual Basic for Applications

(VBA) 19

W

WithEvents 315

Pre-Rele

ase

Do not copy o

r distr

ibute

Page 376: API Api2006 Draft

API Fundamentals

366 Index

Pre-Rele

ase

Do not copy o

r distr

ibute