API Api2006 Draft

November 15, 2016 | Author: Ing Kovács Levente-Kálmán | Category: N/A
Share Embed Donate


Short Description

solidworks...

Description

no Pr t c e-R op e y o lea r d se ist rib ut e

SolidWorks® 2006

Do

API Fundamentals

SolidWorks Corporation 300 Baker Avenue Concord, Massachusetts 01742

COMMERCIAL COMPUTER SOFTWARE - PROPRIETARY U.S. Government Restricted Rights. Use, duplication, or disclosure by the government is subject to restrictions as set forth in FAR 52.227-19 (Commercial Computer Software - Restricted Rights), DFARS 227.7202 (Commercial Computer Software and Commercial Computer Software Documentation), and in the license agreement, as applicable. Contractor/Manufacturer: SolidWorks Corporation, 300 Baker Avenue, Concord, Massachusetts 01742 USA Portions of this software © 1988, 2000 Aladdin Enterprises. Portions of this software © 1996, 2001 Artifex Software, Inc. Portions of this software © 2001 artofcode LLC. Portions of this software © 2005 Bluebeam Software, Inc. Portions of this software © 1999, 2002-2005 ComponentOne Portions of this software © 1990-2005 D-Cubed Limited. Portions of this product are distributed under license from DC Micro Development, Copyright © 19942002 DC Micro Development, Inc. All rights reserved Portions © eHelp Corporation. All rights reserved. Portions of this software © 1998-2005 Geometric Software Solutions Co. Limited. Portions of this software © 1986-2005 mental images GmbH & Co. KG Portions of this software © 1996 Microsoft Corporation. All Rights Reserved. Portions of this software © 2005 Priware Limited Portions of this software © 2001, SIMULOG. Portions of this software © 1995-2005 Spatial Corporation. Portions of this software © 2003-2005, Structural Research & Analysis Corp. Portions of this software © 1997-2005 Tech Soft America. Portions of this software are copyrighted by and are the property of UGS Corp. © 2005. Portions of this software © 1999-2005 Viewpoint Corporation. Portions of this software © 1994-2005, Visual Kinematics, Inc. This software is based in part on the work of the Independent JPEG group. All Rights Reserved

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

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

Document Number: PMT0077-ENG

no Pr t c e-R op e y o lea r d se ist rib ut e

API Fundamentals

Table of Contents

Do

Introduction

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

i

API Fundamentals

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

Lesson 1: Using the Macro Recorder Macro Recording . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Macro Toolbar. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Understanding How Macro Code Works . . . . . . . . . . . . . . . . . . . . . . 20 Variable Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 Entry Point Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 SolidWorks Application Object . . . . . . . . . . . . . . . . . . . . . . . . . . 20 SolidWorks Document Object . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 SolidWorks API Calls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 Procedure End. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 Understanding How to Call Members on API Interfaces . . . . . . . . . . 21 Passing Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 Cleaning Up Code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 Commenting Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 Debugging Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Adding Forms to a Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 Exercise 1: Recording a Macro. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 Exercise 2: Adding Macro Code to a VBA Button Control . . . . . . . . 37 Exercise 3: Adding User Input Fields on a VBA Form . . . . . . . . . . . 40 Lesson 2: The API Object Model SolidWorks API Object Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Visual Basic Automatic Type Casting . . . . . . . . . . . . . . . . . . . . . 46 Application Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 SldWorks Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 SolidWorks 2006 Type Library . . . . . . . . . . . . . . . . . . . . . . . . . . 48 IntelliSense . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 Early vs. Late Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 Case Study: Connecting to New Documents . . . . . . . . . . . . . . . . . . . 51 Macro Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 ModelDoc2 Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 ModelDoc Extension Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 PartDoc Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 AssemblyDoc Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 DrawingDoc Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 Case Study: Connecting to Existing Documents . . . . . . . . . . . . . . . . 69 Exercise 4: Working with New Documents . . . . . . . . . . . . . . . . . . . . 77 Exercise 5: Working with Existing Documents . . . . . . . . . . . . . . . . . 79

ii

API Fundamentals

Lesson 3: Setting System Options and Document Properties

no Pr t c e-R op e y o lea r d se ist rib ut e

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

Do

Lesson 4: Automating Part Design Case Study: Automation Tool for Parts . . . . . . . . . . . . . . . . . . . . . . 129 Setting Material. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 Creating the Sketch Rectangle . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Adding Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Selection on Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Creating the Sketch Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 Creating Extruded Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 Enabling Contour Selection for the Extrusion . . . . . . . . . . . . . . 134 Creating Revolved Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 Standard Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 View Commands. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 Sketch Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 Sketch Tools Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 Features Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 Sketch Relations Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 Reference Geometry Commands . . . . . . . . . . . . . . . . . . . . . . . . 139 Exercise 8: Automating the Part Creation Process . . . . . . . . . . . . . . 141 Lesson 5: Assembly Automation Case Study: Automation Tool for Assemblies . . . . . . . . . . . . . . . . . 145 Transforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 Creating MathTransforms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 The Transformation Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 Activating Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 Invisible Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 Object Collections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 Establishing the Curve and Edge Collections. . . . . . . . . . . . . . . 150

iii

API Fundamentals

no Pr t c e-R op e y o lea r d se ist rib ut e

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

Lesson 6: Drawing Automation

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

Do

Lesson 7: Selection and Traversal Techniques Case Study: Programming With a Selected Object . . . . . . . . . . . . . 179 SelectionManager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 Accessing the Selection Manager . . . . . . . . . . . . . . . . . . . . . . . . 180 Counting Selected Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 Accessing Selected Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 Getting Selected Object Types . . . . . . . . . . . . . . . . . . . . . . . . . . 181 Getting Feature Type Names . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 Feature Data Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 Accessing the Feature Data Object . . . . . . . . . . . . . . . . . . . . . . . 182 Accessing Selections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 Releasing Selections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 Modifying Feature Data Properties. . . . . . . . . . . . . . . . . . . . . . . 183 Modify the Object Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 The SolidWorks BREP Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 Traversing Topology and Geometry. . . . . . . . . . . . . . . . . . . . . . 186 Case Study: Body and Face Traversal . . . . . . . . . . . . . . . . . . . . . . . 187 Returning a List of Body Pointers . . . . . . . . . . . . . . . . . . . . . . . 188 Face Material Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190

iv

API Fundamentals

no Pr t c e-R op e y o lea r d se ist rib ut e

Case Study: Feature Manager Traversal . . . . . . . . . . . . . . . . . . . . . . 192 Traversing the FeatureManager from the Top . . . . . . . . . . . . . . 192 Displaying Feature Names and Types . . . . . . . . . . . . . . . . . . . . 193 Setting Feature Suppression . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 Setting Feature UI State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 Obtaining a Feature by FeatureManager Position . . . . . . . . . . . 197 Exercise 11: Handling Preselection 1 . . . . . . . . . . . . . . . . . . . . . . . . 199 Exercise 12: Handling Preselection 2 . . . . . . . . . . . . . . . . . . . . . . . . 201 Exercise 13: Traversing the FeatureManager . . . . . . . . . . . . . . . . . . 203

Do

Lesson 8: Adding Custom Properties and Attributes Case Study: Custom Properties. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 Adding Custom Properties to a SolidWorks Document . . . . . . . 208 Setting and Getting Custom Property Values . . . . . . . . . . . . . . . 209 Getting Custom Property Names . . . . . . . . . . . . . . . . . . . . . . . . 210 Getting the Custom Property Count . . . . . . . . . . . . . . . . . . . . . . 210 Case Study: Configurations With Custom Properties. . . . . . . . . . . . 211 Returning Mass Properties From a SolidWorks Model . . . . . . . 213 Using the API to Return the Mass Properties . . . . . . . . . . . . . . . 213 Case Study: File Summary Information . . . . . . . . . . . . . . . . . . . . . . 216 Adding Summary Information . . . . . . . . . . . . . . . . . . . . . . . . . . 216 Case Study: Document Attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . 217 Naming Attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 The Attribute Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 AttributeDef Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 Attribute Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 Parameter Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 Case Study: Face Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 Finding the Cylindrical Faces and Attaching Attributes . . . . . . 223 Displaying Callouts in the Model View . . . . . . . . . . . . . . . . . . . 225 Callout Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 Creating the CNC Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 Types of Attribute Traversal. . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 A Final Word about Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . 229 Exercise 14: Adding Mass Properties as Custom Properties . . . . . . 231 Exercise 15: Adding Attributes to Edges . . . . . . . . . . . . . . . . . . . . . 233 Lesson 9: The SolidWorks API SDK The API SDK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 Installing the SDK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 Case Study: Creating a VB.NET Add-In.. . . . . . . . . . . . . . . . . . . . . 244 References. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246 Comparing Addin DLLs and Stand-Alone Executables. . . . . . . 249 Loading and Running an Add-in Application. . . . . . . . . . . . . . . 250 Case Study: Creating a C# Add-in . . . . . . . . . . . . . . . . . . . . . . . . . . 252

v

API Fundamentals

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

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

Lesson 10: Customizing the SolidWorks User Interface Case Study: Customizing the UI With VB.NET. . . . . . . . . . . . . . . . 267 Debugging the DLL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 Debugger Keyboard Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . 271 Understanding The Add-in Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 Importing Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 The Add-in Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 Understanding the GUID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274 Connecting to Solidworks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 Bidirectional Communication. . . . . . . . . . . . . . . . . . . . . . . . . . . 276 Setting Callback Information . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 Custom Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 Custom Menu Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 Creating and Adding Custom Toolbars to an Add-in . . . . . . . . . 281 Creating the Toolbar Bitmaps. . . . . . . . . . . . . . . . . . . . . . . . . . . 282 Adding Toolbar Bitmaps to a VB.NET Solution . . . . . . . . . . . . 283 The Bitmap Handler Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284 Adding Toolbars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 Adding Toolbar Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 Property Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289 PropertyPage Members. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289 Add-In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 SldWorks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 UserPMPage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 SldWorks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 Add-In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 ppage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 handler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 PropertyManager Page2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 PropertyManager Page2Handler2. . . . . . . . . . . . . . . . . . . . . . . . 290 Creating a PropertyManager Page . . . . . . . . . . . . . . . . . . . . . . . 291 Property Page Groups and Controls . . . . . . . . . . . . . . . . . . . . . . . . . 292 Adding Group Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293 Group and control IDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293 Adding Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294 Adding Picture Labels to Controls . . . . . . . . . . . . . . . . . . . . . . . 297 Removing Menus and Toolbars . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299

vi

API Fundamentals

Other Areas of Customization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302 Custom Status Bars. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302 Custom Pop-up Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 Custom ModelView Windows . . . . . . . . . . . . . . . . . . . . . . . . . . 303 Exercise 16: Implement a New Menu. . . . . . . . . . . . . . . . . . . . . . . . 305 Exercise 17: Implement Toolbar Buttons . . . . . . . . . . . . . . . . . . . . . 307 Exercise 18: Implement Controls on a Property Manager Page . . . . 309

no Pr t c e-R op e y o lea r d se ist rib ut e

Lesson 11: Notifications

Notifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 Notifications in VBA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 Case Study: Simple Notification. . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 The Class Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 Case Study: Using Notifications in .NET . . . . . . . . . . . . . . . . . . . . . 318 The AddHandler Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 The AddressOf Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 The Event Handler Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 The Document Event Handler Class. . . . . . . . . . . . . . . . . . . . . . 323 Attaching the DocumentEvent Handlers . . . . . . . . . . . . . . . . . . 324 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 The Derived Event Handler Classes . . . . . . . . . . . . . . . . . . . . . . 328 The DocView Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 Detaching the Document and Model View Event Handlers. . . . 333 Detaching the SolidWorks Event Handlers . . . . . . . . . . . . . . . . 337 Interfaces That Support Notifications. . . . . . . . . . . . . . . . . . . . . 340 Exercise 19: Handling Events Using the Add-in Wizard . . . . . . . . . 347 Solution. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348

Do

Appendix

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

vii

Do no Pr t c e-R op e y o lea r d se ist rib ut e

API Fundamentals

viii

Do no Pr t c e-R op e y o lea r d se ist rib ut e

API Fundamentals

Introduction

1

Do no Pr t c e-R op e y o lea r d se ist rib ut e

Introduction

API Fundamentals

2

API Fundamentals Introduction

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.

no Pr t c e-R op e y o lea r d se ist rib ut e

About This Course

Prerequisites

Students attending this course are expected to have: I I I I

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

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.

Do

Course Design Philosophy

Windows® XP

About This Course

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.

3

API Fundamentals Introduction

Conventions Used in this Book

This manual uses the following typographic conventions: Convention

SolidWorks commands and options appear in this style. For example, View, Toolbars means choose the Toolbars option from the View menu.

no Pr t c e-R op e y o lea r d se ist rib ut e

Bold Sans Serif

Meaning

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

Do

About the CD

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

Bound inside the rear cover is a CD containing copies of the parts, assemblies, drawings, templates, macros and projects that are used throughout this course. They are organized by lesson in two folders: Case Study and Exercises.

The Case Study folder contains the files your instructor uses while presenting the various lessons. The Exercises folder contains any files that are required for doing the laboratory exercises. Solutions are provided throughout each lesson.

4

About This Course

API Fundamentals Introduction

Getting Started

There are a few things a programmer should note before recording a macro in SolidWorks or writing an application in Visual Basic that connects to SolidWorks.

File Types

In SolidWorks 2006, the macro files we will create are of type: SW VBA Macros (*.swp)

no Pr t c e-R op e y o lea r d se ist rib ut e

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.

Do

Variables

Getting Started

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.

5

API Fundamentals Introduction

Choosing Data Types

Visual Basic supports these standard types of data: - holds characters. To make sure a variable is of this type, use ($) after the variable name.

String

Integer -

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

no Pr t c e-R op e y o lea r d se ist rib ut e

Long

Precision - holds numeric values with decimal points, accurate to seven digits. To make sure a variable is of this type, use (!) after the variable name. Single

Precision - holds numeric values with decimal points, accurate to sixteen digits. To make sure a variable is of this type, use (#) after the variable name. Double

Decimal -

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

Byte

- holds integer values between 0 and 255

Boolean -

holds values that are either True or False

Variant -

holds values of all data types

Object - holds a 32 bit (4-byte) address that refers to objects. Using the Set statement, a variable declared as an object can have any object

Do

reference assigned to it.

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

swApp swApp filename dvarArray(2)

As As As As

Object SldWorks.SldWorks String Double

'Generic object 'Specific object 'Simple string 'Set of 3 doubles

There are additional data types available to the programmer once the SolidWorks 2006 type library has been referenced (e.g. SldWorks). API Units

6

All APIs use meters and radians for length and angle units.

Getting Started

API Fundamentals Introduction

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.

no Pr t c e-R op e y o lea r d se ist rib ut e

SolidWorks Constants Type Library

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.

Do

Note

Getting Started

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

7

API Fundamentals Introduction

Macro Recording Tips

Recording a macro is a great starting point for capturing basic functionality. However, be aware that not all API functionality is recorded. I

no Pr t c e-R op e y o lea r d se ist rib ut e

I

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

I

I

Part.ActiveView().RotateAboutCenter

I

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.

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.

Do

SolidWorks 2006 API Help

8

Macro Recording Tips

API Fundamentals Introduction

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

no Pr t c e-R op e y o lea r d se ist rib ut e

Contents

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

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.

Do

Index

Search

Macro Recording Tips

The Index tab of the API help file allows you to quickly locate API topics through it’s alphabetically ordered list of keywords. The Search tab of the API help file allows you to search for keywords on every page of the API help file.

9

API Fundamentals Introduction

Understanding API Interface Member Descriptions

1 2

3 4

no Pr t c e-R op e y o lea r d se ist rib ut e

5

6

7

8

9

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.

Do

2. API Interface Diagram and Member Links- Diagrams to show where the currently selected API interface fits into the SolidWorks object model.

10

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

Macro Recording Tips

API Fundamentals Introduction

5. API Call - This section shows the complete syntax for using the member. void SldWorks.ArrangeWindows (style), is written in VB: swApp.ArrangeWindows 0

no Pr t c e-R op e y o lea r d se ist rib ut e

Void means there is no return value for this call. You do not use void in Visual Basic source code. It is simply written in the help file as an indicator - not to return a value.

For other methods, a return value is necessary and the API call section looks different:

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

Dim swPart As Object Set swPart = swApp.NewPart

swPart is our retval (short for Return Value). The return value of SldWorks::NewPart is LPDISPATCH (a pointer to a dispatch object) which we declare in Visual Basic as simply Object, because it points to an API interface object (the newly created part document).

Note

In VBA if you are returning data on the left side return value, you will need to encompass your input parameters in parenthesis. If you are not returning data, parenthesis are not used. If you want to call a method or a property directly from a returned object, you will need to use the parenthesis. This is shown in the following example.

Do

swModel.CreateLine2(0,0,0,1, 0,0).ConstructionLine = true

Macro Recording Tips

11

API Fundamentals Introduction

6. Input - Describes how to declare those parameters (if the API member requires parameters). In this case, (long) style tells us that a parameter called style must be declared as type long in order for the API to work properly. In Visual Basic, the declaration is written above our API call.

no Pr t c e-R op e y o lea r d se ist rib ut e

Dim style As Long style = 1 swApp.ArrangeWindows (style)

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

Note

The name style is just a descriptive name for the variable, you can name this variable anything you like. Always try to give your variables descriptive names. 7. Parameters - Descriptions of possible values for each parameter (if the API call requires parameters). In this case, put a 0 to cascade, 1 tiles the windows horizontally, and 2 tiles the windows vertically. 8. Syntax (COM) - Devoted to COM programming syntax.

Do

9. Remarks - Contains notes to the programmer about using the member. Before using any member spend time reading this section if there is information available.

12

Macro Recording Tips

no Pr t c e-R op e y o lea r d se ist rib ut e

API Fundamentals

Lesson 1 Using the Macro Recorder

Do

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

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

I

Identify each button on the Macro toolbar.

I

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

I

Customize a Macro toolbar button to run your macro.

I

Understand how the macro begins a procedure and connects to SolidWorks.

I

Improve macro recorder default code.

I

Debug a macro.

I

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

13

Lesson 1

API Fundamentals

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

Using the Macro Recorder

14

API Fundamentals

Lesson 1 Using the Macro Recorder

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.

no Pr t c e-R op e y o lea r d se ist rib ut e

Macro Recording

By default, the Macro toolbar is turned off. To create and use your macros, it is best to view and dock the macro toolbar at the top of the SolidWorks window. From the View menu, select Toolbars, Macro. launches the Run Macro dialog box, where the user selects the macro to execute. Run

launches the Save As macro dialog box, where the user enters a valid name and extension for the macro. If the save is cancelled, a prompt appears that allows the user to continue or cancel the recording. Stop

Record/Pause

allows the user to begin or pause macro recording.

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

Next, the macro file is populated with standard lines of programming code to connect to SolidWorks. Finally, the VBA editor opens the macro file for the user to begin programming.

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

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.

Do

Custom

Macro Recording

15

Lesson 1

API Fundamentals

Using the Macro Recorder

1

Start SolidWorks and create a new part.

For this part, use millimeters as the default units. View the Macro toolbar. From the View menu, choose Toolbars, Macro.

no Pr t c e-R op e y o lea r d se ist rib ut e

2

3

Click Record

4

Select the Front plane.

5

Click Sketch

6

Click Circle

.

.

.

Do

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

16

Macro Toolbar

API Fundamentals

Lesson 1 Using the Macro Recorder

7

Click Extruded Boss/Base

.

no Pr t c e-R op e y o lea r d se ist rib ut e

Drag the extrude path approximately 15 millimeters, then enter the exact value of 15 mm in the PropertyManager. Click OK.

8 9

Click Stop

.

Save the macro.

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

10 Delete all features.

Remove the extruded base and sketch created previously.

11 Click Play

.

Do

Select Macro1.swp from the previous step.

Macro Toolbar

17

Lesson 1

API Fundamentals

Using the Macro Recorder

Automation Review

Let’s take a look at how much we’ve automated so far with this simple macro

no Pr t c e-R op e y o lea r d se ist rib ut e

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.

Do

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

Note

18

Custom macro buttons can be placed on any toolbar, not just the Macro toolbar.

Macro Toolbar

API Fundamentals

Lesson 1 Using the Macro Recorder

13 Program a custom button.

When the new button is dropped on a toolbar, the Customize Macro Button dialog appears automatically.

no Pr t c e-R op e y o lea r d se ist rib ut e

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.

Do

Select Macro1.swp.

Macro Toolbar

19

Lesson 1

API Fundamentals

Using the Macro Recorder

Understanding How Macro Code Works Variable Declaration

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

no Pr t c e-R op e y o lea r d se ist rib ut e

The macro recorder declares (or dimensions) a number of variables by default.

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:

You can comment out or delete variables not utilized in the entry point procedure.

Entry Point Procedure

Sub main()

This is the beginning of our functionality. Every macro must establish an entry point procedure.

SolidWorks Application Object

Set swApp = Application.SldWorks

This line of code will start an instance of SolidWorks or connect to a running instance of SolidWorks. Without it, your program will not run.

SolidWorks Document Object

Set Part = swApp.ActiveDoc

In order for us to work within the application, top-level document objects are accessed and made active. This allows the ability to program document specific functionality

Do

SolidWorks API Calls

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

Procedure End

20

Set SelMgr = Part.SelectionManager boolstatus = Part.Extension.SelectByID2("Front Plane", _ "PLANE", 0, 0, 0, False, 0, Nothing, 0) Part.InsertSketch2 True Part.ClearSelection2 True Part.CreateCircle 0, 0, 0, 0.043409,-0.003803, 0 Part.ShowNamedView2 "*Trimetric", 8 Part.ClearSelection2 True boolstatus = Part.Extension.SelectByID2("Arc1", _ "SKETCHSEGMENT", 0, 0, 0, False, 0, Nothing, 0) Part.FeatureManager.FeatureExtrusion2 True, False, False, 0,_ 0, 0.01, 0.01, False, False, False, False, 0.017453, _ 0.017453, False, False, False, False, 1, 1, 1, 0, 0, False Part.SelectionManager.EnableContourSelection = 0 End Sub

Understanding How Macro Code Works

API Fundamentals

Lesson 1 Using the Macro Recorder

Understanding How to Call Members on API Interfaces

API members, often referred to as events, properties, methods, functions or simply APIs, are called to interact with the actual object members that are exposed by the SolidWorks application. In order to call members on API objects, a few steps are required.

no Pr t c e-R op e y o lea r d se ist rib ut e

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

Do

Some APIs require additional objects:

Part.FeatureManager.FeatureExtrusion2 True, False, False, _ 0, 0, 0.015, 0, False, False, False, False, _ 0.01745, 0.01745, False, False, False, False, 1, 1, 1, _ 0, 0, False

Some APIs utilize return values: Dim boolstatus As Boolean boolstatus = Part.Extension.SelectByID2("Front Plane", _ "PLANE", 0, 0, 0, False, 0, Nothing, 0)

Understanding How to Call Members on API Interfaces

21

Lesson 1

API Fundamentals

Using the Macro Recorder

Passing Parameters

As you begin developing productivity tools for SolidWorks it will become clear that your code will not run properly unless every parameter within an API call is satisfied. To learn more about specific API calls we turn to the API help file. Let’s explore one of our lengthy calls, FeatureManager::FeatureExtrusion, which has 20 parameters.

FeatureManager::FeatureExtrusion2

no Pr t c e-R op e y o lea r d se ist rib ut e

pFeat = FeatureManager.FeatureExtrusion (sd, flip, dir, t1, t2, d1, d2, dchk1, dchk2, ddir1, ddir2, dang1, dang2, offsetReverse1, offsetReverse2, translateSurface1, translateSurface2, merge, useFeatScope, useAutoSelect, t0, startOffset, flipStartOffset )

Output:

pFeat

Pointer to the feature object.

Input:

sd

TRUE

for single ended, FALSE for double ended.

flip

TRUE

to flip the direction to cut.

dir

TRUE

to flip the direction to extrude.

t1

Termination type for first end from swEndConditions_e enumeration.

Input: Input: Input:

swEndCondBlind swEndCondThroughAll swEndCondThroughNext swEndCondUpToVertex swEndCondUpToSurface swEndCondOffsetFromSurface swEndCondMidPlane swEndCondUpToBody

Input:

Input: Input:

Termination type for second end from swEndConditions_e enumeration. (see above)

d1

Depth of extrusion for first end in meters.

d2

Depth of extrusion for second end in meters.

dchk1

allows draft angle in first direction, FALSE does not allow drafting.

Do

Input:

t2

TRUE

Input:

dchk2

allows draft angle in second direction, FALSE does not allow drafting.

Input:

ddir1

TRUE

Input:

ddir2

for second draft angle to be inward, FALSE to be outward.

Input:

dang1

Draft angle for first end.

Input:

dang2

Draft angle for second end.

22

TRUE

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

Passing Parameters

API Fundamentals

Lesson 1 Using the Macro Recorder

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:

Input:

Input:

no Pr t c e-R op e y o lea r d se ist rib ut e

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.

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.

merge

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

not.

Input:

if the feature only affects selected bodies, FALSE if the feature affects all bodies.

useAutoSelect

TRUE

Do

Input:

useFeatScope

Input:

t0

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

Passing Parameters

23

Lesson 1

API Fundamentals

Using the Macro Recorder

Cleaning Up Code

Never be satisfied with results the SolidWorks macro recorder returns. Always look to improve and clean up your code. Macro code usually needs to be edited to complete your automation task. Option Explicit '********************************************************** ' Macro1.swb - macro recorded on ##/##/## '**********************************************************

no Pr t c e-R op e y o lea r d se ist rib ut e

These comments are not functional and can be deleted.

Dim swApp As Object Dim Part As Object

This variable is not needed

Dim SelMgr As Object

These variables are not needed. They can be deleted or commented for later use.

Dim longstatus As Long, longwarnings As Long Dim Feature As Object

Dim boolstatus As Boolean

Sub main()

Set swApp = Application.SldWorks Set Part = swApp.ActiveDoc

This call is unnecessary

Set SelMgr = Part.SelectionManager

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

See Note below.

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

These calls are unnecessary.

Part.ShowNamedView2 "*Trimetric", 8 Part.ClearSelection2 True boolstatus = Part.Extension.SelectByID2("Arc1", "SKETCHSEGMENT", 0, 0, 0, False, 0, Nothing, 0)

Part.FeatureManager.FeatureExtrusion2 True, False, False, 0,_ 0, 0.015, 0, False, False, False, False, 0.01745, 0.01745, _ False, False, False, False, 1, 1, 1, 0, 0, False

This call is unnecessary.

Part.SelectionManager.EnableContourSelection = 0 End Sub

Do

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.

24

Cleaning Up Code

API Fundamentals

Lesson 1 Using the Macro Recorder

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.

no Pr t c e-R op e y o lea r d se ist rib ut e

Tip

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.

Do

Option Explicit Dim swApp As Object Dim Part As Object Dim boolstatus As Boolean

Sub main() ‘Connect to SolidWorks Set swApp = Application.SldWorks Set Part = swApp.ActiveDoc ‘Create a cylinder on the front plane boolstatus = Part.Extension.SelectByID2("Front Plane", _ "PLANE", 0, 0, 0, False, 0, Nothing, 0) Part.InsertSketch2 True Part.CreateCircleByRadius2 0, 0, 0, 0.04 Part.FeatureManager.FeatureExtrusion2 True, False, False, 0,_ 0, 0.015, 0, False, False, False, False, 0.01745, 0.01745,_ False, False, False, False, 1, 1, 1, 0, 0, False End Sub

Cleaning Up Code

25

Lesson 1

API Fundamentals

Using the Macro Recorder

Debugging Code

Although this manual does not go into detail about debugging techniques for Visual Basic, it is important to use debugging practices throughout the course. The next few steps are designed to help get you familiar with how to debug code. 17 Add a breakpoint.

no Pr t c e-R op e y o lea r d se ist rib ut e

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

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

Do

the programmer to step through the code.

26

Cleaning Up Code

API Fundamentals

Lesson 1 Using the Macro Recorder

no Pr t c e-R op e y o lea r d se ist rib ut e

19 Begin stepping into code. Press F8 to enter the procedure (yellow highlight will move).

20 Press F8.

Do

21 Press F8.

Note

Cleaning Up Code

Certain API calls have a return value. In order to help debug a macro, place the mouse cursor over a return value before executing a line.

27

Lesson 1

API Fundamentals

Using the Macro Recorder

Note

no Pr t c e-R op e y o lea r d se ist rib ut e

22 Press F8.

Place the mouse cursor over the same return value to see if the call was performed correctly. In this case, the return value boolstatus changes from False, to True. This reveals that the macro selected the item successfully.

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.

Do

Adding Forms to a Macro

Where to Find It

To provide a user interface to your program, add a userform to the macro.

I I

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

The VBA Toolbox is displayed along with the form by default. If it does not appear click View, Toolbox.

28

Adding Forms to a Macro

API Fundamentals

Lesson 1 Using the Macro Recorder

24 Add a userform to the macro. In VBA, click Insert, UserForm. 25 Edit the userform properties.

no Pr t c e-R op e y o lea r d se ist rib ut e

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

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): cmd100mm Caption: 100 mm CommandButton2: (Name): cmd500mm Caption: 500 mm

Do

CommandButton3: (Name): cmd1m Caption: 1 m

Adding Forms to a Macro

CommandButton4: (Name): cmd5m Caption: 5 m CommandButton5: (Name): cmdExit Caption: Exit

29

Lesson 1

API Fundamentals

Using the Macro Recorder

27 Add a click event to each button.

Double-click each button on the form to set up a button click event handler for these controls. When you double-click each button, the VBA environment automatically adds a skeleton event handler to the source code. The code that you will add to the event handlers will run when the user clicks the button when your macro is running.

no Pr t c e-R op e y o lea r d se ist rib ut e

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.

Do

At this point the entire macro file should contain one module and one form. We want to keep both, but move code to different locations. Cut everything within the module leaving only an empty entry point procedure (Sub main .... End Sub). Paste the code in the click event for each command button (except the Exit button). Look closely at the code below. Only one parameter (shown in bold) is changed to account for the different extrusion depths of each button.

30

Private Sub cmd100mm_Click() Dim swApp As Object Dim Part As Object Dim boolstatus As Boolean ‘Connect to SolidWorks Set swApp = Application.SldWorks Set Part = swApp.ActiveDoc ‘Create a cylinder on the front plane boolstatus = Part.Extension.SelectByID2("Front Plane", _ "PLANE", 0, 0, 0, False, 0, Nothing, 0) Part.InsertSketch2 True Part.CreateCircleByRadius2 0, 0, 0, 0.04 Part.FeatureManager.FeatureExtrusion2 True, False, False, 0,_ 0, 0.1, 0, False, False, False, False, 0.01745,0.01745, _ False, False, False, False, 1, 1, 1, 0, 0, False End Sub

Adding Forms to a Macro

API Fundamentals

Lesson 1 Using the Macro Recorder

no Pr t c e-R op e y o lea r d se ist rib ut e

Private Sub cmd500mm_Click() Dim swApp As Object Dim Part As Object Dim boolstatus As Boolean ‘Connect to SolidWorks Set swApp = Application.SldWorks Set Part = swApp.ActiveDoc ‘Create a cylinder on the front plane boolstatus = Part.Extension.SelectByID2("Front Plane", _ "PLANE", 0, 0, 0, False, 0, Nothing, 0) Part.InsertSketch2 True Part.CreateCircleByRadius2 0, 0, 0, 0.04 Part.FeatureManager.FeatureExtrusion2 True, False, False, 0,_ 0, 0.5, 0, False, False, False, False, 0.01745, 0.01745, _ False, False, False, False, 1, 1, 1, 0, 0, False End Sub

Do

Private Sub cmd1m_Click() Dim swApp As Object Dim Part As Object Dim boolstatus As Boolean ‘Connect to SolidWorks Set swApp = Application.SldWorks Set Part = swApp.ActiveDoc ‘Create a cylinder on the front plane boolstatus = Part.Extension.SelectByID2("Front Plane", _ "PLANE", 0, 0, 0, False, 0, Nothing, 0) Part.InsertSketch2 True Part.CreateCircleByRadius2 0, 0, 0, 0.04 Part.FeatureManager.FeatureExtrusion2 True, False, False, 0,_ 0, 1, 0, False, False, False, False, 0.01745, 0.01745, _ False, False, False, False, 1, 1, 1, 0, 0, False End Sub

Adding Forms to a Macro

Private Sub cmd5m_Click() Dim swApp As Object Dim Part As Object Dim boolstatus As Boolean ‘Connect to SolidWorks Set swApp = Application.SldWorks Set Part = swApp.ActiveDoc ‘Create a cylinder on the front plane boolstatus = Part.Extension.SelectByID2("Front Plane", _ "PLANE", 0, 0, 0, False, 0, Nothing, 0) Part.InsertSketch2 True Part.CreateCircleByRadius2 0, 0, 0, 0.04 Part.FeatureManager.FeatureExtrusion2 True, False, False, 0,_ 0, 5, 0, False, False, False, False, 0.01745, 0.01745, _ False, False, False, False, 1, 1, 1, 0, 0, False End Sub

31

Lesson 1

API Fundamentals

Using the Macro Recorder

29 Program the Exit button. Private Sub cmdExit_Click() End End Sub

30 Add code to the module.

no Pr t c e-R op e y o lea r d se ist rib ut e

In order for the userform to appear in SolidWorks, the entry point procedure on the module needs to show the userform. Enter the following line of code: Sub main() frmMacro1a.Show End Sub

31 Save and run the macro.

Save the macro. With SolidWorks open and a new part file created, run the macro either from the Macro toolbar or from the VBA editor. Click the buttons to create the different length cylinders. 100mm

500mm

1m

5m

Do

32 Exit the macro. Click the Exit button to end the macro and return to VBA.

32

33 Add a second userform. Click Insert, UserForm. Enter the following property values: UserForm2: (Name): frmMacro1b Caption: Custom Cylinder Startup Position: 2 - CenterScreen ShowModal: False

Adding Forms to a Macro

API Fundamentals

Lesson 1 Using the Macro Recorder

34 Add controls to the second form.

To capture input from a user, we add textbox controls that require the user to specify the depth and diameter rather than hard coding the values. Use the following diagram as a guide for laying out your controls.

no Pr t c e-R op e y o lea r d se ist rib ut e

TextBox1: (Name): txtDiameter Text:

TextBox2: (Name): txtDepth Text: CommandButton1: (Name): cmdBuild Caption: Build CommandButton2: (Name): cmdExit Caption: Exit

35 Add code to each button.

We want each string value in the text boxes to be converted to a double value for diameter and depth. Make a copy of the working code you already have from one of the buttons on frmMacro1a and paste into a click event for cmdBuild on frmMacro1b. Then make the adjustments to the code: Private Sub cmdBuild_Click() Dim swApp As Object Dim Part As Object Dim boolstatus As Boolean Dim diameter As Double Dim depth As Double

Do

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

Adding Forms to a Macro

‘Connect to SolidWorks Set swApp = Application.SldWorks Set Part = swApp.ActiveDoc

‘Create a cylinder on the front plane boolstatus = Part.Extension.SelectByID2("Front Plane", _ "PLANE", 0, 0, 0, False, 0, Nothing, 0) Part.InsertSketch2 True Part.CreateCircleByRadius2 0, 0, 0, diameter / 2 Part.FeatureManager.FeatureExtrusion2 True, False, False, 0,_ 0, depth, 0, False, False, False, False, 0.01745, _ 0.01745, False, False, False, False, 1, 1, 1, 0, 0, False End Sub

33

Lesson 1

API Fundamentals

Using the Macro Recorder

36 Program the Exit button. Private Sub cmdExit_Click() End End Sub

37 Add code to the module.

no Pr t c e-R op e y o lea r d se ist rib ut e

In order for the userform to appear in SolidWorks, the entry point procedure on the module needs to show the userform. Enter the following line of code: Sub main() frmMacro1b.Show End Sub

38 Save and run the macro.

10

50

Do

39 Exit the macro.

34

Adding Forms to a Macro

API Fundamentals

Exercise 1: Recording a Macro

no Pr t c e-R op e y o lea r d se ist rib ut e

Exercise 1: Recording a Macro

Objective

To familiarize yourself with the starting point of API programming: the macro recorder. The recorder captures the methods necessary for interacting with the SolidWorks application. By recording macros, you are able to automate repetitive tasks in SolidWorks, such as extruding, revolving, suppressing, and selecting.

Skills Learned

I I

Recording, saving, and playing a macro. Customizing the Macro toolbar.

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

Procedure

1. 2. 3. 4.

Do

APIs Used

5. 6. 7. 8. 9.

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

35

Exercise 1:

API Fundamentals

Recording a Macro

Solution

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

no Pr t c e-R op e y o lea r d se ist rib ut e

Dim Dim Dim Dim Dim Dim

Do

Sub main() Set swApp = Application.SldWorks Set Part = swApp.ActiveDoc Set SelMgr = Part.SelectionManager boolstatus = Part.Extension.SelectByID2("Front Plane", _ "PLANE", 0, 0, 0, False, 0, Nothing, 0) Part.InsertSketch2 True Part.ClearSelection2 True Part.CreateCircle 5.432844932845E-04, 0.001086568986569, _ 0, 0.02227466422466, -0.005976129426129, 0 Part.ShowNamedView2 "*Trimetric", 8 Part.ClearSelection2 True boolstatus = Part.Extension.SelectByID2("Arc1", _ "SKETCHSEGMENT", 0, 0, 0, False, 0, Nothing, 0) Part.FeatureManager.FeatureExtrusion2 True, False, False, _ 0, 0, 0.08, 0.00254, False, False, False, False, _ 0.01745329251994, 0.01745329251994, False, False, _ False, False, 1, 1, 1, 0, 0, False Part.SelectionManager.EnableContourSelection = 0 End Sub

36

API Fundamentals

Exercise 2: Adding Macro Code to a VBA Button Control

no Pr t c e-R op e y o lea r d se ist rib ut e

Exercise 2: Adding Macro Code to a VBA Button Control

Objective

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

Skills Learned

I I I I I

Adding a form. Displaying a form. Adding command button controls to a form. Adding code to the click event of a button. Improving macro code with updated methods.

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

Procedure

1. 2. 3. 4. 5.

Do

APIs Used

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

37

Exercise 2:

API Fundamentals

Adding Macro Code to a VBA Button Control

Solution

Option Explicit Sub main() frmMacro1a.Show End Sub --------------------------------------------------------------Option Explicit

no Pr t c e-R op e y o lea r d se ist rib ut e

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

Set swApp = Application.SldWorks Set Part = swApp.ActiveDoc boolstatus = Part.Extension.SelectByID2("Front Plane", _ "PLANE", 0, 0, 0, False, 0, Nothing, 0) Part.InsertSketch2 True Part.CreateCircleByRadius2 0, 0, 0, 0.04 Part.FeatureManager.FeatureExtrusion2 True, False, False, _ 0, 0, 0.01, 0, False, False, False, False, 0.01745, _ 0.01745, False, False, False, False, 1, 1, 1, 0, 0, False End Sub Private Sub cmd20mm_Click() Dim swApp As Object Dim Part As Object Dim boolstatus As Boolean

Do

Set swApp = Application.SldWorks Set Part = swApp.ActiveDoc boolstatus = Part.Extension.SelectByID2("Front Plane", _ "PLANE", 0, 0, 0, False, 0, Nothing, 0) Part.InsertSketch2 True Part.CreateCircleByRadius2 0, 0, 0, 0.04 Part.FeatureManager.FeatureExtrusion2 True, False, False, _ 0, 0, 0.02, 0, False, False, False, False, 0.01745, _ 0.01745, False, False, False, False, 1, 1, 1, 0, 0, False End Sub

Private Sub cmd30mm_Click() Dim swApp As Object Dim Part As Object Dim boolstatus As Boolean Set swApp = Application.SldWorks Set Part = swApp.ActiveDoc boolstatus = Part.Extension.SelectByID2("Front Plane", _ "PLANE", 0, 0, 0, False, 0, Nothing, 0) Part.InsertSketch2 True Part.CreateCircleByRadius2 0, 0, 0, 0.04 Part.FeatureManager.FeatureExtrusion2 True, False, False, _ 0, 0, 0.03, 0, False, False, False, False, 0.01745, _ 0.01745, False, False, False, False, 1, 1, 1, 0, 0, False End Sub

38

API Fundamentals

Exercise 2: Adding Macro Code to a VBA Button Control

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

no Pr t c e-R op e y o lea r d se ist rib ut e

Set swApp = Application.SldWorks Set Part = swApp.ActiveDoc boolstatus = Part.Extension.SelectByID2("Front Plane", _ "PLANE", 0, 0, 0, False, 0, Nothing, 0) Part.InsertSketch2 True Part.CreateCircleByRadius2 0, 0, 0, 0.04 Part.FeatureManager.FeatureExtrusion2 True, False, False, _ 0, 0, 0.04, 0, False, False, False, False, 0.01745, _ 0.01745, False, False, False, False, 1, 1, 1, 0, 0, False End Sub

Private Sub cmdExit_Click() End End Sub

Do

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

39

Exercise 3:

API Fundamentals

Adding User Input Fields on a VBA Form

no Pr t c e-R op e y o lea r d se ist rib ut e

Exercise 3: Adding User Input Fields on a VBA Form

Objective

To automate the feature creation process while allowing for userdefined parameters. You will capture two parameters from the user before running the macro: radius and depth. Within the code, you will declare the variables as string values, convert them to double values and pass them as parameters to the methods. When the user clicks the Build button, the application should create the user-defined cylinder.

Skills Learned

I I I

Adding textbox controls to a form. Declaring variables and converting values from a text box. Debugging code.

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

Procedure

1. 2. 3. 4.

Do

APIs Used

5.

6. 7. 8. 9.

40

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

API Fundamentals

Exercise 3: Adding User Input Fields on a VBA Form

Solution

Option Explicit Sub main() frmMacro1b.Show End Sub --------------------------------------------------------------Option Explicit swApp As Object Part As Object boolstatus As Boolean radius As Double depth As Double

no Pr t c e-R op e y o lea r d se ist rib ut e

Dim Dim Dim Dim Dim

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

Set swApp = Application.SldWorks Set Part = swApp.ActiveDoc boolstatus = Part.Extension.SelectByID2("Front", "Front _ Plane", 0, 0, 0, False, 0, Nothing) Part.InsertSketch2 True Part.CreateCircleByRadius2 0, 0, 0, radius Part.FeatureManager.FeatureExtrusion2 True, False, False, 0,_ 0, depth, 0.01, False, False, False, False, 0.01745, _ 0.01745, False, False, False, False, 1, 1, 1, 0, 0, False End Sub

Do

Private Sub cmdExit_Click() End End Sub ---------------------------------------------------------------

41

Exercise 3:

API Fundamentals

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

Adding User Input Fields on a VBA Form

42

no Pr t c e-R op e y o lea r d se ist rib ut e

API Fundamentals

Lesson 2 The API Object Model

Do

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

Recognize the object relationships and organization within the SolidWorks API Object Model.

I

Connect your macro to the highest level application object in the API Object Model: SldWorks.

I

Use accessors to connect your macro to the other application objects: ModelDoc2, ModelDocExtension, PartDoc, AssemblyDoc and DrawingDoc.

I

Identify common API methods specific to each application object.

I

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

43

Lesson 2

API Fundamentals

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

The API Object Model

44

API Fundamentals

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

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

SolidWorks API Object Model

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.

SolidWorks API Object Model

45

Lesson 2

API Fundamentals

The API Object Model

The macro in this case study also highlights the differences between connecting to new documents versus existing documents. There are different accessor methods on the SldWorks interface that permit you to do this. This case study will also help you understand how the ModelDoc2 object is different from the more specific document object types: PartDoc, AssemblyDoc, and DrawingDoc. Visual Basic 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.)

no Pr t c e-R op e y o lea r d se ist rib ut e

Visual Basic Automatic Type Casting

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.

Do

In C++, type casting would have to be done between the base classes and their derived objects to call the specific methods on their interfaces.

46

SolidWorks API Object Model

API Fundamentals

Lesson 2 The API Object Model

Application Objects

SldWorks Object

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:

no Pr t c e-R op e y o lea r d se ist rib ut e

(swApp)

This lesson introduces an assortment of API calls that connect to SolidWorks and each document type. To use these API calls, you have to first connect to a specific application object. The first object we’ll explore is the top level API interface called SldWorks.

Dim swApp As SldWorks.SldWorks Set swApp = Application.SldWorks

The variable, swApp, is arbitrary and is declared using a generic type, Object, rather than a specific type, SldWorks.SldWorks. This is discussed in Early vs. Late Binding on page 49. As we progress, it is better practice to use early binding techniques when programming with the SolidWorks API. SldWorks Methods and Properties

.NewDocument (TemplateName, PaperSize, Width, Height) .RevisionNumber

.DisplayStatusBar (OnOff) .SolidWorksExplorer

.OpenDoc6 (FileName, Type, Options, Config, Errors, Warnings) .LoadFile2 (FileName, ArgumentString) .CreateNewWindow

.ArrangeWindows (Style)

Do

.ActiveDoc

.ActivateDoc2 (Name, Silent, Errors) .CloseDoc (Name) .QuitDoc (Name) .ExitApp .DocumentVisible (Visible, Type) .SendMsgToUser2 (Message, icons, buttons)

Note

Application Objects

The tables used in this book are not a complete documentation of all methods and properties that exist on the interface being described. For a complete list refer to the API help file.

47

Lesson 2

API Fundamentals

The API Object Model

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.

no Pr t c e-R op e y o lea r d se ist rib ut e

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.

Do

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

48

Application Objects

API Fundamentals

Lesson 2 The API Object Model

IntelliSense

IntelliSense is a Microsoft technology that allows you to preview your code choices by displaying class definitions, methods, properties, parameters and comments as you type your code into the editor. IntelliSense also minimizes typing because it will automatically complete lines of code by allowing you to select your methods and properties from a list.

no Pr t c e-R op e y o lea r d se ist rib ut e

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.

Do

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.

Application Objects

49

Lesson 2

API Fundamentals

The API Object Model

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

Late Binding

Dim swApp As Object Dim swModel As Object

no Pr t c e-R op e y o lea r d se ist rib ut e

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

Early Binding

Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2

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

Tip

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

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

Do

4

50

Test the IntelliSense drop down list.

Begin adding the following code until the IntelliSense appears: Dim swApp As SldWorks.SldWorks Sub main() Set swApp = Application.SldWorks swApp.setu

Application Objects

API Fundamentals

Lesson 2 The API Object Model

no Pr t c e-R op e y o lea r d se ist rib ut e

Use the Up and Down arrow keys on the keyboard to navigate through the drop down list and use the spacebar to have VBA automatically type the rest of the selected method. This saves the programmer the effort of typing things out completely. IntelliSense also corrects some syntax errors automatically and will validate whether or not the type library is being referenced properly. If IntelliSense does not appear by this step, you know you have a problem with your variable declaration or you 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.SldWorks swApp.SetUserPreferenceDoubleValue

End Sub

6

Close the macro.

You are finished testing IntelliSense and early binding.

Do

Case Study: Connecting to New Documents

Tip

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. If the form is not visible in the VBA editor, press Ctrl + R on the keyboard. The Project Explorer window displays. Doubleclick on frmNewDocs under the Forms folder to display the form in the editor.

Case Study: Connecting to New Documents

51

Lesson 2

API Fundamentals

The API Object Model

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:

no Pr t c e-R op e y o lea r d se ist rib ut e

UserForm1: (Name): frmNewDocs Caption: New Documents BorderStyle: 1 fmBorderStyleSingle Startup Position: 2 CenterScreen ShowModal: False Height: 300 Width: 270 Frame1: (Name): fraSldWorks Caption: SldWorks Height: 72 Width: 252

CheckBox1: (Name): chkRevNum Caption: RevisionNumber

CheckBox2: (Name): chkDispStatBar Caption: DisplayStatusBar

CheckBox3: (Name): chkSWExp Caption: SolidWorksExplorer

CommandButton1: (Name): cmdConnect Caption: Connect to SolidWorks

3

Add the button click event.

Do

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.SldWorks Set swApp = Application.SldWorks End Sub

52

Case Study: Connecting to New Documents

API Fundamentals

Lesson 2 The API Object Model

5

Add SldWorks methods and properties.

Continue adding code within the event for the checkboxes: Private Sub cmdConnect_Click() Dim swApp As SldWorks.SldWorks Set swApp = Application.SldWorks

no Pr t c e-R op e y o lea r d se ist rib ut e

If chkRevNum.Value = True Then Dim retval As String retval = swApp.RevisionNumber MsgBox "9.0.0 = SolidWorks 2001 " & vbCrLf & _ "10.0.0 = SolidWorks 2001Plus " & vbCrLf & _ "11.0.0 = SolidWorks 2003" & vbCrLf & _ "12.0.0 = SolidWorks 2004 " & vbCrLf & _ "13.0.0 = SolidWorks 2005" & vbCrLf & _ "14.0.0 = SolidWorks 2006" & vbCrLf & _ "" & vbCrLf & _ "You are running " & retval End If If chkDispStatBar.Value = True Then swApp.DisplayStatusBar True Else swApp.DisplayStatusBar False End If

If chkSWExp.Value = True Then swApp.SolidWorksExplorer End If End Sub

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.

Do

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

Case Study: Connecting to New Documents

53

Lesson 2

API Fundamentals

The API Object Model

Macro Results +

.

no Pr t c e-R op e y o lea r d se ist rib ut e

1.

+

.

3.

+

.

Do

2.

8

54

Stop the macro.

Case Study: Connecting to New Documents

API Fundamentals

Lesson 2 The API Object Model

Now let’s examine the second highest level object in the API object hierarchy, ModelDoc2. ModelDoc2 Object (swModel)

no Pr t c e-R op e y o lea r d se ist rib ut e

The “Topics Found” dialog shown to the right is taken from the SolidWorks API help file. It shows the dialog that appears when you click the Accessors link for ModelDoc2.

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

This is the dialog that allows us to understand which methods are available for successfully connecting to objects further down the Object Model.

‘ option 1 Dim swModel As SldWorks.ModelDoc2 Set swModel = swApp.ActiveDoc ‘ option 2 Dim swModel As SldWorks.ModelDoc2 Set swModel = swApp.NewDocument (TemplateName, PaperSize, _ Width, Height) ‘ option 3 Dim swModel As SldWorks.ModelDoc2 Set swModel = swApp.OpenDoc6 (FileName, Type, Options, _ Config, Errors, Warnings)

ModelDoc2 Methods and Properties .InsertSketch2 (UpdateEditRebuild)

Do

.InsertFamilyTableNew .InsertNote

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

Case Study: Connecting to New Documents

55

Lesson 2

API Fundamentals

The API Object Model

Over the years, enhancements to SolidWorks has increased the amount of methods on the ModelDoc2 object to capacity (1,024). There is now an extension object that serves as a interface for new methods, it is called ModelDocExtension. ModelDoc Extension Use the ModelDoc2 property, Extension, to connect to the Object ModelDocExtension object:

no Pr t c e-R op e y o lea r d se ist rib ut e

(swModelExt)

‘ option 1 - get a pointer to the ModelDocExtension object Dim swModelExt As SldWorks.ModelDocExtension Set swModelExt = swModel.Extension swModelExt.SelectByID2 (....) swModelExt.GetMassProperties (....)

‘ option 2 - call the Extension object directly from ModelDoc2 ‘ as a property without the need for ModelDocExtension pointer Dim swModel As SldWorks.ModelDoc2 Set swModel = swApp.ActiveDoc swModel.Extension.SelectByID2 (....) swModel.Extension.GetMassProperties (....)

ModelDocExtension Methods and Properties

.SelectByID2 (Name, Type, X, Y, Z, Append, Mark, Callout, SelectOption) .GetMassProperties (Accuracy, Status)

Do

The return value for this method is a 0-based array of 13 doubles as follows: returnvalue0 returnvalue1 returnvalue2 returnvalue3 returnvalue4 returnvalue5 returnvalue6 returnvalue7 returnvalue8 returnvalue9 returnvalue10 returnvalue11 returnvalue12

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

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

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

The following steps demonstrate how to use the accessor method SldWorks::NewDocument to create new instances of the ModelDoc2 interface pointer and call several of it’s methods. 56

Case Study: Connecting to New Documents

API Fundamentals

Lesson 2 The API Object Model

9

Review the controls that create new documents.

no Pr t c e-R op e y o lea r d se ist rib ut e

Look to the second frame control on the form. It contains three option buttons, one command button and three more checkboxes. These controls will allow you to create a new ModelDoc2 object. The ModelDoc2 object will be either a PartDoc, AssemblyDoc, or DrawingDoc object. The controls have the following properties: Frame2: (Name): fraModelDoc2 Caption: ModelDoc2 Height: 114 Width: 252 OptionButton1: (Name): optPart Caption: Part Value: True

OptionButton2: (Name): optAssy Caption: Assembly Value: False OptionButton3: (Name): optDraw Caption: Drawing Value: False

CheckBox4: (Name): chkSketch Caption: InsertSketch2

CheckBox5: (Name): chkFamilyTable Caption: InsertFamilyTableNew

Do

CheckBox6: (Name): chkNote Caption: InsertNote

CommandButton2: (Name): cmdNewModel Caption: Connect to Model

10 Add the button click event.

Double-click the second command button to set up the event handler. Private Sub cmdNewModel_Click() End Sub

Case Study: Connecting to New Documents

57

Lesson 2

API Fundamentals

The API Object Model

11 Connect to SldWorks and create a new document.

Add the following lines of programming code: Const filedir As String = "C:\SolidWorks 2006 Training Files\API Fundamentals\Templates\"

no Pr t c e-R op e y o lea r d se ist rib ut e

Private Sub cmdNewModel_Click() Dim swApp As SldWorks.SldWorks Set swApp = Application.SldWorks Dim swModel As SldWorks.ModelDoc2 Set swModel = swApp.NewDocument(filedir + _ "APIPart.prtdot",0, 0#, 0#) End Sub

12 Add code to create different document types.

Add conditional statements to account for each of the three radio button choices. Const filedir As String = "C:\SolidWorks 2006 Training Files\API Fundamentals\Templates\" Private Sub cmdNewModel_Click() Dim swApp As SldWorks.SldWorks Set swApp = Application.SldWorks

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

If optPart.Value = True Then Set swModel = swApp.NewDocument(filedir + _ "APIPart.prtdot",0, 0#, 0#) End If

If optAssy.Value = True Then Set swModel = swApp.NewDocument(filedir + _ "APIAssembly.asmdot", 0, 0#, 0#) End If

Do

If optDraw.Value = True Then Set swModel = swApp.NewDocument(filedir + _ "APIDrawing.drwdot", 0, 0#, 0#) End If

13 Add ModelDoc2 methods and properties.

Add the remaining code for each of the checkboxes. (This code should added right after the code from the previous step and right before the End Sub statement.) ' Determine which items are checked ' and call specific methods and properties on ModelDoc2 If chkSketch.Value = True Then swModel.InsertSketch2 True End If If chkFamilyTable.Value = True Then swModel.InsertFamilyTableNew End If

58

Case Study: Connecting to New Documents

API Fundamentals

Lesson 2 The API Object Model

If chkNote.Value = True Then Dim swNote As Sldworks.Note Dim swAnnotation As Sldworks.Annotation Dim text As String

no Pr t c e-R op e y o lea r d se ist rib ut e

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

14 Save and run the macro.

Try each of the option buttons first: +

+

+

Do

New document

Case Study: Connecting to New Documents

59

Lesson 2

API Fundamentals

The API Object Model

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

+

+

no Pr t c e-R op e y o lea r d se ist rib ut e

+

New sketch

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

+

+

Do

+

New design table

60

Case Study: Connecting to New Documents

API Fundamentals

Lesson 2 The API Object Model

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

+

+

+

+

no Pr t c e-R op e y o lea r d se ist rib ut e

+

Do

New note

Note

Not all ModelDoc2 methods work exactly the same across all three document types. A drawing, for example, would need at least one view inserted before we could use the methods FocusLocked and InsertFamilyTableNew (see step 16 )

Case Study: Connecting to New Documents

61

Lesson 2

API Fundamentals

The API Object Model

15 Stop the macro.

Click the close icon in the upper right corner of the form. 16 Add code to prepare the drawing.

Add this user defined function at the bottom of the module to prepare a drawing:

no Pr t c e-R op e y o lea r d se ist rib ut e

Private Function preparedrawingView(ByRef swApp As _ SldWorks.SldWorks, ByRef swModel As ModelDoc2) As _ SldWorks.View Dim drawname As String Dim errors As Long Dim warnings As Long

drawname = swModel.GetTitle swApp.OpenDoc6 filedir + "BlockwithDesignTable.SLDPRT", 1, _ 0, "", errors, warnings Set swModel = swApp.ActivateDoc2(drawname, True, errors) 'Notice automatic typecasting to DrawingDoc! Set preparedrawingView = swModel.CreateDrawViewFromModelView_ (filedir + "BlockwithDesignTable.SLDPRT", "*Isometric", 0.1,_ 0.1, 0) End Function

Note

Notice that Visual Basic automatically type casts the ModelDoc2 object to a DrawingDoc object and allows you to call the method CreateDrawViewFromModelView directly from the ModelDoc2 object. CreateDrawViewFromModelView is a method on the DrawingDoc interface. Another thing to note is that as you type, you will not see this method using IntelliSense.

17 Insert new code to call the new function.

Do

Insert these additional condition statements for FocusLocked and InsertFamilyTableNew to call the new function from the previous step: Dim swView As SldWorks.View If chkSketch.Value = True Then If optDraw.Value = True Then Set swView = preparedrawingView(swApp, swModel) swView.FocusLocked = True Else swModel.InsertSketch2 True End If End If

If chkFamilyTable.Value = True Then If optDraw.Value = True Then Set swView = preparedrawingView(swApp, swModel) swModel.SelectByID swView.Name, "DRAWINGVIEW", 0, 0, 0 swModel.InsertFamilyTableNew Else swModel.InsertFamilyTableNew End If End If

62

Case Study: Connecting to New Documents

API Fundamentals

Lesson 2 The API Object Model

18 Save and run the macro.

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

+

+

no Pr t c e-R op e y o lea r d se ist rib ut e

+

Sketch mode is now active in view

Design table is inserted into view

19 Stop the macro.

Do

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

Case Study: Connecting to New Documents

63

Lesson 2

API Fundamentals

The API Object Model

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

no Pr t c e-R op e y o lea r d se ist rib ut e

AssemblyDoc Object

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.

(swAssy)

DrawingDoc Object (swDraw)

Dim Dim Dim Dim

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

Set swModel = swApp.ActiveDoc

If (swModel.GetType = swDocPART) Then Set swPart = swModel End If

If (swModel.GetType = swDocASSEMBLY) Then Set swAssy = swModel End If If (swModel.GetType = swDocDRAWING) Then Set swDraw = swModel End If

If swModel Is Nothing Then swApp.SendMsgToUser "Open a part, assembly or drawing!" End If

PartDoc Methods and Properties .EditRollback

.MaterialPropertyValues .CreateNewBody

Do

.MirrorPart

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

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

64

Case Study: Connecting to New Documents

API Fundamentals

Lesson 2 The API Object Model

20 Review the controls for the specific document types.

At the bottom of the form, each document type has a frame, a command button, and a checkbox. The properties for the controls are as follows:

no Pr t c e-R op e y o lea r d se ist rib ut e

Frame3: (Name): fraPart Caption: PartDoc Height: 66 Width: 78

CommandButton3: (Name): cmdPart Caption: New Model

CheckBox7: (Name): chkRollback Caption: EditRollback ----------------------------frame4: (Name): fraAssy Caption: AssemblyDoc Height: 66 Width: 84 CommandButton4: (Name): cmdAssy Caption: New Assembly

CheckBox8: (Name): chkComponent Caption: AddComponent ----------------------------Frame5: (Name): fraDraw Caption: DrawingDoc Height: 66 Width: 78

Do

CommandButton5: (Name): cmdDraw Caption: New Drawing CheckBox9: (Name): chkFormat Caption: EditFormat

21 Add a click event to each button.

Double-click the new command buttons to set up each click event. Private Sub cmdPart_Click() End Sub Private Sub cmdAssy_Click() End Sub Private Sub cmdDraw_Click() End Sub

Case Study: Connecting to New Documents

65

Lesson 2

API Fundamentals

The API Object Model

22 Connect to the SldWorks object.

Add the following lines of programming code within each event: cmdPart_Click() As SldWorks.SldWorks = Application.SldWorks cmdAssy_Click() As SldWorks.SldWorks = Application.SldWorks

no Pr t c e-R op e y o lea r d se ist rib ut e

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

cmdDraw_Click() As SldWorks.SldWorks = Application.SldWorks

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

Add the following code:

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

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

Do

Add the following code:

Private Sub cmdAssy_Click() Dim swApp As SldWorks.SldWorks Set swApp = Application.SldWorks Dim fileerror As Long Dim filewarning As Long swApp.OpenDoc6 filedir + "Sample.sldprt", swDocPART, _ swOpenDocOptions_ViewOnly, "", fileerror, filewarning Dim swModel As SldWorks.ModelDoc2 Set swModel = swApp.NewDocument(filedir + _ "APIAssembly.asmdot", 0, 0#, 0#)

Dim swAssy As SldWorks.AssemblyDoc Set swAssy = swModel If chkComponent.value = True Then swAssy.AddComponent2 filedir + "Sample.sldprt", 0, 0, 0 swModel.FeatureManager.UpdateFeatureTree End If End Sub

66

Case Study: Connecting to New Documents

API Fundamentals

Lesson 2 The API Object Model

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

Add the following code:

no Pr t c e-R op e y o lea r d se ist rib ut e

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

26 Test each of the following: Save and run the macro.

+

Before

Do

After

Rollback

Case Study: Connecting to New Documents

67

Lesson 2

API Fundamentals

The API Object Model

+

no Pr t c e-R op e y o lea r d se ist rib ut e

Before

After

New component

+

Before

Do

After

Edit sheet format is now active in drawing

27 Stop the macro..

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

68

Case Study: Connecting to New Documents

API Fundamentals

Lesson 2 The API Object Model

Case Study: Connecting to Existing Documents

So far, we have used the method NewDocument to create new instances of the different document interfaces. We will now connect to existing documents that have already been opened in your SolidWorks session.

no Pr t c e-R op e y o lea r d se ist rib ut e

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\"

Do

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

If chkOpen.value = True Then Dim fileerror As Long Dim filewarning As Long swApp.OpenDoc6 filedir + "Sample.sldprt", swDocPART, _ swOpenDocOptions_ViewOnly, "", fileerror, filewarning End If If chkLoad.value = True Then swApp.LoadFile2 filedir + "Sample.igs", "" End If

If chkNewWindow.value = True Then swApp.CreateNewWindow swApp.ArrangeWindows 1 End If End Sub

Case Study: Connecting to Existing Documents

69

Lesson 2

API Fundamentals

The API Object Model

30 Add code to module.

Switch back to the ObjectModelBasics1 module. Put a comment in front of the first line, and show the new form on the second line:

no Pr t c e-R op e y o lea r d se ist rib ut e

Sub main() ‘frmNewDocs.Show frmExistingDocs.Show End Sub

31 Save and run macro.

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

+

.

2.

+

.

3.

+

.

32 Stop macro.

Click the close icon in the upper right corner of the form. Return to the VBA editor.

33 Review methods available for every document type. Click View, Code or double-click the second command button named:

Connect to Model.

Private Sub cmdNewModel_Click() Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2

Do

Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc ' Check to see if a document is loaded If swModel Is Nothing Then swApp.SendMsgToUser "Open a part, assembly or drawing." Exit Sub End If

70

If chkToolbars.value = True Then swModel.SetToolbarVisibility swFeatureToolbar, True swModel.SetToolbarVisibility swMacroToolbar, True swModel.SetToolbarVisibility swMainToolbar, True swModel.SetToolbarVisibility swSketchToolbar, True swModel.SetToolbarVisibility swSketchToolsToolbar, True swModel.SetToolbarVisibility swStandardToolbar, True swModel.SetToolbarVisibility swStandardViewsToolbar, True swModel.SetToolbarVisibility swViewToolbar, True End If

Case Study: Connecting to Existing Documents

API Fundamentals

Lesson 2 The API Object Model

no Pr t c e-R op e y o lea r d se ist rib ut e

If chkToolbars.value = False Then swModel.SetToolbarVisibility swFeatureToolbar, False swModel.SetToolbarVisibility swMacroToolbar, False swModel.SetToolbarVisibility swMainToolbar, False swModel.SetToolbarVisibility swSketchToolbar, False swModel.SetToolbarVisibility swSketchToolsToolbar, False swModel.SetToolbarVisibility swStandardToolbar, False swModel.SetToolbarVisibility swStandardViewsToolbar, False swModel.SetToolbarVisibility swViewToolbar, False End If

If chkCustomInfo.value = True Then Dim retval As Boolean retval = swModel.AddCustomInfo3("", "MyInfo", _ swCustomInfoText, "MyData") End If End Sub

34 Open the following files and run the macro.

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

.

Do

Toolbars hidden

Case Study: Connecting to Existing Documents

71

Lesson 2

API Fundamentals

The API Object Model

+

.

no Pr t c e-R op e y o lea r d se ist rib ut e

Toolbars visible

+

Do

Custom Property

72

Case Study: Connecting to Existing Documents

API Fundamentals

Lesson 2 The API Object Model

35 Stop the macro.

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

Existing Part.

no Pr t c e-R op e y o lea r d se ist rib ut e

Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2 Dim swPart As SldWorks.PartDoc

Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc Set swPart = swModel 'Explicit Type Cast

' Check to see if a part is loaded If swModel Is Nothing Then swApp.SendMsgToUser "Please open a part." Exit Sub End If

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

Do

Set swModel = swApp.ActiveDoc swModel.ShowNamedView2 "*Isometric", 7 swModel.ViewZoomtofit2 swApp.ArrangeWindows 1 Dim retval As Boolean Dim errors As Long Set swModel = swApp.ActivateDoc2("sheetmetalsample.SLDPRT",_ True, errors) retval = swModel.DeSelectByID("Top", "PLANE", 0, 0, 0) End If End Sub

Case Study: Connecting to Existing Documents

73

Lesson 2

API Fundamentals

The API Object Model

37 Run the macro.

Use the part file: SheetMetalSample.sldprt .

no Pr t c e-R op e y o lea r d se ist rib ut e

+

Mirrored part

38 Stop the macro..

Return to the VBA editor.

39 Review method available only to AssemblyDoc.

Do

Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2 Dim swAssy As SldWorks.AssemblyDoc Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc Set swAssy = swModel 'Explicit Type Cast! ' Check to see if an assembly is loaded If swModel Is Nothing Then swApp.SendMsgToUser "Please open an assembly." Exit Sub End If

74

If chkCavity.value = True Then Dim boolstatus As Boolean boolstatus = _ swModel.Extension.SelectByID2( _ "sheetmetalsample-1@sheetmetalsample", "COMPONENT", 0, 0, _ 0, False, 0, Nothing, 0) swAssy.EditPart swModel.ClearSelection boolstatus = swModel.Extension.SelectByID2( _ "plug-1@sheetmetalsample", "COMPONENT", 0, 0, 0, True, _ 0 ,Nothing, 0) swAssy.InsertCavity4 10, 10, 10, 1, 1, -1 swAssy.EditAssembly boolstatus = swModel.Extension.SelectByID2( _ "plug-1@sheetmetalsample", "COMPONENT", 0, 0, 0, _ True, 0,Nothing, 0) swAssy.EditSuppress2 End If

Case Study: Connecting to Existing Documents

API Fundamentals

Lesson 2 The API Object Model

40 Run macro.

Use the assembly file: SheetMetalSample.sldasm .

no Pr t c e-R op e y o lea r d se ist rib ut e

+

Edit part

Select component

Insert cavity

Do

Return to edit assembly mode

Suppress part to view cavity

Case Study: Connecting to Existing Documents

75

Lesson 2

API Fundamentals

The API Object Model

41 Stop the macro.

Return to the VBA editor. 42 Review method available only to DrawingDoc. Click View, Code.

no Pr t c e-R op e y o lea r d se ist rib ut e

Private Sub cmdDraw_Click() Dim swApp As SldWorks.SldWorks Dim swDraw As SldWorks.DrawingDoc Set swApp = Application.SldWorks Set swDraw = swApp.ActiveDoc

'Check to see if a drawing is loaded If swDraw Is Nothing Then swApp.SendMsgToUser "Please open a drawing." Exit Sub End If

If chkLayer.value = True Then 'Notice automatic type cast. swDraw.ClearSelection Dim retval As Boolean retval = swDraw.CreateLayer("MyRedLayer", "Red", RGB(255, _ 0,0), swLineSTITCH, swLW_THICK, True) End If End Sub

43 Run macro.

Use the drawing file: SheetMetalSample.slddrw

Do

+

.

New layer

44 Exit macro.

76

Case Study: Connecting to Existing Documents

API Fundamentals

Exercise 4: Working with New Documents

Exercise 4: Working with New Documents

To connect a macro to the SolidWorks application, create new documents, and call methods on SldWorks and ModelDoc2 objects.

Skills Learned

I

no Pr t c e-R op e y o lea r d se ist rib ut e

Objective

I I I

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

APIs Used

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

Procedure

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

Do

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

77

Exercise 4:

API Fundamentals

Working with New Documents

Solution

Option Explicit Sub main() frmNewDocs.Show End Sub --------------------------------------------------------------Option Explicit

no Pr t c e-R op e y o lea r d se ist rib ut e

Const filedir As String = "C:\SolidWorks 2006 Training Files\API Fundamentals\Templates\" Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2

Private Sub cmdSldWorks_Click() Set swApp = Application.SldWorks

If chkMessage.Value = True Then swApp.SendMsgToUser2 "Hello, this is a sample message", 1, 2 End If

End Sub

Private Sub cmdModel_Click() Set swApp = Application.SldWorks

If optPart.Value = True Then Set swModel = swApp.NewDocument(filedir + _ "APIPart.prtdot", 0, 0#, 0#) End If If optAssy.Value = True Then Set swModel = swApp.NewDocument(filedir + _ "APIAssembly.asmdot", 0, 0#, 0#) End If

Do

If chkCircle.Value = True Then swModel.InsertSketch2 True swModel.CreateCircleByRadius2 0, 0, 0, 0.05 swModel.ViewZoomtofit2 End If

78

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

API Fundamentals

Exercise 5: Working with Existing Documents

Exercise 5: Working with Existing Documents

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

Skills Learned

I

no Pr t c e-R op e y o lea r d se ist rib ut e

Objective

I I I

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

APIs Used

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

Procedure

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

Do

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

79

Exercise 5:

API Fundamentals

Working with Existing Documents

Solution

Option Explicit Sub main() frmExistingDocs.Show End Sub --------------------------------------------------------------Option Explicit

no Pr t c e-R op e y o lea r d se ist rib ut e

Const filedir As String = "C:\SolidWorks 2006 Training Files\API Fundamentals\Templates\" Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2

Private Sub cmdSldWorks_Click() Set swApp = Application.SldWorks If chkOpen.Value = True Then Dim fileerror As Long Dim filewarning As Long

If optPart.Value = True Then swApp.OpenDoc6 filedir + "sample.sldprt", swDocPART, _ swOpenDocOptions_Silent, "", fileerror, filewarning End If

If optAssy.Value = True Then swApp.OpenDoc6 filedir + "sample.sldasm", swDocASSEMBLY, _ swOpenDocOptions_Silent, "", fileerror, filewarning End If

End If

End Sub

Do

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

' Check to see if a document is loaded If swModel Is Nothing Then swApp.SendMsgToUser "Please open a part or assembly." Exit Sub End If

If chkSpot.Value = True Then swModel.AddLightSource "SW#2", 4, "Directional2" swModel.SetLightSourcePropertyValuesVB "SW#2", 4, 1, _ 16777215, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 swModel.LockLightToModel 2, False swModel.GraphicsRedraw End If End Sub

80

no Pr t c e-R op e y o lea r d se ist rib ut e

API Fundamentals

Do

Lesson 3 Setting System Options and Document Properties

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

Use the API to change system options and document properties.

I

Locate and automate checkboxes, textbox values, listboxes, radio buttons and slider bars within the SolidWorks options dialog.

81

Do no Pr t c e-R op e y o lea r d se ist rib ut e

Lesson 3

82

API Fundamentals

API Fundamentals

User Preferences System Options

Lesson 3

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

no Pr t c e-R op e y o lea r d se ist rib ut e

SldWorks::SetUserPreferenceIntegerValue SldWorks::SetUserPreferenceDoubleValue SldWorks::SetUserPreferenceStringValue

Note

Each method listed above also has a counterpart. Substitute SetUserPreference with GetUserPreference to retrieve existing system options.

Setting Checkboxes

Call the SldWorks::SetUserPreferenceToggle method to turn on and off checkbox items within the SolidWorks options dialog.

SldWorks::SetUserPreferenceToggle

SldWorks.SetUserPreferenceToggle (UserPreferenceValue, onFlag)

Input:

See UserPreference Tables For System Options on page 92. Toggle items are designated with “Toggle”.

onFlag

TRUE =

Do

Input:

UserPreferenceValue

User Preferences - System Options

FALSE

toggle the item on = toggle the item off

83

Lesson 3

API Fundamentals

1

Create a new macro. Click the New Macro

button on the Macro toolbar.

Name the macro SystemOptions.swp. 2

Early bind to SolidWorks.

no Pr t c e-R op e y o lea r d se ist rib ut e

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.SldWorks swApp.SetUserPreferenceToggle _ swConst.swInputDimValOnCreate, True swApp.SetUserPreferenceToggle _ swConst.swSingleCommandPerPick, True swApp.SetUserPreferenceToggle _ swConst.swShowDimensionNames, True swApp.SetUserPreferenceToggle _ swConst.swShowErrorsEveryRebuild, True End Sub

4

Save and run the macro.

Test to see if the checkboxes are enabled. Return to VBA when finished.

Do

Tip

84

In many cases an option may only need to be changed when the macro is run. It is polite to set a changed option to the value it was set before the macro runs. An end user may become irritated if they have to manually change the option back to their preference every time they run the macro.

User Preferences - System Options

API Fundamentals

Lesson 3

Setting Textboxes with Integers

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

SldWorks::SetUserPreferenceIntegerValue

no Pr t c e-R op e y o lea r d se ist rib ut e

retval = swApp.SetUserPreferenceIntegerValue (UserPreferenceValue, value)

Output:

retval

TRUE

Input:

UserPreferenceValue

See UserPreference Tables For System Options on page 92. Integer value items are designated with “Int”.

value

Numeric value that you want to give to the user preference specified in userPreferenceValue

Input:

5

if the successful, FALSE if not.

Add code to change viewport color. On the Colors page, change the Viewport Background color value.

Do

Dim swApp As SldWorks.SldWorks Dim viewportColor As Long Sub main() Set swApp = Application.SldWorks swApp.SetUserPreferenceToggle _ swConst.swInputDimValOnCreate, True swApp.SetUserPreferenceToggle _ swConst.swSingleCommandPerPick, True swApp.SetUserPreferenceToggle _ swConst.swShowDimensionNames, True swApp.SetUserPreferenceToggle _ swConst.swShowErrorsEveryRebuild,True viewportColor = RGB(128, 255, 128) ‘sets color to green swApp.SetUserPreferenceIntegerValue _ swConst.swSystemColorsViewportBackground, viewportColor End Sub

6

Save and run macro.

Test to see if the textbox values have changed. Return to VBA when finished.

User Preferences - System Options

85

Lesson 3

API Fundamentals

Setting Textboxes with Doubles

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

SldWorks::SetUserPreferenceDoubleValue

no Pr t c e-R op e y o lea r d se ist rib ut e

retval = swApp.SetUserPreferenceDoubleValue (UserPreferenceValue, value)

Output:

retval

TRUE

Input:

UserPreferenceValue

See UserPreference Tables For System Options on page 92. Double value items are designated with “Double”.

value

Numeric value that you want to give to the user preference specified in userPreferenceValue

Input:

7

if the successful, FALSE if not.

Add code to change the detail view scale. On the Drawings page, change the Detail View Scaling value.

Do

Set swApp = Application.SldWorks swApp.SetUserPreferenceToggle _ swConst.swInputDimValOnCreate, True swApp.SetUserPreferenceToggle _ swConst.swSingleCommandPerPick, True swApp.SetUserPreferenceToggle _ swConst.swShowDimensionNames, True swApp.SetUserPreferenceToggle _ swConst.swShowErrorsEveryRebuild,True color = RGB(128, 255, 128) ‘sets color to green swApp.SetUserPreferenceIntegerValue _ swConst.swSystemColorsViewportBackground, color swApp.SetUserPreferenceDoubleValue _ swConst.swDrawingDetailViewScale, 1.5 End Sub

8

Save and run macro.

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

86

User Preferences - System Options

API Fundamentals

Lesson 3

Setting Textboxes with String Values

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

SldWorks::SetUserPreferenceStringValue

no Pr t c e-R op e y o lea r d se ist rib ut e

retval = swApp.SetUserPreferenceStringValue (UserPreferenceValue, value)

Output:

retval

TRUE

Input:

UserPreferenceValue

See UserPreference Tables For System Options on page 92. String value items are designated with “String”.

value

Numeric value that you want to give to the user preference specified in userPreferenceValue

Input:

9

if the successful, FALSE if not.

Add code to change backup directory string value.

Do

On the Backups page, change the Save Backup Copies in Directory string value. Dim value As String Sub main() Set swApp = Application.SldWorks swApp.SetUserPreferenceToggle _ swConst.swInputDimValOnCreate, True swApp.SetUserPreferenceToggle _ swConst.swSingleCommandPerPick, True swApp.SetUserPreferenceToggle _ swConst.swShowDimensionNames, True swApp.SetUserPreferenceToggle _ swConst.swShowErrorsEveryRebuild, True color = RGB(128, 255, 128) ‘sets color to green swApp.SetUserPreferenceIntegerValue _ swConst.swSystemColorsViewportBackground, color swApp.SetUserPreferenceDoubleValue _ swConst.swDrawingDetailViewScale, 1.5 value = ("D:\Temp") swApp.SetUserPreferenceStringValue _ swConst.swBackupDirectory, value End Sub

10 Save and run macro.

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

User Preferences - System Options

87

Lesson 3

Call the SldWorks::SetUserPreferenceIntegerValue; StringValue or Toggle method (for lists that have only two choices) to change listbox values.

no Pr t c e-R op e y o lea r d se ist rib ut e

Setting Listboxes

API Fundamentals

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.

Do

Setting Radio Buttons

88

User Preferences - System Options

API Fundamentals

Lesson 3

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

On the Display/Selections page, change the Hidden Edges Displayed As option to Solid. On the View Rotation page, change the Mouse Speed value and the View Animation Speed value.

no Pr t c e-R op e y o lea r d se ist rib ut e

Dim swApp As SldWorks.SldWorks Dim color As Long Dim value As String

Sub main() Set swApp = Application.SldWorks swApp.SetUserPreferenceToggle _ swConst.swInputDimValOnCreate, True swApp.SetUserPreferenceToggle _ swConst.swSingleCommandPerPick, True swApp.SetUserPreferenceToggle _ swConst.swShowDimensionNames, True swApp.SetUserPreferenceToggle _ swConst.swShowErrorsEveryRebuild,True color = RGB(128, 255, 128) ‘sets color to green swApp.SetUserPreferenceIntegerValue _ swConst.swSystemColorsViewportBackground, color swApp.SetUserPreferenceDoubleValue _ swConst.swDrawingDetailViewScale, 1.5 value = ("D:\Temp") swApp.SetUserPreferenceStringValue _ swConst.swBackupDirectory, value swApp.SetUserPreferenceIntegerValue _ swConst.swEdgesHiddenEdgeDisplay, _ swConst.swEdgesHiddenEdgeDisplayDashed

Do

‘ View Rotation - Mouse Speed ‘ 0 = Slow ‘ 100 = Fast swApp.SetUserPreferenceIntegerValue _ swConst.swViewRotationMouseSpeed, 50

‘ View Rotation - ViewAnimationSpeed ‘ 0 = Off ‘ 0.5 = Fast ‘ 1.0 ‘ 1.5 ‘ 2.0 ‘ 2.5 ‘ 3.0 = Slow swApp.SetUserPreferenceDoubleValue _ swConst.swViewAnimationSpeed, 1.5 End Sub

12 Save and run macro.

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

User Preferences - System Options

89

Lesson 3

API Fundamentals

User Preferences Document Properties

In order to customize or automate default document properties in SolidWorks, it is necessary to connect to both the SldWorks object and the ModelDoc2 object. Then call the same user preference methods as before but make the call to ModelDoc2, instead of to SldWorks. ModelDoc2::SetUserPreferenceToggle

no Pr t c e-R op e y o lea r d se ist rib ut e

ModelDoc2::SetUserPreferenceIntegerValue ModelDoc2::SetUserPreferenceDoubleValue ModelDoc2::SetUserPreferenceStringValue

The following table highlights the ability to set a checkbox for document property using ModelDoc2, not SldWorks.

ModelDoc2::SetUserPreferenceToggle

ModelDoc2.SetUserPreferenceToggle (UserPreferenceValue, onFlag)

Input:

Input:

UserPreferenceValue

See UserPreference Tables For System Options on page 92. Toggle items are designated with “Toggle”.

onFlag

TRUE =

toggle the item on toggle the item off

Do

FALSE =

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

90

User Preferences - Document Properties

API Fundamentals

Lesson 3

4

Connect to ModelDoc2.

Add the following lines of code: Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2

no Pr t c e-R op e y o lea r d se ist rib ut e

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

5

Add code to change toggle value.

On the Document Properties, Detailing page enable the checkbox for Dual Dimension Display. Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2

Sub main() Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc swModel.SetUserPreferenceToggle _ swConst.swDetailingDualDimensions, True End Sub

6

Create a new part in SolidWorks.

Save and run the macro.

Test to see if the checkbox is enabled.

Do

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.

Locating the Correct APIs and Enumeration Values

91

Lesson 3

API Fundamentals

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.

no Pr t c e-R op e y o lea r d se ist rib ut e

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

UserPreference Tables For System Options

The following tables list all of the System Options and how they are represented by the API. The tables have three columns that show the:

I

Do

I

Note

92

I

Setting in the System Options to be changed. Type of user preference method used to change the setting. Enumerations / Values used when changing the options.

Most of the options are supported by the API, however some are not. The Enumeration / Value column will display Not Supported if the setting cannot be changed by the API. Some settings can be set on both the SldWorks and the ModelDoc2 object. An example would be the Mouse Speed that was shown in the previous case study. Study the User Preference enumeration values in the API help file for more information.

UserPreference Tables For System Options

API Fundamentals

Lesson 3

no Pr t c e-R op e y o lea r d se ist rib ut e

General

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

String

swCustomPropertyUsedAsComponentDescription

Do

Setting

Custom property used as component description

UserPreference Tables For System Options

93

Lesson 3

API Fundamentals

no Pr t c e-R op e y o lea r d se ist rib ut e

Drawings

Type

Enumeration / Values

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

Do

Setting

Keyboard movement increment

94

Not Supported

UserPreference Tables For System Options

API Fundamentals

Lesson 3

no Pr t c e-R op e y o lea r d se ist rib ut e

Display Style

Type

Enumeration / Values

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

Do

Setting

UserPreference Tables For System Options

95

Lesson 3

API Fundamentals

no Pr t c e-R op e y o lea r d se ist rib ut e

Area Hatch

Setting

Type

Enumeration / Values

Area Hatch / Fill

Int

swDrawingAreaHatchFillStyle swAreaHatchFillStyle_e

Pattern

String

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

Double

swDrawingAreaHatchScale

Double

swDrawingAreaHatchAngle

Scale

Do

Angle

96

UserPreference Tables For System Options

API Fundamentals

Lesson 3

no Pr t c e-R op e y o lea r d se ist rib ut e

Colors

Type

Enumeration / Values

Viewport Background

Int

swSystemColorsViewportBackground

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

Do

Setting

UserPreference Tables For System Options

97

Lesson 3

API Fundamentals

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

no Pr t c e-R op e y o lea r d se ist rib ut e

Grid Lines, Major

PropertyManagerSkin

Not Supported

Current Color Scheme

Not Supported

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

Do

Use gradient background

98

UserPreference Tables For System Options

API Fundamentals

Lesson 3

no Pr t c e-R op e y o lea r d se ist rib ut e

Sketch

Type

Enumeration / Values

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

Do

Setting

UserPreference Tables For System Options

99

Lesson 3

API Fundamentals

no Pr t c e-R op e y o lea r d se ist rib ut e

Relations / Snaps

Setting

Type

Enumeration / Values

Enable Snapping

Toggle

swFullyConstrainedSketchMode

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

Toggle

swSketchSnapsTangent

Perpendicular

Toggle

swSketchSnapsPerpendicular

Parallel

Toggle

swSketchSnapsParallel

Horizontal/vertical lines

Toggle

swSketchSnapsHVLines

Horizontal/vertical to points

Toggle

swSketchSnapsHVPoints

Length

Tangent

swSketchSnapsLength

Toggle

swSketchSnapsGrid

Snap only when grid is displayed

Toggle

swSnapOnlyIfGridDisplayed

Angle

Toggle

swSketchSnapsAngle

Snap angle

Double

swSnapToAngleValue

Do

Toggle

Grid

100

UserPreference Tables For System Options

API Fundamentals

Lesson 3

no Pr t c e-R op e y o lea r d se ist rib ut e

Display / Selection

Type

Enumeration / Values

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

Do

Setting

UserPreference Tables For System Options

101

Lesson 3

API Fundamentals

no Pr t c e-R op e y o lea r d se ist rib ut e

Performance

Type

Enumeration / Values

Verification on rebuild

Toggle

swPerformanceVerifyOnRebuild

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

Do

Setting

102

UserPreference Tables For System Options

API Fundamentals

Lesson 3

no Pr t c e-R op e y o lea r d se ist rib ut e

Assemblies

Type

Enumeration / Values

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

Do

Setting

UserPreference Tables For System Options

103

Lesson 3

API Fundamentals

no Pr t c e-R op e y o lea r d se ist rib ut e

External References

Type

Enumeration / Values

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

Do

Setting

104

UserPreference Tables For System Options

API Fundamentals

Lesson 3

no Pr t c e-R op e y o lea r d se ist rib ut e

Default Templates

Setting

Type

Enumeration / Values

Parts

String

swDefaultTemplatePart

Assemblies

String

swDefaultTemplateAssembly

Drawings

String

swDefaultTemplateDrawing

Toggle

swAlwaysUseDefaultTemplates

Do

Always use the default document templates Prompt user to select document template

UserPreference Tables For System Options

105

Lesson 3

API Fundamentals

no Pr t c e-R op e y o lea r d se ist rib ut e

File Locations

Type

Enumeration / Values

Document Templates

String

swFileLocationsDocumentTemplates

Referenced Documents

String

swFileLocationsDocuments

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

Do

Setting

106

UserPreference Tables For System Options

API Fundamentals

Lesson 3

Spelling Folders

String

Not Supported

Scene Folders

String

swFileLocationsScenes

Light Folders

String

swFileLocationsLights

no Pr t c e-R op e y o lea r d se ist rib ut e

Spin Box Increments

Type

Enumeration / Values

English Units

Double

swSpinBoxEnglishLengthIncrement

Metric Units

Double

swSpinBoxMetricLengthIncrement

Angle increments

Double

swSpinBoxAngleIncrement

Do

Setting

UserPreference Tables For System Options

107

Lesson 3

API Fundamentals

no Pr t c e-R op e y o lea r d se ist rib ut e

View Rotation

Type

Enumeration / Values

Arrow keys

Double

swViewRotationArrowKeys

Mouse speed

Int

swViewRotationMouseSpeed 0 - 100 (100 is max speed)

View animation speed

Double

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

Do

Setting

108

UserPreference Tables For System Options

API Fundamentals

Lesson 3

no Pr t c e-R op e y o lea r d se ist rib ut e

Backups

Type

Enumeration / Values

Save auto recover info every

Int

swAutoSaveInterval Set to 0 to turn this option off

# changes

Int

swAutoSaveInterval Anything larger than 0 will turn this on and set the velue

Number of backup copies per document

Int

swBackupCopiesPerDocument

Save backup files in the same location as the original

Toggle

swSaveBackupFilesInSameLocationAsOriginal

Save backup copies in directory

String

swBackupDirectory

Do

Setting

UserPreference Tables For System Options

109

Lesson 3

API Fundamentals

no Pr t c e-R op e y o lea r d se ist rib ut e

File Explorer

Setting

Type

Enumeration / Values

My Documents

Toggle

swFileExplorerShowMyDocuments

My Computer

Toggle

swFileExplorerShowMyComputer

My Network Places

Toggle

swFileExplorerShowMyNetworkPlaces

Recent Documents

Toggle

swFileExplorerShowRecentDocuments

Hidden referenced documents

Toggle

swFileExplorerShowHiddenReferencedDocuments

Samples

Toggle

swFileExplorerShowSamples

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

Do

Collaboration

110

UserPreference Tables For System Options

API Fundamentals

UserPreference Tables For Document Properties

Lesson 3

The following tables list all of the Document Properties and how they are represented by the API.

no Pr t c e-R op e y o lea r d se ist rib ut e

Detailing

Type

Enumeration / Values

Dimensioning Standard

Int

swDetailingDimensionStandard Use enumeration values from swDetailingStandard_e to change the standard

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

Do

Setting

UserPreference Tables For Document Properties

111

Lesson 3

API Fundamentals

no Pr t c e-R op e y o lea r d se ist rib ut e

Dimensions

Type

Enumeration / Values

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

Do

Setting

112

UserPreference Tables For Document Properties

API Fundamentals

Lesson 3

no Pr t c e-R op e y o lea r d se ist rib ut e

Notes

Type

Enumeration / Values

Text Alignment

Int

swDetailingNoteTextAlignment swTextJustification_e

Leader Anchor

Int

swDetailingNoteLeaderSide swLeaderSide_e

Leader Style

Int

swDetailingNotesLeaderStyle swLeaderStyle_e

Leader Length

Double

swDetailingNoteBentLeaderLength

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

Do

Setting

UserPreference Tables For Document Properties

113

Lesson 3

API Fundamentals

no Pr t c e-R op e y o lea r d se ist rib ut e

Balloons

Type

Enumeration / Values

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

Do

Setting

114

UserPreference Tables For Document Properties

API Fundamentals

Lesson 3

no Pr t c e-R op e y o lea r d se ist rib ut e

Arrows

Type

Enumeration / Values

Arrow Height

Double

swDetailingArrowHeight

Arrow Width

Double

swDetailingArrowWidth

Arrow Length

Double

swDetailingArrowLength

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

Do

Setting

UserPreference Tables For Document Properties

115

Lesson 3

API Fundamentals

no Pr t c e-R op e y o lea r d se ist rib ut e

Virtual Sharps

Setting

Type

Enumeration / Values

Virtual Sharps Style

Int

swDetailingVirtualSharpStyle swDetailingVirtualSharp_e

Setting

Type

Enumeration / Values

Cosmetic Threads

Toggle

swDisplayCosmeticThreads

Datums

Toggle

swDisplayDatums

Datum Targets

Toggle

swDisplayDatumTargets

Feature dimensions

Toggle

swDisplayFeatureDimensions

Reference dimensions

Toggle

swDisplayReferenceDimensions

Shaded cosmetic threads

Toggle

swDisplayShadedCosmeticThreads

Geometric tolerances

Toggle

swDisplayGeometricTolerances

Notes

Toggle

swDisplayNotes

Surface finish

Toggle

swDisplaySurfaceFinishSymbols

Do

Annotations Display

116

UserPreference Tables For Document Properties

API Fundamentals

Lesson 3

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

Setting

Type

Enumeration / Values

Note

Text Format

swDetailingNoteTextFormat

Dimension

Text Format

swDetailingDimensionTextFormat

Detail

Text Format

swDetailingDetailTextFormat

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

Welds

Section

Text Format

swDetailingSectionTextFormat

View Arrow

Text Format

swDetailingViewArrowTextFormat

Surface Finish

Text Format

swDetailingSurfaceFinishTextFormat

Weld Symbol

Text Format

swDetailingWeldSymbolTextFormat

Tables

Text Format

swDetailingGeneralTableTextFormat

Balloon

Text Format

swDetailingBalloonTextFormat

Annotations Font

UserPreference Tables For Document Properties

117

Lesson 3

API Fundamentals

no Pr t c e-R op e y o lea r d se ist rib ut e

Grid / Snap

Type

Enumeration / Values

Display Grid

Toggle

swGridDisplay

Dash

Toggle

swGridDisplayDashed

Automatic scaling

Toggle

swGridAutomaticScaling

Major grid spacing

Double

swGridMajorSpacing

Minor-lines per major

Int

swGridMinorLinesPerMajor

Snap points per minor

Int

swSnapPointsPerMinor

Do

Setting

118

UserPreference Tables For Document Properties

API Fundamentals

Lesson 3

no Pr t c e-R op e y o lea r d se ist rib ut e

Units

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

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

Do

Setting

UserPreference Tables For Document Properties

119

Lesson 3

API Fundamentals

no Pr t c e-R op e y o lea r d se ist rib ut e

Colors

Setting

Type

Enumeration / Values

Wireframe/HLR

Int

swDocumentColorWireFrame

Shading

Int

swDocumentColorShading

Int

swDocumentColorHidden

Int

swDocumentColorFeatBend

Int

swDocumentColorFeatBoss

Int

swDocumentColorFeatCavity

Int

swDocumentColorFeatChamfer

Int

swDocumentColorFeatCut

Int

swDocumentColorFeatLoftCut

Cut-Surface

Int

swDocumentColorFeatSurfCut

Cut-Sweep

Int

swDocumentColorFeatSweepCut

Weld Bead

Int

swDocumentColorFeatWeldBead

Extrude

Int

swDocumentColorFeatExtrude

Int

swDocumentColorFeatFillet

Int

swDocumentColorFeatHole

Library Feature

Int

swDocumentColorFeatLibrary

Loft

Int

swDocumentColorFeatLoft

MidSurface

Int

swDocumentColorFeatMidSurface

Pattern

Int

swDocumentColorFeatPattern

Surface

Int

swDocumentColorFeatRefSurface

Revolution

Int

swDocumentColorFeatRevolution

Shell

Int

swDocumentColorFeatShell

Derived Part

Int

swDocumentColorFeatDerivedPart

Sweep

Int

swDocumentColorFeatSweep

Thicken

Int

swDocumentColorFeatThicken

Rib

Int

swDocumentColorFeatRib

Dome

Int

swDocumentColorFeatDome

Hidden Bend Boss Cavity Chamfer Cut Cut-Loft

Fillet

Do

Hole

120

UserPreference Tables For Document Properties

API Fundamentals

Lesson 3

Int

swDocumentColorFeatForm

Shape Feature

Int

swDocumentColorFeatShape

Replace Face

Int

swDocumentColorFeatReplaceFace

Structural Member

Int

swDocumentColorFeatStructuralMember

Gusset

Int

swDocumentColorFeatGusset

End cap

Int

swDocumentColorFeatEndCap

Wrap

Int

swDocumentColorFeatWrap

Apply same color to wireframe, HLR, and shaded

Toggle

swColorsWireframeHLRShadedSame

Ignore feature colors

Toggle

swIgnoreFeatureColors

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

no Pr t c e-R op e y o lea r d se ist rib ut e

Form feature

Do

Material Properties

UserPreference Tables For Document Properties

121

Lesson 3

API Fundamentals

no Pr t c e-R op e y o lea r d se ist rib ut e

Image Quality

Setting

Type

Enumeration / Values

Shaded and draft quality HLR/HLV resolution

Int

swImageQualityShaded

Deviation

Double

swImageQualityShadedDeviation

Optimize edge length (higher quality but slower)

Toggle

swImageQualityUseHighQualityEdgeSize

Apply to all referenced part documents

Toggle

swImageQualityApplyToAllReferencedPartDoc

Save tessellation with part document

Toggle

swImageQualitySaveTesselationWithPartDoc

Wireframe and high quality HLR/HLV resolution

Int

swImageQualityWireframe Range 0 - 100

Setting

Type

Enumeration / Values

Transparency

Int

swPlaneDisplayTransparency Range = 0 - 100

Show Intersections

Toggle

swPlaneDisplayShowIntersections

Do

Plane Display

122

UserPreference Tables For Document Properties

API Fundamentals

Exercise 6: Change Multiple System Options

no Pr t c e-R op e y o lea r d se ist rib ut e

Exercise 6: Change Multiple System Options

Objective

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

I

APIs Used

SldWorks.SetUserPreferenceToggle SldWorks.SetUserPreferenceIntegerValue SldWorks.SetUserPreferenceStringValue

Procedure

1. 2. 3. 4.

Do

Skills Learned

Programming system options in SolidWorks.

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

123

Exercise 6:

API Fundamentals

Change Multiple System Options

Solution

Option Explicit Dim swApp As SldWorks.SldWorks Dim value As String

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

Sub main() Set swApp = Application.SldWorks value = "D:\Temp" swApp.SetUserPreferenceToggle swThumbnailGraphics, True swApp.SetUserPreferenceIntegerValue _ swEdgesHiddenEdgeDisplay, swEdgesHiddenEdgeDisplayDashed swApp.SetUserPreferenceIntegerValue _ swEdgesInContextEditTransparencyType, _ swInContextEditTransparencyForce swApp.SetUserPreferenceIntegerValue _ swEdgesInContextEditTransparency, 50 swApp.SetUserPreferenceStringValue swBackupDirectory, value End Sub

124

API Fundamentals

Exercise 7: Change Multiple Document Properties

no Pr t c e-R op e y o lea r d se ist rib ut e

Exercise 7: Change Multiple Document Properties

Objective

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 I

APIs Used

SldWorks.SetUserPreferenceDoubleValue SldWorks.SetUserPreferenceIntegerValue SldWorks.SetUserPreferenceStringValue

Procedure

1. 2. 3. 4.

Do

Skills Learned

Setting document properties in SolidWorks with the API.

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

125

Exercise 7:

API Fundamentals

Change Multiple Document Properties

Solution

Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

Sub main() Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc swModel.SetUserPreferenceIntegerValue _ swDetailingDimensionStandard, swDetailingStandardANSI swModel.SetUserPreferenceDoubleValue _ swDetailingArrowHeight, 0.15 * 0.0254 swModel.SetUserPreferenceDoubleValue _ swDetailingArrowWidth, 0.42 * 0.0254 swModel.SetUserPreferenceDoubleValue _ swDetailingArrowLength, 1.5 * 0.0254 swModel.SetUserPreferenceIntegerValue swUnitsLinear, swINCHES swModel.SetUserPreferenceIntegerValue _ swUnitsLinearDecimalPlaces, 3 End Sub

126

no Pr t c e-R op e y o lea r d se ist rib ut e

API Fundamentals

Do

Lesson 4 Automating Part Design

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

Design a macro around the part creation process.

I

Automate sketching entities.

I

Add dimensions to sketch entities.

I

Automatically create features such as extrudes and revolves.

I

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

127

Lesson 4

API Fundamentals

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

Automating Part Design

128

API Fundamentals

Lesson 4 Automating Part Design

Case Study: Automation Tool for Parts

no Pr t c e-R op e y o lea r d se ist rib ut e

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:

1

I

Material (aluminum or brass)

I

Profile (rectangular or circular)

I

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

Edit macro.

Open the macro PartAutomation.swp.

2

Store values to database and set units.

Do

Double-click the command button Build Part and enter the following lines of code:

Note

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

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.

Case Study: Automation Tool for Parts

129

Lesson 4

API Fundamentals

Automating Part Design

Setting Material

no Pr t c e-R op e y o lea r d se ist rib ut e

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

Do

3

130

Add code to set the material.

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

Case Study: Automation Tool for Parts

API Fundamentals

Lesson 4 Automating Part Design

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.

no Pr t c e-R op e y o lea r d se ist rib ut e

Creating the Sketch Rectangle

1. Create rectangle

2. Create offset

3. Add axis

ModelDoc2:: AddDimension2, AddVerticalDimension2 and AddHorizontalDimension2 are used to dimension sketch entities. A dimension is only added if an entity is selected. In this next section we will create the rectangle line by line, and dimension the sketch.

Selection on Creation

When you use the API to create any thing in a SolidWorks document, it will automatically be selected. In the next section of code notice that the first time a sketched line is created, the method call ModelDoc2::AddDimension2 immediately follows. By design, the API will automatically select and highlight each sketch entity when it is created. Because of this, no selection code needs to be written to add the dimension to the sketched line.

Do

Adding Dimensions

Note

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. A detailed review of the selection APIs are covered in Selection and Traversal Techniques on page 177.

Case Study: Automation Tool for Parts

131

Lesson 4

API Fundamentals

Automating Part Design

4

Add code to sketch and dimension a rectangle.

Add code to sketch and dimension the profiles.

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

swModel.InsertSketch2 False If optRectangular.Value = True Then txtRadius.enabled = False Dim Height As Double Dim Width As Double Height = CDbl(txtHeight.text) / 1000 Width = CDbl(txtWidth.text) / 1000 'Turn off dimension dialogs swApp.SetUserPreferenceToggle swInputDimValonCreate, False 'Create the first line in the profile swModel.CreateLine2 0.05, 0.05, 0, 0.05, 0.05 + Height, 0 'Add a dimension to the selected entity swModel.AddDimension2 0, 0.05 + Height / 2, 0 swModel.CreateLine2 0.05, 0.05 + Height, 0, 0.05 + Width, _ 0.05 + Height, 0 swModel.CreateLine2 0.05 + Width, 0.05 + Height, 0, _ 0.05 + Width, 0.05, 0 swModel.CreateLine2 0.05 + Width, 0.05, 0, 0.05, 0.05, 0 swModel.AddDimension2 0.05 + Width / 2, 0, 0 swModel.ClearSelection 'Select the origin swModel.Extension.SelectByID2 "", "EXTSKETCHPOINT", _ 0, 0, 0, False, 0, Nothing, 0 'Select an end point on the profile swModel.Extension.SelectByID2 "", "SKETCHPOINT", _ 0.05, 0.05, 0, True, 0, Nothing, 0 'Add a vertical dimension swModel.AddVerticalDimension2 0, 0.025, 0 swModel.ClearSelection 'Select the origin swModel.Extension.SelectByID2 "", "EXTSKETCHPOINT", _ 0, 0, 0, False, 0, Nothing, 0 'Select an end point on the profile swModel.Extension.SelectByID2 "", "SKETCHPOINT", _ 0.05, 0.05, 0, True, 0, Nothing, 0 'Add a horizontal dimension to fully constrain the sketch swModel.AddHorizontalDimension2 0.025, 0, 0 swModel.ClearSelection 'Select all four profile edges swModel.Extension.SelectByID2 "Line1", "SKETCHSEGMENT", _ 0, 0, 0, False, 0, Nothing, 0 swModel.Extension.SelectByID2 "Line2", "SKETCHSEGMENT", _ 0, 0, 0, True, 0, Nothing, 0 swModel.Extension.SelectByID2 "Line3", "SKETCHSEGMENT", _ 0, 0, 0, True, 0, Nothing, 0 swModel.Extension.SelectByID2 "Line4", "SKETCHSEGMENT", _ 0, 0, 0, True, 0, Nothing, 0 'Create the offset sketch profile from the selected edges swModel.SketchOffset2 0.002, 0, 1 swModel.ViewZoomtofit2 Else End if swModel.CreateLine2 _ (0, 0, 0, 0, 0.05, 0).ConstructionGeometry = True swModel.ViewZoomtofit2

132

Case Study: Automation Tool for Parts

API Fundamentals

Lesson 4 Automating Part Design

Creating the Sketch Circle

no Pr t c e-R op e y o lea r d se ist rib ut e

Call ModelDoc2::CreateCircleByRadius2 to create the second profile.

1. Create circle

5

2. Create offset

3. Use axis from previous step

Add code to sketch circle.

Creating the construction line is the same for the rectangle or the circle. Therefore, this call can fall outside the IF..Then statement. Else Dim Radius As Double Radius = CDbl(txtRadius.text) / 1000 swModel.CreateCircleByRadius2 _ 0.05 + Radius, 0.05 + Radius, 0, Radius swModel.SketchOffset2 0.002, 0, 1 swModel.ViewZoomtofit2 End If swModel.CreateLine2 _ (0, 0, 0, 0, 0.05, 0).ConstructionGeometry = True swModel.ViewZoomtofit2

Call FeatureManager::FeatureExtrusion to create the extrude feature.

Do

Creating Extruded Features

Case Study: Automation Tool for Parts

133

Lesson 4

API Fundamentals

Automating Part Design

6

Add code to create an extruded feature.

no Pr t c e-R op e y o lea r d se ist rib ut e

‘MACHINE OPERATION Dim swFeatMgr As SldWorks.FeatureManager If optExtrude.Value = True Then Dim Depth As Double Depth = CDbl(txtDepth.text) / 1000 Set swFeatMgr = swModel.FeatureManager swFeatMgr.FeatureExtrusion True, False, True, 0, 0, Depth, _ 0, False, False, False, False, 0, 0, 0, 0, 0, 0, _ False, False, False swModel.ViewZoomtofit2 End If

Enabling Contour Selection for the Extrusion

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.

Do

Call the SelectionManager::EnableContourSelection to put SolidWorks into contour selection mode. Then use ModelDocExtention::SelectByID2 to select the contours used to extrude or revolve the new feature. When finished, turn off contour selection.

134

Case Study: Automation Tool for Parts

API Fundamentals

Lesson 4 Automating Part Design

7

Add code to enable contour selection.

no Pr t c e-R op e y o lea r d se ist rib ut e

‘MACHINE OPERATION Dim swFeatMgr As SldWorks.FeatureManager If optExtrude.Value = True Then Dim Depth As Double Depth = CDbl(txtDepth.text) / 1000 Set swFeatMgr = swModel.FeatureManager If optRectangular.Value = True Then If chkContour1.Value = True Then swModel.SelectionManager.EnableContourSelection = 1 swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _ 0.05, 0.05, 0, True, 4, Nothing, 0 End If If chkContour2.Value = True Then swModel.SelectionManager.EnableContourSelection = 1 swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _ 0.05 - 0.002, 0.05, 0, True, 4, Nothing, 0 End If Else If chkContour1.Value = True Then swModel.SelectionManager.EnableContourSelection = 1 swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _ 0.05 + Radius, 0.05, 0, True, 4, Nothing, 0 End If If chkContour2.Value = True Then swModel.SelectionManager.EnableContourSelection = 1 swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _ 0.05 + Radius, 0.05 - 0.002, 0, True, 4, Nothing, 0 End If End If swFeatMgr.FeatureExtrusion True, False, True, 0, 0, Depth, _ 0, False, False, False, False, 0, 0, 0, 0, 0, 0, _ False, False, False swModel.SelectionManager.EnableContourSelection = 0 swModel.ViewZoomtofit2 End If

Call FeatureManager::FeatureRevolve to create the revolve feature.

Do

Creating Revolved Features

Case Study: Automation Tool for Parts

135

Lesson 4

API Fundamentals

Automating Part Design

8

Add code to create revolved feature.

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

‘MACHINE OPERATION Dim swFeatMgr As SldWorks.FeatureManager If optExtrude.Value = True Then Dim Depth As Double Depth = CDbl(txtDepth.text) / 1000 Set swFeatMgr = swModel.FeatureManager If optRectangular.Value = True Then If chkContour1.Value = True Then swModel.SelectionManager.EnableContourSelection = 1 swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _ 0.05, 0.05, 0, True, 4, Nothing, 0 End If If chkContour2.Value = True Then swModel.SelectionManager.EnableContourSelection = 1 swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _ 0.05 - 0.002, 0.05, 0, True, 4, Nothing, 0 End If Else If chkContour1.Value = True Then swModel.SelectionManager.EnableContourSelection = 1 swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _ 0.05 + Radius, 0.05, 0, True, 4, Nothing, 0 End If If chkContour2.Value = True Then swModel.SelectionManager.EnableContourSelection = 1 swModel.Extension.SelectByID2 "", "SKETCHCONTOUR", _ 0.05 + Radius, 0.05 - 0.002, 0, True, 4, Nothing, 0 End If End If swFeatMgr.FeatureExtrusion True, False, True, 0, 0, Depth, _ 0, False, False, False, False, 0, 0, 0, 0, 0, 0, _ False, False, False swModel.SelectionManager.EnableContourSelection = 0 swModel.ViewZoomtofit2 Else Dim Angle As Double Angle = CDbl(txtAngle.text * 3.14 / 180) Set swFeatMgr = swModel.FeatureManager swFeatMgr.FeatureRevolve Angle, True, 0, 0, 0, True, _ False, True End If

136

9

Save and run macro.

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

Case Study: Automation Tool for Parts

API Fundamentals

Lesson 4 Automating Part Design

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

no Pr t c e-R op e y o lea r d se ist rib ut e

NewDocument OpenDoc6 LoadFile2

Rebuild EditRebuild3 ForceRebuild3

Save3 SaveAs4 SaveBMP

Standard View Commands

Note

ShowNamedView2 "*Front", 1

ShowNamedView2 "*Top", 5

ShowNamedView2 "*Back", 2

ShowNamedView2 "*Bottom", 6

ShowNamedView2 "*Left", 3

ShowNamedView2 "*Isometric", 7

ShowNamedView2 "*Right", 4

ShowNamedView2 "*Normal To", 0

Also available through the API:

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

View Commands

ViewDisplayWireframe

ViewOrientationUndo

ViewDisplayHiddengreyed

Do

TranslateBy

ViewZoomtofit2

ViewDisplayHiddenremoved

ViewZoomTo2

HlrQuality = 1

ZoomByFactor

HlrQuality = 0

ViewZoomToSelection

ViewDisplayShaded

RotateAboutCenter

AddPerspective

Case Study: Automation Tool for Parts

137

Lesson 4

API Fundamentals

Automating Part Design

Sketch Commands Insert3DSketch2

GridOptions

SketchModifyFlip SketchModifyRotate SketchModifyScale SketchModifyTranslate

no Pr t c e-R op e y o lea r d se ist rib ut e

SelectByID2 SelectByRay

InsertSketch2

AutoSolveToggle

Sketch Tools Commands

SketchUseEdge2

CreateArc2

Sketch3DIntersections

CreateTangentArc2

InsertProjectedSketch2

Create3PointArc

SketchMirror

CreateCircle2 CreateCircleByRadius2

SketchFillet2

CreateEllipse2 CreateEllipticalArc2

SketchChamfer

SketchParabola

SketchOffset2

SketchSpline CreateSpline Insert3DSplineCurve

MakeStyledCurves

SketchPolygon

SketchTrim, 1

SketchRectangle

SketchTrim, 2

Do

CreateLine2

138

SketchRectangleAtAnyAngle

SplitOpenSegment SplitClosedSegment

CreatePoint2

CreateLinearSketchStepAndRepeat

CreateCenterLine CreateLine2.ConstructionGeometry

CreateCircularSketchStepAndRepeat

InsertSketchText

InsertSketchPicture

Case Study: Automation Tool for Parts

API Fundamentals

Lesson 4 Automating Part Design

Features Commands InsertDome

FeatureRevolve FeatureRevolveThin

InsertRip

FeatureCut FeatureCutThin

EditUnsuppress2

FeatureRevolveCut FeatureRevolveThinCut

EditUnsuppressDependent2

InsertProtrusionSwept InsertCutSwept

EditSuppress2

InsertProtrusionBlend InsertCutBlend

FeatureLinearPattern

FeatureFillet

FeatureCirularPattern

FeatureChamfer FeatureChamferType

MirrorFeature

InsertRib2

InsertRip

Scale

SplitBody

InsertFeatureShell InsertFeatureShellAddThickness

InsertCombineFeature

InsertMfDraft2

InsertDeleteBody

SimpleHole2

InsertMoveCopyBody

no Pr t c e-R op e y o lea r d se ist rib ut e

FeatureExtrusion FeatureExtrusionThin FeatureBoss

Sketch Relations Commands

GetConstraints

SketchAddConstraints

Autodimension

Do

AddDimension2 AddHorizontalDimension2 AddVerticalDimension2

Reference Geometry Commands CreatePlaneAtAngle3 CreatePlaneAtOffset3 CreatePlaneAtSurface3 CreatePlaneFixed2 CreatePlanePerCurveAndPassPoint3 CreatePlaneThru3Points3 CreatePlaneThruLineAndPt CreatePlaneThruPtParallelToPlane

Case Study: Automation Tool for Parts

InsertCoordinateSystem InsertAxis2

139

Lesson 4

API Fundamentals

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

Automating Part Design

140

Case Study: Automation Tool for Parts

API Fundamentals

Exercise 8: Automating the Part Creation Process

no Pr t c e-R op e y o lea r d se ist rib ut e

Exercise 8: Automating the Part Creation Process

Objective

To design your own part automation tool using the techniques and methods from the case study. The forms are prebuilt, but missing controls. Add these controls, and capture the user-entered values before launching the machine command.

The tool should set the material to Steel (density = 7.8 grams/cm3), and sketch a profile (L bracket) with adjustable height and width. It should also allow the user to extrude or revolve the profile as a thin feature (with adjustable depth or angle).

Skills Learned

I I

Do

APIs Used

Procedure

Automating sketch entities and dimensions Automating features and set user preferences.

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

1. 2. 3. 4. 5.

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

141

Exercise 8:

API Fundamentals

Automating the Part Creation Process

Solution

Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2 Dim swFeatMgr As SldWorks.FeatureManager

no Pr t c e-R op e y o lea r d se ist rib ut e

Private Sub cmdBuild_Click() Set swApp = Application.SldWorks Set swModel = swApp.NewPart swModel.SetUserPreferenceIntegerValue swConst.swUnitsLinear,_ swConst.swMETER If chkSteel.Value = True Then swModel.SetUserPreferenceDoubleValue _ swConst.swMaterialPropertyDensity, 7800 swModel.SetUserPreferenceStringValue _ swConst.swMaterialPropertyCrosshatchPattern, _ "ISO (Steel)" End If swModel.InsertSketch2 False

Do

Dim Height As Double Dim Width As Double Height = CDbl(txtHeight.text) / 1000 Width = CDbl(txtWidth.text) / 1000 swApp.SetUserPreferenceToggle swConst.swInputDimValOnCreate,_ False swModel.CreateLine2 0.01, 0.01, 0, 0.01, 0.01 + Height, 0 swModel.ViewZoomtofit2 swModel.AddDimension2 0, 0.01 + Height / 2, 0 swModel.CreateLine2 0.01, 0.01, 0, 0.01 + Width, 0.01, 0 swModel.ViewZoomtofit2 swModel.AddDimension2 0.01 + Width / 2, 0, 0 swModel.CreateLine2(0, 0, 0, 0, 0.01, 0). _ ConstructionGeometry = True swModel.ClearSelection swModel.ViewZoomtofit2

142

Dim Thick As Double Thick = CDbl(txtThick.text) / 1000 If optExtrude.Value = True Then Dim Depth As Double Depth = CDbl(txtDepth.text) / 1000 Set swFeatMgr = swModel.FeatureManager swFeatMgr.FeatureExtrusionThin True, False, True, 0, 0, _ Depth, 0, False, False, False, False, 0, 0, False, _ False, False, False, False, Thick, 0, 0, 0, 0, False, _ False, False, False swModel.ViewZoomtofit2 Else Dim Angle As Double Angle = CDbl(txtAngle.text * 3.14 / 180) Set swFeatMgr = swModel.FeatureManager swFeatMgr.FeatureRevolveThin Angle, 0, 0, 0, Thick, 0, 0, _ 1, 1, 1 End If swModel.ShowNamedView2 "Isometric", 7 swModel.ViewZoomtofit2 End Sub

no Pr t c e-R op e y o lea r d se ist rib ut e

API Fundamentals

Do

Lesson 5 Assembly Automation

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

Open components invisible to the user.

I

Understand the use of safe entities.

I

Traverse all the loops in a selected face.

I

Create and use collections of SolidWorks objects.

I

Determine if a face is cylindrical.

I

Use the MathUtility object.

I

Multiply with transforms.

I

Add components to specific locations and add mates.

143

Lesson 5

API Fundamentals

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

Assembly Automation

144

API Fundamentals

Lesson 5 Assembly Automation

This macro works correctly for all configurations of the chassis.

Do

Note

This macro is designed to explore the various API calls associated with adding components to an assembly. It demonstrates positioning, mating, face traversal, creating object collections and the use of safe entities.

no Pr t c e-R op e y o lea r d se ist rib ut e

Case Study: Automation Tool for Assemblies

This macro also works for any face with a hole.

Case Study: Automation Tool for Assemblies

145

Lesson 5

API Fundamentals

Assembly Automation

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.

no Pr t c e-R op e y o lea r d se ist rib ut e

I I I I I I

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

Do

Tip

146

To navigate quickly to the UserForm_Activate event, double-click on an empty grey area on the user form. This will automatically display the form’s code and set the cursor on the first line of code in the event handler.

Case Study: Automation Tool for Assemblies

API Fundamentals

Lesson 5 Assembly Automation

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

no Pr t c e-R op e y o lea r d se ist rib ut e

I

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

I I

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

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.

Do

Question

Case Study: Automation Tool for Assemblies

147

Lesson 5

API Fundamentals

Assembly Automation

Transforms

no Pr t c e-R op e y o lea r d se ist rib ut e

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.

MathUtility::CreateTransform

retval = MathUtility.CreateTransform (ArrayData)

Return: Input:

retval

Pointer to the newly created MathTransform object.

ArrayData

Sixteen components of the transform.

Do

The Transformation Matrix

Tip

148

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

The first nine are elements of a 3x3 rotational sub-matrix. The next three define a translation vector. The next one is a scaling factor. The last three elements are unused in this context.

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

Case Study: Automation Tool for Assemblies

API Fundamentals

Lesson 5 Assembly Automation

4

Add code to establish a transform.

Find the transform of the chassis component. I I I

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

no Pr t c e-R op e y o lea r d se ist rib ut e

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

Activating Documents

Call the SldWorks::ActivateDoc2 method to activate an inactive document in the SolidWorks session. The file becomes the active document in the SolidWorks user interface, and the method returns a pointer to that document object.

SldWorks::ActivateDoc2

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

Return: Input: Input:

Output:

retval

Pointer to a Dispatch object, the document.

Name

Name of document to activate.

Silent

TRUE

Errors

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

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

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.

Do

Invisible Documents

Case Study: Automation Tool for Assemblies

149

Lesson 5

API Fundamentals

Assembly Automation

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

Return:

void

There is no return value.

Input:

visible

True

no Pr t c e-R op e y o lea r d se ist rib ut e

Input:

to show this document type, False to hide it.

type

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

5

Open component.

Add the following code to the OpenComponentModelToAddToAssembly sub program. The following code: I I I

Turns off visibility for any newly opened documents. Opens the 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, warnings Set swModel = swApp.ActivateDoc2 (AssemblyTitle, True, errors) Set swAssy = swModel End Sub

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.

Do

Object Collections

This sub program traverses all the loops on the selected face. If the loop is an inner loop then it returns an array of all of the edges belonging to that loop. Then one by one, it checks each edge to see if it is a complete circle. If it is, it then adds the edge object and it's corresponding curve object to their appropriate collections. These objects are used later to reselect faces for mating the control knob, and to determine the position in the assembly that the knob components will be added.

150

Case Study: Automation Tool for Assemblies

API Fundamentals

Lesson 5 Assembly Automation

Here is the pseudo code for the EstablishCircularCurveAndEdgeCollections sub program: I I I I

no Pr t c e-R op e y o lea r d se ist rib ut e

I

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

I

6

Establish curve and edge collections.

Add the following code to the EstablishCircularCurveAndEdgeCollections sub program.

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

Do

Establishing the Face Collection

The edge and curve collections are now established. A collection must also be created to maintain pointers to the cylindrical faces that are bounded by the circular edges. These faces are also needed later on to help establish the concentric mate needed to mate the control button concentrically to the hole in the chassis.

Case Study: Automation Tool for Assemblies

151

Lesson 5

API Fundamentals

Assembly Automation

The EstablishCylindricalFaceCollection sub program gathers the cylindrical faces of the control knob holes and adds them to the SafeCylindricalFaceCollection.

no Pr t c e-R op e y o lea r d se ist rib ut e

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

I I I I I I

Getting Adjacent Faces

Use Edge::GetTwoAdjacentFaces to get faces sharing the circular edge. Declare a surface pointer for the first face. Declare another surface pointer for the second face. Set the first and second surface pointers. Determine which one is the cylindrical surface. When the cylindrical face is found, add it to the face collection.

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

Edge::GetTwoAdjacentFaces

Edge.GetTwoAdjacentFaces (Face1, Face2)

Output:

Face1

Pointer to the first adjacent face.

Output:

Face2

Pointer to the second adjacent face.

7

Establish face collection.

Do

Add the following code to the EstablishCylindricalFaceCollection sub program.

152

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

Case Study: Automation Tool for Assemblies

API Fundamentals

Lesson 5 Assembly Automation

no Pr t c e-R op e y o lea r d se ist rib ut e

Else Set swTempSurf = swSurface2 Set swEntity = swFaces(1) End If If Not swTempSurf Is Nothing Then 'When the cylindrical Face is found.... Dim swSafeFace As SldWorks.entity Set swSafeFace = swEntity.GetSafeEntity SafeCylindricalFaceCollection.Add swSafeFace End If Next i End Sub

Establishing the Points Collection

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

Getting Curve Parameters

The method Curve::CircleParams is used to get the parameters of a circular curve. The first three values of the returned array are the center point of the curve.

Curve::CircleParams

retval = Curve.CircleParams ( )

Return:

retval

SafeArray of seven doubles: center.x, center.y, center.z, axis.x, axis.y, axis.z and radius

Do

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

Important!

When building the collection of center points, use the MathPoint object from the MathUtility class. This object has a method for multiplying the point location by the transform of the target component in the assembly.

Remember that the points that are retrieved from the center location of the circular edges are not in assembly space. These edges belong to the chassis part model. The center points of these edges are relative to the models origin, not the assembly origin.

Case Study: Automation Tool for Assemblies

153

Lesson 5

API Fundamentals

Assembly Automation

The pseudo code for the EstablishPointsCollection is: I I I I

no Pr t c e-R op e y o lea r d se ist rib ut e

I

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.

I

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 Variant circleParams = CircularCurveCollection(i).circleParams Dim arrayData(2) As Double Dim swMathPoint As SldWorks.mathPoint arrayData(0) = circleParams(0) arrayData(1) = circleParams(1) arrayData(2) = circleParams(2) Set swMathPoint = swMathUtility.CreatePoint(arrayData) Set swMathPoint = swMathPoint. _ MultiplyTransform(swCompTransform) PointCollection.Add swMathPoint Next i End Sub

Adding and Mating the Knobs to the Chassis

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

Do

I I I I I I I

154

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

Case Study: Automation Tool for Assemblies

API Fundamentals

Lesson 5 Assembly Automation

Adding Components

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

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

Pointer to dispatch object for the added component.

Input:

CompName

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

Input Input: Input: Input:

no Pr t c e-R op e y o lea r d se ist rib ut e

Return:

ConfigName X

X coordinate of the component center.

Y

Y coordinate of the component center.

Z

Z coordinate of the component cente.r

Adding Mates

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

AssemblyDoc::AddMate

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

swMateCOINCIDENT swMateCONCENTRIC swMatePERPENDICULAR swMatePARALLEL swMateTANGENT swMateDISTANCE swMateANGLE swMateUNKNOWN

Align

swMateAlignALIGNED swMateAlignANTI_ALIGNED swMateAlignCLOSEST

Flip

TRUE

Input:

Dist

Distance value used with swMateDISTANCE mate type.

Input:

Angle

Angle value used with swMateANGLE mate type.

Input:

Input:

Do

Input:

Case Study: Automation Tool for Assemblies

to flip the component, FALSE otherwise.

155

Lesson 5

API Fundamentals

Assembly Automation

9

Add a knob to the assembly and mate it.

Add the following code to the AddComponentsToAssembly sub program.

no Pr t c e-R op e y o lea r d se ist rib ut e

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

10 Destroy all collections and variables.

Do

Review the following code in the Finalize sub program. This code cleans up all the variables and resets the document visibility setting. By setting the collections to nothing, this code can be run on another selected face in the assembly without having to restart the macro. Public Sub Finalize() swApp.DocumentVisible True, swDocPART Set swAssy = Nothing Set CircularCurveCollection = Nothing Set CircularEdgeCollection = Nothing Set SafeCylindricalFaceCollection = Nothing Set swModel = Nothing Set PointCollection = Nothing Set swSelFace = Nothing Set swSelMgr = Nothing Set swApp = Nothing Me.Hide End Sub

11 Save and run macro. 12 Exit macro.

156

Case Study: Automation Tool for Assemblies

API Fundamentals

Exercise 9: Adding Components

Exercise 9: Adding Components

no Pr t c e-R op e y o lea r d se ist rib ut e

Correct positions

Incorrect component positions

Objective

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

Skills Learned

Procedure

I

Debugging transforms.

I

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

1. Open the assembly Transforms.sldasm. 2. Open the macro Transforms.swp 3. Add breakpoint to the following line.

Do

Call AddcomponentsToAssembly("control knob.SLDPRT")

4. Debug the macro and step through the code line by line to understand it. 5. Delete control knobs when finished and return to macro. 6. Comment out the following lines: Set swMathPoint = swMathPoint.MultiplyTransform _ (swCompTransform) swAssy.AddMate swMateCOINCIDENT, 0, False, 0, 0 swAssy.AddMate swMateCONCENTRIC, 1, False, 0, 0

7. Save the macro and debug it again to see why the transformations are important when adding components to an assembly.

157

Exercise 9:

API Fundamentals

Adding Components

Private Sub cmdAddComponentsAndMate_Click() Set swSelFace = swSelMgr.GetSelectedObject3(1) Dim swEntity As SldWorks.entity Set swEntity = swSelFace Set swSafeSelFace = swEntity.GetSafeEntity If Not swSelFace Is Nothing Then Else MsgBox ("You did not select a face.") Exit Sub End If Call EstablishTargetComponentsTransform Call OpenComponentModelToAddToAssembly("control knob.SLDPRT") Call EstablishCircularCurveAndEdgeCollections Call EstablishCylindricalFaceCollection Call EstablishPointsCollection ’Step 3 - Add breakpoint here. ’ Call AddcomponentsToAssembly("control knob.SLDPRT") Call Finalize End Sub

no Pr t c e-R op e y o lea r d se ist rib ut e

Solution

Do

Public Sub EstablishPointsCollection() For i = 1 To CircularCurveCollection.Count() Dim circleParams As Variant circleParams = CircularCurveCollection(i).circleParams Dim arrayData(2) As Double Dim swMathPoint As SldWorks.mathPoint arrayData(0) = circleParams(0) arrayData(1) = circleParams(1) arrayData(2) = circleParams(2) Set swMathPoint = swMathUtility.CreatePoint(arrayData) ’Step 6 - Comment the next line. ’ Set swMathPoint = swMathPoint.MultiplyTransform _ (swCompTransform) PointCollection.Add swMathPoint Next i End Sub

158

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

no Pr t c e-R op e y o lea r d se ist rib ut e

API Fundamentals

Lesson 6 Drawing Automation

Do

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

Design a macro to automate drawing creation.

I

Create a drawing with multiple sheets based on an assembly with multiple configurations.

I

Insert drawing views on each sheet in the drawing.

I

Automatically insert model annotations and dimensions.

I

Automatically save drawings in different file formats.

159

Lesson 6

API Fundamentals

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

Drawing Automation

160

API Fundamentals

Lesson 6 Drawing Automation

Case Study: Automating Drawing Creation

no Pr t c e-R op e y o lea r d se ist rib ut e

This macro is designed to explore API calls associated with creating drawings. It automates the production of new drawing sheets and names each sheet after a specific configuration. It also imports model dimensions and annotations.

With Cut

Without Cut

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.

Do

Early bind to SldWorks and connect to the active model. Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2 Sub main() Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc End Sub

3

Prompt user for projection type.

Use the intrinsic VBA MsgBox function to prompt the user for the projection type. Dim Response As Integer Dim ThirdAngle As Boolean Sub main() Response = MsgBox("Create third angle projection?", vbYesNo) If Response = vbYes Then ThirdAngle = True Else ThirdAngle = False End If

Case Study: Automating Drawing Creation

161

Lesson 6

API Fundamentals

Drawing Automation

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.

no Pr t c e-R op e y o lea r d se ist rib ut e

Const TemplateName As String = “C:\SolidWorks 2006 Training Files\API Fundamentals\Templates\APIDrawing.drwdot” Const PaperSize As Long = swConst.swDwgPaperA1size Const ScaleNum As Double = 1 Const ScaleDenom As Double = 2 Dim Dim Dim Dim

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

Sub main() Response = MsgBox("Create third angle projection?", vbYesNo) If Response = vbYes Then ThirdAngle = True Else ThirdAngle = False End If

5

Create new drawing.

Add the code to create a new drawing document. Dim Dim Dim Dim Dim

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

Do

Sub main() Response = MsgBox("Create third angle projection?", vbYesNo) If Response = vbYes Then ThirdAngle = True Else ThirdAngle = False End If

Note

162

Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc Set swDraw = swApp.NewDocument(TemplateName, PaperSize, _ 0#, 0#) End Sub

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

Case Study: Automating Drawing Creation

API Fundamentals

Lesson 6 Drawing Automation

6

Save and run the macro.

no Pr t c e-R op e y o lea r d se ist rib ut e

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

Getting Configuration Names

Use the ModelDoc2::GetConfigurationNames method to get a list of configuration names existing in this document.

ModelDoc2::GetConfigurationNames

retval = ModelDoc2.GetConfigurationNames ( )

Return:

retval

7

Safearray of strings containing the names of the configurations in this part.

Get list of configurations.

Do

Add variables that store the assembly configuration names. Then add code to set up a loop that traverses them. Dim ConfigNamesArray As Variant Dim ConfigName As Variant Dim i As Long Sub main() Response = MsgBox("Create third angle projection?", vbYesNo) If Response = vbYes Then ThirdAngle = True Else ThirdAngle = False End If Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc Set swDraw = swApp.NewDocument(TemplateName, PaperSize, _ 0#, 0#) ConfigNamesArray = swModel.GetConfigurationNames For i = 0 To UBound(ConfigNamesArray) ConfigName = ConfigNamesArray(i) Next i End Sub

Case Study: Automating Drawing Creation

163

Lesson 6

API Fundamentals

Drawing Automation

Creating Sheets

Call DrawingDoc::NewSheet3 to create new drawing sheets.

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

Return:

retval

TRUE

Input:

Name

Name of the new sheet.

PaperSize

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

TemplateIn

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

Scale1

Scale numerator.

Scale2

Scale denominator.

Input:

Input:

Do

Input:

no Pr t c e-R op e y o lea r d se ist rib ut e

Input:

if successful, FALSE if not.

Input:

FirstAngle

TRUE

Input:

TemplateName

Name of custom template with full directory path if templateIn is set to swDwgTemplateCustom.

Input:

Width

Paper width if templateIn is set to swDwgTemplateNone or swDwgPapersUserDefined.

Input:

Height

Paper height if templateIn is set to swDwgTemplateNone or swDwgPapersUserDefined.

Input:

PropertyViewName

Name of the view containing the model to get custom property values from.

164

for first angle projection, FALSE otherwise.

Case Study: Automating Drawing Creation

API Fundamentals

Lesson 6 Drawing Automation

8

Add new variables.

Add some more variables that are used for creating the new sheets on the drawing.

no Pr t c e-R op e y o lea r d se ist rib ut e

Const TemplateName As String = “C:\SolidWorks 2006 Training Files\API Fundamentals\Templates\APIDrawing.drwdot” Const TemplateSize As Long = swConst.swDwgTemplateA1size Const PaperSize As Long = swConst.swDwgPaperA1size Const ScaleNum As Double = 1# Const ScaleDenom As Double = 2# Dim Dim Dim Dim Dim Dim Dim Dim Dim

9

swApp As SldWorks.SldWorks swModel As SldWorks.ModelDoc2 Response As Integer ThirdAngle As Boolean swDraw As SldWorks.DrawingDoc ConfigNamesArray As Variant ConfigName As Variant i As Long retval As Boolean

Add the code to create the new drawing sheets.

For i = 0 To UBound(ConfigNamesArray) ConfigName = ConfigNamesArray(i) retval = swDraw.NewSheet3(ConfigName, TemplateSize, _ PaperSize, ScaleNum, ScaleDenom, Not ThirdAngle, "", _ 0#, 0#, "") Next i End Sub

10 Run the code and examine the drawing.

Notice that new tabs are created for each new drawing sheet.

Do

Close the drawing without saving it.

Case Study: Automating Drawing Creation

165

Lesson 6

API Fundamentals

Drawing Automation

Creating Views

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

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

DrawingDoc::Create3rdAngleViews2

Return: Input: Tip

no Pr t c e-R op e y o lea r d se ist rib ut e

retval = DrawingDoc.Create3rdAngleViews2 (modelName) retval

TRUE

modelName

Name of the document to create views from.

if successful, FALSE if not.

There are two API methods that could be used to pass the name of the document to the first parameter of this method. ModelDoc2::GetTitle, and ModelDoc2::GetFullPathName. The latter is the better choice. Depending on what operating system this macro runs, ModelDoc2::GetTitle may not always return the extension part of the file name. If the extension part of the file name is not found, DrawingDoc::Create1stAngleViews2 will fail.

11 Insert standard views.

Add the code to create the drawing views. Run the macro.

Do

Examine the drawing views and then close it when finished.

166

Sub main() Response = MsgBox("Create third angle projection?", vbYesNo) If Response = vbYes Then ThirdAngle = True Else ThirdAngle = False End If Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc Set swDraw = swApp.NewDocument(TemplateName, PaperSize, _ 0#, 0#) ConfigNamesArray = swModel.GetConfigurationNames For i = 0 To UBound(ConfigNamesArray) ConfigName = ConfigNamesArray(i) retval = swDraw.NewSheet3(ConfigName, TemplateSize, _ PaperSize, ScaleNum, ScaleDenom, Not ThirdAngle, "", _ 0#, 0#, "") If ThirdAngle = True Then retval = swDraw.Create3rdAngleViews2(swModel.GetPathName) Else retval = swDraw.Create1stAngleViews2(swModel.GetPathName) End If Next i End Sub

Case Study: Automating Drawing Creation

API Fundamentals

Lesson 6

no Pr t c e-R op e y o lea r d se ist rib ut e

Drawing Automation

Running the macro produces the projection views automatically.

Inserting Annotations

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

DrawingDoc::InsertModelAnnotations3

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

Return: Input:

Input

VARIANT of type SafeArray of inserted Annotation objects

option

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

types

use values from swInsertAnnotations_e

allViews

TRUE = inserts the annotations for all views in the drawing FALSE = inserts annotation only in the selected view

Do

Input:

Variant

Input:

duplicateDims

TRUE to insert duplicate dimensions, FALSE to eliminate duplicate dimensions

Input

hiddenFeatureDims

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

Input

usePlacementInSketch

TRUE to insert dimensions as they were placed in sketch, FALSE to not

Input

Case Study: Automating Drawing Creation

167

Lesson 6

API Fundamentals

Drawing Automation

12 Insert dimensions and notes.

Add the code to insert the dimensions and annotations from the underlying assembly model.

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

Sub main() Response = MsgBox("Create third angle projection?", vbYesNo) If Response = vbYes Then ThirdAngle = True Else ThirdAngle = False End If Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc Set swDraw = swApp.NewDocument(TemplateName, PaperSize, _ 0#, 0#) ConfigNamesArray = swModel.GetConfigurationNames For i = 0 To UBound(ConfigNamesArray) ConfigName = ConfigNamesArray(i) retval = swDraw.NewSheet3(ConfigName, TemplateSize, _ PaperSize, ScaleNum, ScaleDenom, Not ThirdAngle, "", _ 0#, 0#, "") If ThirdAngle = True Then retval = swDraw.Create3rdAngleViews2(swModel.GetPathName) Else retval = swDraw.Create1stAngleViews2(swModel.GetPathName) End If swDraw.InsertModelAnnotations3 0, _ SwConst.swInsertDimensionsMarkedForDrawing + _ SwConst.swInsertNotes, True, True, True, False Next i End Sub

Running the macro inserts the annotations automatically.

168

Case Study: Automating Drawing Creation

API Fundamentals

Lesson 6 Drawing Automation

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.

no Pr t c e-R op e y o lea r d se ist rib ut e

Traversing Drawing Views

13 Traverse views and set configurations.

Do

Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim

swApp As SldWorks.SldWorks swModel As SldWorks.ModelDoc2 Response As Integer ThirdAngle As Boolean swDraw As SldWorks.DrawingDoc ConfigNamesArray As Variant ConfigName As Variant i As Long retval As Boolean swView As SldWorks.view

Sub main() Response = MsgBox("Create third angle projection?", vbYesNo) If Response = vbYes Then ThirdAngle = True Else ThirdAngle = False End If Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc Set swDraw = swApp.NewDocument(TemplateName, PaperSize, _ 0#, 0#) ConfigNamesArray = swModel.GetConfigurationNames For i = 0 To UBound(ConfigNamesArray) ConfigName = ConfigNamesArray(i) retval = swDraw.NewSheet3(ConfigName, TemplateSize, _ PaperSize, ScaleNum, ScaleDenom, Not ThirdAngle, "", _ 0#, 0#, "") If ThirdAngle = True Then retval = swDraw.Create3rdAngleViews2(swModel.GetPathName) Else retval = swDraw.Create1stAngleViews2(swModel.GetPathName) End If retval = swDraw.InsertModelAnnotations(0, False, _ swConst.swInsertDimensions + swConst.swInsertNotes, _ True) Set swView = swDraw.GetFirstView Do While Not swView Is Nothing swView.ReferencedConfiguration = ConfigName Set swView = swView.GetNextView Loop swDraw.ForceRebuild Next i End Sub

Case Study: Automating Drawing Creation

169

Lesson 6

API Fundamentals

Drawing Automation

Saving Drawings in Different Formats

Another feature in this program is to save each drawing sheet in other file formats. Often it is necessary to send drawings to other systems for printing and viewing purposes. The ModelDoc2::SaveAs4 method is used to save the drawings in other file formats.

ModelDoc2::SaveAs4

Return: Input:

Input Input Output Output

Note

no Pr t c e-R op e y o lea r d se ist rib ut e

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

TRUE if the save is successful, FALSE if not

Name

New name of the document. The file extension indicates any conversion that should be performed (for example, Part1.igs to save to IGES)

Version

Format in which to save this document as defined in swSaveAsVersion_e

Options

Option indicating how to save the document as defined in swSaveAsOptions_e

Errors

Errors that caused the save to fail as defined in swFileSaveError_e

Warnings

Warnings or extra information generated during the save operation as defined in swFileSaveWarning_e

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.

Do

Navigate to the variable declarations and add the following code. Dim Dim Dim Dim Dim Dim Dim Dim Dim

swApp As SldWorks.SldWorks swModel As SldWorks.ModelDoc2 Response As Integer ThirdAngle As Boolean swDraw As SldWorks.DrawingDoc ConfigNamesArray As Variant ConfigName As Variant i As Long retval As Boolean

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

170

Case Study: Automating Drawing Creation

API Fundamentals

Lesson 6 Drawing Automation

15 Save the drawing sheets in different file formats.

Add the following code to export the drawings.

no Pr t c e-R op e y o lea r d se ist rib ut e

For i = 0 To UBound(ConfigNamesArray) ConfigName = ConfigNamesArray(i) retval = swDraw.NewSheet3(ConfigName, TemplateSize, _ PaperSize, ScaleNum, ScaleDenom, Not ThirdAngle, "", _ 0#, 0#, "") If ThirdAngle = True Then retval = swDraw.Create3rdAngleViews2(swModel.GetPathName) Else retval = swDraw.Create1stAngleViews2(swModel.GetPathName) End If retval = swDraw.InsertModelAnnotations(0, False, _ swConst.swInsertDimensions + swConst.swInsertNotes, _ True) Set swView = swDraw.GetFirstView Do While Not swView Is Nothing swView.ReferencedConfiguration = ConfigName Set swView = swView.GetNextView Loop swDraw.ForceRebuild swDraw.SaveAs4 SaveAsPath & ConfigName & ".DXF", _ 0, 0, errors, warnings swDraw.SaveAs4 SaveAsPath & ConfigName & ".DWG", _ 0, 0, errors, warnings swDraw.SaveAs4 SaveAsPath & ConfigName & ".JPG", _ 0, 0, errors, warnings swDraw.SaveAs4 SaveAsPath & ConfigName & ".TIF", _ 0, 0, errors, warnings Next i

16 Save and run macro.

Return to VBA when finished. Examine the drawing sheets.

Do

Also navigate to the export directory and open the files that were saved with the SaveAs4 method.

Configuration = “Cut”

Configuration = “No Cut”

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

Case Study: Automating Drawing Creation

171

Lesson 6

API Fundamentals

Drawing Automation

Drawing Commands CreateAuxiliaryViewAt3

CreateDetailViewAt3

CreateBreakoutSection

CreateSectionView

UpdateViewDisplayGeometry

CreateSectionViewAt4

InsertHatchedFace

no Pr t c e-R op e y o lea r d se ist rib ut e

Create1stAngleViews Create3rdAngleViews

CreateDrawViewFromModelView

Annotation Commands CreateText2 InsertNote

InsertCenterMark2

InsertSurfaceFinishSymbol2

InsertCenterLine

NewGtol

AddHoleCallout2

InsertBOMBalloon2

InsertCosmeticThread ShowCosmeticThread HideCosmeticThread

InsertDatumTargetSymbol

InsertStackedBalloon

InsertWeldSymbol

InsertMultiJogLeader

InsertBlock

InsertDowelSymbol

InsertModelAnnotations InsertModelDimensions

Do

Layer Commands CreateLayer ChangeComponentLayer SetCurrentLayer

Line Format Commands SetLineColor

HideEdge

SetLineWidth

ShowEdge

SetLineStyle

172

Case Study: Automating Drawing Creation

API Fundamentals

Exercise 10: Drawing Automation

Exercise 10: Drawing Automation

Objective Write a drawing automation macro using the techniques and methods from the case study.

no Pr t c e-R op e y o lea r d se ist rib ut e

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

Do

APIs Used

I

Automating drawing and annotation commands.

I

Working with multiple configurations in drawing views.

SldWorks.NewDocument ModelDoc2.GetConfigurationNames DrawingDoc.NewSheet3 DrawingDoc.Create1stAngleViews2 DrawingDoc.Create3rdAngleViews2 DrawingDoc.CreateDrawViewFromModelView DrawingDoc.ViewDisplayShaded DrawingDoc.InsertModelAnnoatations DrawingDoc.GetFirstView View.ReferencedConfiguration DrawingDoc.GetNextView DrawingDoc.ForceRebuild ---- Challenge #1 ---DrawDoc.ActivateSheet DrawDoc.GetCurrentSheet Sheet.SetName ---- Challenge #2 ---ModelDoc2.SaveAs4

Procedure

1. 2. 3. 4.

Open AutomationDrawings.sldasm. Open AutomationDrawings.swp. Use the APIs listed above to automate the drawing creation. Save and run macro.

173

Exercise 10:

API Fundamentals

Drawing Automation

Solution

Const TemplateName As String = "C:\SolidWorks 2006 Training Files\API Fundamentals\Templates\APIDrawing.drwdot" Const TemplateSize As Long = swConst.swDwgTemplateBsize Const PaperSize As Long = swConst.swDwgPaperBsize Const ScaleNum As Double = 1# Const ScaleDenom As Double = 2# swApp As SldWorks.SldWorks swModel As SldWorks.ModelDoc2 Response As Integer ThirdAngle As Boolean swDraw As SldWorks.DrawingDoc ConfigNamesArray As Variant ConfigName As Variant i As Long retval As Boolean swView As SldWorks.view

no Pr t c e-R op e y o lea r d se ist rib ut e

Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim

Sub main() Response = MsgBox("Create third angle projection?", vbYesNo) If Response = vbYes Then ThirdAngle = True Else ThirdAngle = False End If

Do

Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc Set swDraw = swApp.NewDocument(TemplateName, PaperSize, _ 0#, 0#) ConfigNamesArray = swModel.GetConfigurationNames

174

Dim isFirstSheet As Boolean isFirstSheet = True For i = 0 To UBound(ConfigNamesArray) ConfigName = ConfigNamesArray(i) If isFirstSheet = True Then swDraw.ActivateSheet "Sheet1" Dim swSheet As Sheet Set swSheet = swDraw.GetCurrentSheet swSheet.SetName ConfigName Else retval = swDraw.NewSheet3(ConfigName, TemplateSize, _ PaperSize, ScaleNum, ScaleDenom, Not ThirdAngle, "", _ 0#, 0#, "") End If isFirstSheet = False If ThirdAngle = True Then retval = swDraw.Create3rdAngleViews2(swModel.GetPathName) Else retval = swDraw.Create1stAngleViews2(swModel.GetPathName) End If swDraw.CreateDrawViewFromModelView swModel.GetPathName, _ "*Isometric", 0.2635088599471, 0.1934578136726, 0 swDraw.ViewDisplayShaded retval = swDraw.InsertModelAnnotations(0, False, _ swConst.swInsertDimensions + swConst.swInsertNotes, _ True)

API Fundamentals

Exercise 10: Drawing Automation

Set swView = swDraw.GetFirstView Do While Not swView Is Nothing swView.ReferencedConfiguration = ConfigName Set swView = swView.GetNextView Loop swDraw.ForceRebuild

no Pr t c e-R op e y o lea r d se ist rib ut e

Const SaveAsPath As String = "C:\SolidWorks 2006 Training _ Files\API Fundamentals\" & ConfigName & ".DXF", 0, 0, _ & ConfigName & ".DWG", 0, 0, _ & ConfigName & ".JPG", 0, 0, _ & ConfigName & ".TIF", 0, 0, _

Do

swDraw.SaveAs4 SaveAsPath errors, warnings swDraw.SaveAs4 SaveAsPath errors, warnings swDraw.SaveAs4 SaveAsPath errors, warnings swDraw.SaveAs4 SaveAsPath errors, warnings Next i End Sub

175

Exercise 10:

API Fundamentals

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

Drawing Automation

176

no Pr t c e-R op e y o lea r d se ist rib ut e

API Fundamentals

Do

Lesson 7 Selection and Traversal Techniques

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

Programmatically select objects.

I

Access selected objects using the SelectionManager.

I

Determine the type of a selected feature.

I

Extract and modify feature data.

I

Traverse features.

I

Traverse geometry.

I

Suppress features and set feature visibility.

I

Select features at a known FeatureManager position.

177

Lesson 7

API Fundamentals

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

Selection and Traversal Techniques

178

API Fundamentals

Lesson 7 Selection and Traversal Techniques

Case Study: Programming With a Selected Object

This macro demonstrates how to access and modify the data specific to certain features in a part file.

no Pr t c e-R op e y o lea r d se ist rib ut e

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.

Do

Add the following code

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

Case Study: Programming With a Selected Object

179

Lesson 7

API Fundamentals

Selection and Traversal Techniques

SelectionManager

no Pr t c e-R op e y o lea r d se ist rib ut e

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

Accessing the Selection Manager

To get an interface pointer to the SelectionManager object, you would use the ModelDoc2::SelectionManager property:

Dim SelMgr as SldWorks.SelectionMgr

Set SelMgr = ModelDoc2.SelectionManager.

ModelDoc2::SelectionManager

SelectionMgr = ModelDoc2.SelectionManager

Output:

SelectionMgr

Counting Selected Objects

Pointer a Dispatch object, the SelectionMgr object for this document

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

SelectionMgr::GetSelectedObjectCount

retval = SelectionMgr.GetSelectedObjectCount ( )

Return:

retval

3

Number of currently selected objects.

Add the following code.

Do

Connect to the Selection Manager and return the object count.

180

Private Sub cmdGenerate_Click() Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2 Dim swSelMgr As SldWorks.SelectionMgr Dim count As long Set swSelMgr = swModel.SelectionManager count = swSelMgr.GetSelectedObjectCount If count 1 Then swApp.SendMsgToUser2 "Please select only Extrude1.", _ swMbWarning, swMbOk Me.Hide Exit Sub End If End Sub

Case Study: Programming With a Selected Object

API Fundamentals

Lesson 7 Selection and Traversal Techniques

Accessing Selected Objects

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

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

Pointer a dispatch object.

Input:

AtIndex

Index position within the current list of selected items where AtIndex ranges:From 1 To

no Pr t c e-R op e y o lea r d se ist rib ut e

Return:

SelectionMgr::GetSelectObjectCount

Getting Selected Object Types

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

SelectionMgr::GetSelectedObjectType2

retval = SelectionMgr.GetSelectedObjectType2 (AtIndex)

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

retval

Object type. See API Help file for full list.

AtIndex

Index position within the current list of selected items where AtIndex ranges:From 1 To SelectionMgr::GetSelectObjectCount

Getting Feature Type Names

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

Feature::GetTypeName

retval = Feature.GetTypeName ( ) retval

Do

Return:

4

Feature type. See API Help file for full list.

Declare a feature variable.

Add the variable in the button click event. Private Sub cmdGenerate_Click() Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2 Dim swSelMgr As SldWorks.SelectionMgr Dim count As long Dim Feature As SldWorks.Feature Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc Set swSelMgr = swModel.SelectionManager count = swSelMgr.GetSelectedObjectCount

Case Study: Programming With a Selected Object

181

Lesson 7

API Fundamentals

Selection and Traversal Techniques

5

Return a pointer to the selected feature.

Scroll down and add the following code:

no Pr t c e-R op e y o lea r d se ist rib ut e

If count > 1 Then swApp.SendMsgToUser2 "Please select only Extrude1.", _ swMbWarning, swMbOk Me.Hide Exit Sub End If Set Feature = swSelMgr.GetSelectedObject5(count) If Not Feature.GetTypeName = “Extrusion” Then swApp.SendMsgToUser "Please select only Extrude1." Exit Sub End If End Sub

Feature Data Objects

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

Accessing the Feature Data Object

To return a pointer to the FeatureData object from a Feature object use the method Feature::GetDefinition.

Feature::GetDefinition

retval = Feature.GetDefintion ( )

Return:

retval

Do

Accessing Selections

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

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

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

Return:

accessGained

TRUE

if the selections were accessed successfully, if not.

FALSE

Input:

TopDoc

Top-level document.

Input:

Component

Component in which the feature is to be modified.

182

Case Study: Programming With a Selected Object

API Fundamentals

Lesson 7 Selection and Traversal Techniques

Releasing Selections

When using AccessSelections, the program must also make a corresponding call to ExtrudeFeatureData2::ReleaseSelectionAccess to restore the rollback state for cases when a feature is not modified. This method is only needed if the feature’s data is not modified.

no Pr t c e-R op e y o lea r d se ist rib ut e

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.

ExtrudeFeatureData2::ReleaseSelectionAccess

void ExtrudeFeatureData2.ReleaseSelectionAccess ( )

Return:

void

No return value.

6

Connect to a FeatureData object.

Add the following code to connect to the ExtrudeFeatureData object.

Do

Private Sub cmdGenerate_Click() Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2 Dim swSelMgr As SldWorks.SelectionMgr Dim count As long Dim Feature As SldWorks.Feature Dim ExtrudeFeatureData As Sldworks.ExtrudeFeatureData2 Dim retval As Boolean

Modifying Feature Data Properties

Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc Set swSelMgr = swModel.SelectionManager count = swSelMgr.GetSelectedObjectCount If count > 1 Then swApp.SendMsgToUser "Please select only Extrude1." Me.Hide Exit Sub End If Set Feature = swSelMgr.GetSelectedObject5(count) If Not Feature.GetTypeName = swTnExtrusion Then swApp.SendMsgToUser2 "Please select the Extrude1.", _ swMbWarning, swMbOk Exit Sub End If Set ExtrudeFeatureData = Feature.GetDefinition End Sub

One of the modifications for an extruded feature is setting the depth. First call ExtrudeFeatureData2::GetDepth to retrieve the existing depth value and then call ExtrudeFeatureData2::SetDepth to set a new value.

Case Study: Programming With a Selected Object

183

Lesson 7

API Fundamentals

Selection and Traversal Techniques

Modify the Object Definition

Finally, call Feature::ModifyDefinition to implement changes.

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

Return:

retval

TRUE

if the feature is updated successfully, FALSE if

Input: Input: Input:

no Pr t c e-R op e y o lea r d se ist rib ut e

not.

Definition

Dispatch pointer to the feature definition object.

TopDoc

Top-level document.

Component

Component for the feature.

7

Modify extrude depth.

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

Do

Private Sub cmdGenerate_Click() Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2 Dim swSelMgr As SldWorks.SelectionMgr Dim count As long Dim Feature As SldWorks.Feature Dim ExtrudeFeatureData As SldWorks.ExtrudeFeatureData2 Dim retval As Boolean Dim Depth As Double Dim Factor As Integer

184

Factor = CInt(txtDepth.Text) Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc Set swSelMgr = swModel.SelectionManager count = swSelMgr.GetSelectedObjectCount If count > 1 Then swApp.SendMsgToUser2 "Please select only Extrude1.", _ swMbWarning, swMbOk Me.Hide Exit Sub End If Set Feature = swSelMgr.GetSelectedObject5(count) If Not Feature.GetTypeName = swTnExtrusion Then swApp.SendMsgToUser2 "Please select the Extrude1.", _ swMbWarning, swMbOk Exit Sub End If Set ExtrudeFeatureData = Feature.GetDefinition Depth = ExtrudeFeatureData.GetDepth(True) ExtrudeFeatureData.SetDepth True, Depth * Factor retval = Feature.ModifyDefinition _ (ExtrudeFeatureData, swModel, Nothing) End Sub

Case Study: Programming With a Selected Object

API Fundamentals

Lesson 7 Selection and Traversal Techniques

8

Save and run the macro.

Select the Extrude1 feature from the FeatureManager and run the macro.

no Pr t c e-R op e y o lea r d se ist rib ut e

Enter 5 in the multiplication factor text box and click the Generate button.

Click it again and notice how the length of the extrusion keeps getting larger. Return to VBA when finished.

The SolidWorks BREP Model

In order to traverse geometry in SolidWorks, a programmer should understand the boundary representation (BREP) model that SolidWorks uses and how the API represents these objects. Two object types are used to represent the BREP model in the SolidWorks API. I I

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

Do

Highest Level Object

Lowest Level Object

The SolidWorks BREP Model

185

Lesson 7

API Fundamentals

Selection and Traversal Techniques

no Pr t c e-R op e y o lea r d se ist rib ut e

The Face2 object is a topology object. All of the Face2 object members return data about the topology of this object and nothing about the actual sizes of the surface that the face surrounds. To get the actual geometrical data from the face, a programmer would call the accessor Face2::GetSurface to return a pointer to the underlying surface. The programmer could then use a method such as Surface::GetBSurfaceParams or Surface::EvaluateAtPoint to discover the actual shape of this geometrical object. The objects in the diagram are listed in the order in which a programmer would have to connect to them. A programmer would first have to connect to a Body pointer before they could connect to a Face pointer. The Body object has an accessor method called Body::GetFirstFace that would return a Face pointer to the first face encountered on the body. The Face pointer has an accessor method called Face::GetNextFace that returns a pointer to the next face on the body. Combining these methods in a loop structure would allow the programmer to traverse all the faces on a body. This technique could be used on the other BREP objects as well.

Tip

Keep in mind that there are accessors on several of these BREP objects that will allow a programmer to side step some of the traversing. For instance, to traverse to the edges of a face, a programmer does not have to get a pointer to every object above it in the diagram before they can finally work with an edge pointer. The Face2 object has an accessor method named Face2::GetEdges. This method will return a list of all the edges on the face. Although all the objects above the edge object have a special purpose, there are times where it would not be necessary to access all these objects just to get a pointer to the edge of a face.

Do

Traversing Topology and Geometry

186

The SolidWorks BREP Model

API Fundamentals

Lesson 7 Selection and Traversal Techniques

Case Study: Body and Face Traversal

This next macro traverses all the faces of a part (single or multibody) and modifies the color properties on each face. It does not require the user to select a face in order to run. Face traversal techniques are important in many areas of API programming, including: I I

no Pr t c e-R op e y o lea r d se ist rib ut e

I

Selecting all types of faces (cylindrical, planar, etc.) on a body. Finding faces for adding mates. Finding edge, curve, and point information on faces. Automating multiple face modifications. Adding attributes to faces.

I I

1

Open an existing part and create a new macro.

Open the part BodyFaceTraversal.sldprt. Click

2

and name the macro BodyFaceTraversal.swp.

Add code to Sub Main.

Do

Connect to SolidWorks and the active document. Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2 Sub main() Set swApp = Application.SldWorks If Not swApp Is Nothing Then Set swModel = swApp.ActiveDoc If Not swModel Is Nothing Then End If Set swModel = Nothing End If Set swApp = Nothing End Sub

Case Study: Body and Face Traversal

187

Lesson 7

API Fundamentals

Selection and Traversal Techniques

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.

no Pr t c e-R op e y o lea r d se ist rib ut e

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

Returning a List of Body Pointers

PartDoc::GetBodies2 returns an array of all of the bodies in a part document. A loop can be used to traverse this returned list of bodies.

PartDoc::GetBodies2

retval = PartDoc.GetBodies2 (BodyType, VisibleOnly)

Return: Input:

SafeArray of dispatch pointers to the bodies.

BodyType

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

VisibleOnly

TRUE

gets only the visible bodies, FALSE gets all of the bodies in the part.

Do

Input:

retval

188

Case Study: Body and Face Traversal

API Fundamentals

Lesson 7 Selection and Traversal Techniques

4

Return the array body object pointers. Dim Dim Dim Dim

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

no Pr t c e-R op e y o lea r d se ist rib ut e

Sub main() Set swApp = Application.SldWorks If Not swApp Is Nothing Then Set swModel = swApp.ActiveDoc If Not swModel Is Nothing Then Set swPart = swModel If Not swPart Is Nothing Then retval = swPart.GetBodies2(swConst.swSolidBody, True) End If Set swPart = Nothing End If Set swModel = Nothing End If Set swApp = Nothing End Sub

5

Declare an indexer and a face pointer.

Dim Dim Dim Dim Dim Dim

Do

6

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

Program a loop to traverse the faces.

Sub main() Set swApp = Application.SldWorks If Not swApp Is Nothing Then Set swModel = swApp.ActiveDoc If Not swModel Is Nothing Then Set swPart = swModel If Not swPart Is Nothing Then retval = swPart.GetBodies2(swSolidBody, True) For i = 0 To UBound(retval) Set swFace = retval(i).GetFirstFace Do While Not swFace Is Nothing Loop Next i End If Set swPart = Nothing End If Set swModel = Nothing End If Set swApp = Nothing End Sub

Case Study: Body and Face Traversal

189

Lesson 7

API Fundamentals

Selection and Traversal Techniques

Face Material Properties

Use the property Face2::MaterialPropertyValues to get or set material properties for a face. Material properties are the colors and visual properties of a face. These properties can be overridden on every face in a model.

Face2::MaterialPropertyValues

no Pr t c e-R op e y o lea r d se ist rib ut e

MaterialPropertyValues = Face2.MaterialPropertyValues ‘ Gets property Face2.MaterialPropertyValues = MaterialPropertyValues ‘ Sets property

Output:

MaterialPropertyValues

SafeArray of material values on a face. The format of the return values is an array of doubles as follows: MaterialPropertyValues(0) MaterialPropertyValues(1) MaterialPropertyValues(2) MaterialPropertyValues(3) MaterialPropertyValues(4) MaterialPropertyValues(5) MaterialPropertyValues(6) MaterialPropertyValues(7) MaterialPropertyValues(8)

7

-

Red Green Blue Ambient Diffuse Specular Shininess Transparency Emission

Declare an array to hold face material properties. swApp As SldWorks.SldWorks swModel As SldWorks.ModelDoc2 swPart As SldWorks.PartDoc retval As Variant i As Integer swFace As SldWorks.face2 matProps(8) As Double

Do

Dim Dim Dim Dim Dim Dim Dim

190

Case Study: Body and Face Traversal

API Fundamentals

Lesson 7 Selection and Traversal Techniques

8

Set up an array of material properties.

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

no Pr t c e-R op e y o lea r d se ist rib ut e

Sub main() Set swApp = Application.SldWorks If Not swApp Is Nothing Then Set swModel = swApp.ActiveDoc If Not swModel Is Nothing Then Set swPart = swModel If Not swPart Is Nothing Then retval = swPart.GetBodies2(swConst.swSolidBody, True) For i = 0 To UBound(retval) Set swFace = retval(i).GetFirstFace matProps(0) = 1 matProps(1) = 0 matProps(2) = 0 matProps(3) = 1 matProps(4) = 1 matProps(5) = 0.3 matProps(6) = 0.3 matProps(7) = 0 matProps(8) = 0 Do While Not swFace Is Nothing swFace.MaterialPropertyValues = ((matProps)) Loop Next i End If Set swPart = Nothing End If Set swModel = Nothing End If Set swApp = Nothing End Sub

Notice when passing the material property values to the face in the code above, that the variant value matProps is enclosed in double parentheses. When passing an array in VBA to a SolidWorks method, it should be enclosed in double parentheses. If not, an exception could be thrown.

Important!

Do

9

Traverse remaining faces.

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

10 Save and run macro.

Return to VBA when finished.

Case Study: Body and Face Traversal

191

Lesson 7

API Fundamentals

Selection and Traversal Techniques

Case Study: Feature Manager Traversal

no Pr t c e-R op e y o lea r d se ist rib ut e

This macro traverses the FeatureManager design tree and retrieves each 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.

Do

Traversing the FeatureManager from the Top

To traverse the FeatureManager tree from the top, set up a loop. Before entering the loop, use the method ModelDoc2::FirstFeature to return a pointer to the first feature in the FeatureManager design tree.

ModelDoc2:FirstFeature retval = ModelDoc2.FirstFeature ( )

Return:

192

retval

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

Case Study: Feature Manager Traversal

API Fundamentals

Lesson 7 Selection and Traversal Techniques

Consecutive calls to Feature::GetNextFeature in this loop would continue the traversal Feature:GetNextFeature retval = Feature.GetNextFeature ( ) retval

Dispatch pointer to the next feature.

no Pr t c e-R op e y o lea r d se ist rib ut e

Return:

2

Add the feature traversal code.

Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2 Dim swFeature As SldWorks.feature

Sub main() Set swApp = Application.SldWorks If Not swApp Is Nothing Then Set swModel = swApp.ActiveDoc If Not swModel Is Nothing Then Set swFeature = swModel.FirstFeature While Not swFeature Is Nothing Set swFeature = swFeature.GetNextFeature Wend End If Set swModel = Nothing End If Set swApp = Nothing End Sub

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.

Do

Displaying Feature Names and Types

3

Retrieve and display feature information.

Declare some variables to store a feature name and type. Dim Dim Dim Dim Dim

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

Case Study: Feature Manager Traversal

193

Lesson 7

API Fundamentals

Selection and Traversal Techniques

4

Return the feature name and type to the user.

no Pr t c e-R op e y o lea r d se ist rib ut e

Sub main() Set swApp = Application.SldWorks If Not swApp Is Nothing Then Set swModel = swApp.ActiveDoc If Not swModel Is Nothing Then Set swFeature = swModel.FirstFeature While Not swFeature Is Nothing FeatName = swFeature.Name FeatType = swFeature.GetTypeName MsgBox "Feature screen name = " & FeatName & vbCrLf & _ "Feature type name = " & FeatType Set swFeature = swFeature.GetNextFeature Wend End If Set swModel = Nothing End If Set swApp = Nothing End Sub

5

Save and run the macro.

Return to VBA when finished.

Notice that sketch names are returned before their parent features. The Feature traversal returns the features in the chronological order that they were created in the model. Therefore Sketch1 would be displayed to the user before the Extrude1 feature.

Do

Note

Setting Feature Suppression

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

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

Return:

suppressSet

TRUE

if the suppression state was successfully set, if not.

FALSE

Input:

194

suppressState

swSuppressFeature swUnSuppressFeature swUnSuppressDependent

Case Study: Feature Manager Traversal

API Fundamentals

Lesson 7 Selection and Traversal Techniques

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.

no Pr t c e-R op e y o lea r d se ist rib ut e

Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2 Dim swFeature As SldWorks.feature Dim FeatName As String Dim FeatType As String Dim swSubFeature As SldWorks.feature Dim SubFeatName As String Dim SubFeatType As String Sub main() Set swApp = Application.SldWorks If Not swApp Is Nothing Then Set swModel = swApp.ActiveDoc If Not swModel Is Nothing Then Set swFeature = swModel.FirstFeature While Not swFeature Is Nothing FeatName = swFeature.Name FeatType = swFeature.GetTypeName If FeatType = "Fillet" Then Dim suppressSet As Boolean Dim suppressState As Long suppressSet = swFeature.SetSuppression_ (swConst.swSuppressFeature) End If ‘ MsgBox "Feature screen name = " & FeatName & vbCrLf & _ "Feature type name = " & FeatType Set swFeature = swFeature.GetNextFeature Wend End If Set swModel = Nothing End If Set swApp = Nothing End Sub

Do

7

Save and run macro.

Return to VBA when finished.

Case Study: Feature Manager Traversal

195

Lesson 7

API Fundamentals

Selection and Traversal Techniques

Setting Feature UI State

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

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

Input:

StateType

swIsHiddenInFeatureMgr

Input:

Flag

TRUE

no Pr t c e-R op e y o lea r d se ist rib ut e

hides the display of the feature in the FeatureManager design tree, FALSE otherwise.

8

Hide all features.

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

Do

Dim Dim Dim Dim Dim Dim Dim Dim

swApp As SldWorks.SldWorks swModel As SldWorks.ModelDoc2 swFeature As SldWorks.feature FeatName As String FeatType As String swSubFeature As SldWorks.feature SubFeatName As String SubFeatType As String

Sub main() Set swApp = Application.SldWorks If Not swApp Is Nothing Then Set swModel = swApp.ActiveDoc If Not swModel Is Nothing Then Set swFeature = swModel.FirstFeature While Not swFeature Is Nothing swFeature.SetUIState swConst.swIsHiddenInFeatureMgr, _ True Set swFeature = swFeature.GetNextFeature Wend swModel.ForceRebuild End If Set swModel = Nothing End If Set swApp = Nothing End Sub

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

196

The Undo command will not work for UI settings.

Case Study: Feature Manager Traversal

API Fundamentals

Lesson 7 Selection and Traversal Techniques

Obtaining a Feature by FeatureManager Position

To obtain a feature from a specific location in the FeatureManager, call ModelDoc2::FeatureByPositionReverse. This method starts counting from the last feature in the Feature Manager and walks “upwards” to get the feature at the index you pass to it.

ModelDoc2::FeatureByPositionReverse

Return: Input:

no Pr t c e-R op e y o lea r d se ist rib ut e

retval = ModelDoc2.FeatureByPositionReverse (PositionFromEnd) retval

Pointer to dispatch object for the nth from last feature in the document.

PositionFromEnd

The feature position number from the last feature. 0

-

gives the last feature

11 Modify code.

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

Sub main() Set swApp = Application.SldWorks If Not swApp Is Nothing Then Set swModel = swApp.ActiveDoc If Not swModel Is Nothing Then Set swFeature = swModel.FeatureByPositionReverse(2) FeatName = swFeature.Name FeatType = swFeature.GetTypeName MsgBox "Feature screen name = " & FeatName & vbCrLf & _ "Feature type name = " & FeatType Set swModel = Nothing End if Set swApp = Nothing End If End Sub

12 Save and run macro.

Do

13 Exit macro.

Case Study: Feature Manager Traversal

197

Lesson 7

API Fundamentals

Do

no Pr t c e-R op e y o lea r d se ist rib ut e

Selection and Traversal Techniques

198

Case Study: Feature Manager Traversal

API Fundamentals

Exercise 11: Handling Preselection 1

no Pr t c e-R op e y o lea r d se ist rib ut e

Exercise 11: Handling Preselection 1

Objective

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

I

Handling selected object types.

I

Handling two face selections at one time.

Do

APIs Used

Procedure

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

1. 2. 3. 4.

Open bottomcase.sldprt. Open DistanceBetweenFaces.swp. Use the APIs listed above to handle the preselection. Save and run macro.

199

Exercise 11:

API Fundamentals

Handling Preselection 1

Solution

Const ParallelDistTolerance As Double = 0.0001 Function Sq(Num As Double) As Double Sq = Num * Num End Function

no Pr t c e-R op e y o lea r d se ist rib ut e

Sub main() Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2 Dim swSelMgr As SldWorks.SelectionMgr Dim SelType1 As Long Dim SelType2 As Long Dim swFace1 As SldWorks.face2 Dim swFace2 As SldWorks.face2 Dim swSurf1 As SldWorks.surface Dim swSurf2 As SldWorks.surface Dim varSelPt1 As Variant Dim varSelPt2 As Variant Dim varClosePt1 As Variant Dim varClosePt2 As Variant Dim Dist1 As Double Dim Dist2 As Double Dim bRet As Boolean

Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc Set swSelMgr = swModel.SelectionManager SelType1 = swSelMgr.GetSelectedObjectType2(1) SelType2 = swSelMgr.GetSelectedObjectType2(2)

Do

If SelType1 swSelFACES Or SelType2 swSelFACES Then Exit Sub End If

Set swFace1 = swSelMgr.GetSelectedObject5(1) Set swFace2 = swSelMgr.GetSelectedObject5(2) Set swSurf1 = swFace1.GetSurface Set swSurf2 = swFace2.GetSurface varSelPt1 = swSelMgr.GetSelectionPoint(1) varSelPt2 = swSelMgr.GetSelectionPoint(2) varClosePt1 = swSurf1.GetClosestPointOn(varSelPt2(0), _ varSelPt2(1), varSelPt2(2)) varClosePt2 = swSurf2.GetClosestPointOn(varSelPt1(0), _ varSelPt1(1), varSelPt1(2)) Dist1 = Sqr(Sq(varSelPt1(0) - varClosePt2(0)) + _ Sq(varSelPt1(1) - varClosePt2(1)) + Sq(varSelPt1(2) - _ varClosePt2(2))) Dist2 = Sqr(Sq(varSelPt2(0) - varClosePt1(0)) + _ Sq(varSelPt2(1) - varClosePt1(1)) + Sq(varSelPt2(2) - _ varClosePt1(2)))

If Abs(Dist1 - Dist2)
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF