• No results found

API Api2006 Draft

N/A
N/A
Protected

Academic year: 2021

Share "API Api2006 Draft"

Copied!
376
0
0

Loading.... (view fulltext now)

Full text

(1)

SolidWorks

®

2006

API Fundamentals

SolidWorks Corporation 300 Baker Avenue Concord, Massachusetts 01742

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(2)

© 1995-2005, SolidWorks Corporation 300 Baker Avenue

Concord, Massachusetts 01742 USA All Rights Reserved

U.S. Patents 5,815,154; 6,219,049; 6,219,055; 6,603,486; 6,611,725; and 6,844,877 and certain other foreign patents, including EP 1,116,190 and JP 3,517,643. U.S. and foreign patents pending. SolidWorks Corporation is a Dassault Systemes S.A. (Nasdaq:DASTY) company.

The information and the software discussed in this document are subject to change without notice and should not be considered commitments by SolidWorks Corporation.

No material may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose without the express written permission of SolidWorks Corporation.

The software discussed in this document is furnished under a license and may be used or copied only in accordance with the terms of this license. All warranties given by SolidWorks Corporation as to the software and documentation are set forth in the SolidWorks Corporation License and Subscription Service Agreement, and nothing stated in, or implied by, this document or its contents shall be considered or deemed a modification or amendment of such warranties.

SolidWorks, PDMWorks, and 3D PartStream.NET, and the eDrawings logo are registered trademarks of SolidWorks Corporation.

SolidWorks 2006 is a product name of SolidWorks Corporation.

COSMOSXpress, DWGeditor, DWGgateway, eDrawings, Feature Palette, PhotoWorks, and XchangeWorks are trademarks, 3D ContentCentral is a service mark, and FeatureManager is a jointly owned registered trademark of SolidWorks Corporation.

COSMOS, COSMOSWorks, COSMOSMotion, and COSMOSFloWorks are trademarks of Structural Research and Analysis Corporation.

FeatureWorks is a registered trademark of Geometric Software Solutions Co. Limited. ACIS is a registered trademark of Spatial Corporation.

GLOBEtrotter and FLEXlm are registered trademarks of Globetrotter Software, Inc. Other brand or product names are trademarks or registered trademarks of their respective holders.

Document Number: PMT0077-ENG

COMMERCIAL COMPUTER SOFTWARE - PROPRIETARY

U.S. Government Restricted Rights. Use, duplication, or disclosure by the government is subject to restrictions as set forth in FAR 52.227-19 (Commercial Computer Software - Restricted Rights), DFARS 227.7202 (Commercial Computer Software and Commercial Computer Software Documentation), and in the license agreement, as applicable.

Contractor/Manufacturer:

SolidWorks Corporation, 300 Baker Avenue, Concord, Massachusetts 01742 USA

Portions of this software © 1988, 2000 Aladdin Enterprises.

Portions of this software © 1996, 2001 Artifex Software, Inc.

Portions of this software © 2001 artofcode LLC. Portions of this software © 2005 Bluebeam Software, Inc.

Portions of this software © 1999, 2002-2005 ComponentOne

Portions of this software © 1990-2005 D-Cubed Limited.

Portions of this product are distributed under license from DC Micro Development, Copyright © 1994-2002 DC Micro Development, Inc. All rights reserved

Portions © eHelp Corporation. All rights reserved. Portions of this software © 1998-2005 Geometric Software Solutions Co. Limited.

Portions of this software © 1986-2005 mental images GmbH & Co. KG

Portions of this software © 1996 Microsoft Corporation. All Rights Reserved.

Portions of this software © 2005 Priware Limited Portions of this software © 2001, SIMULOG. Portions of this software © 1995-2005 Spatial Corporation.

Portions of this software © 2003-2005, Structural Research & Analysis Corp.

Portions of this software © 1997-2005 Tech Soft America.

Portions of this software are copyrighted by and are the property of UGS Corp. © 2005.

Portions of this software © 1999-2005 Viewpoint Corporation.

Portions of this software © 1994-2005, Visual Kinematics, Inc.

This software is based in part on the work of the Independent JPEG group.

All Rights Reserved

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(3)

API Fundamentals

i

Table of Contents

Introduction

About This Course . . . 3

Prerequisites . . . 3

Course Design Philosophy . . . 3

Using this Book . . . 3

Windows® XP . . . 3

Conventions Used in this Book . . . 4

About the CD . . . 4

Getting Started . . . 5

File Types . . . 5

Option Explicit . . . 5

Variables . . . 5

Choosing Data Types . . . 6

API Units . . . 6

SolidWorks Constants Type Library . . . 7

Macro Recording Tips . . . 8

SolidWorks 2006 API Help . . . 8

API Object Interfaces . . . 8

Contents . . . 9

Index . . . 9

Search . . . 9

Understanding API Interface Member Descriptions . . . 10

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(4)

API Fundamentals

Lesson 1:

Using the Macro Recorder

Macro Recording . . . 15

Macro Toolbar. . . 15

Understanding How Macro Code Works . . . 20

Variable Declaration . . . 20

Entry Point Procedure . . . 20

SolidWorks Application Object . . . 20

SolidWorks Document Object . . . 20

SolidWorks API Calls. . . 20

Procedure End. . . 20

Understanding How to Call Members on API Interfaces . . . 21

Passing Parameters . . . 22

Cleaning Up Code. . . 24

Commenting Code . . . 25

Debugging Code . . . 26

Adding Forms to a Macro . . . 28

Exercise 1: Recording a Macro. . . 35

Exercise 2: Adding Macro Code to a VBA Button Control . . . 37

Exercise 3: Adding User Input Fields on a VBA Form . . . 40

Lesson 2: The API Object Model SolidWorks API Object Model . . . 45

Visual Basic Automatic Type Casting . . . 46

Application Objects . . . 47

SldWorks Object. . . 47

SolidWorks 2006 Type Library . . . 48

IntelliSense . . . 49

Early vs. Late Binding . . . 49

Case Study: Connecting to New Documents . . . 51

Macro Results . . . 54

ModelDoc2 Object . . . 55

ModelDoc Extension Object. . . 56

PartDoc Object . . . 64

AssemblyDoc Object . . . 64

DrawingDoc Object . . . 64

Case Study: Connecting to Existing Documents . . . 69

Exercise 4: Working with New Documents . . . 77

Exercise 5: Working with Existing Documents . . . 79

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(5)

API Fundamentals

iii

Lesson 3:

Setting System Options and Document Properties

User Preferences - System Options . . . 83

Setting Checkboxes. . . 83

Setting Textboxes with Integers . . . 85

Setting Textboxes with Doubles . . . 86

Setting Textboxes with String Values . . . 87

Setting Listboxes. . . 88

Setting Radio Buttons . . . 88

Setting Slider Bars . . . 88

User Preferences - Document Properties . . . 90

Locating the Correct APIs and Enumeration Values . . . 91

UserPreference Tables For System Options . . . 92

UserPreference Tables For Document Properties . . . 111

Exercise 6: Change Multiple System Options . . . 123

Exercise 7: Change Multiple Document Properties . . . 125

Lesson 4: Automating Part Design Case Study: Automation Tool for Parts . . . 129

Setting Material. . . 130

Creating the Sketch Rectangle . . . 131

Adding Dimensions . . . 131

Selection on Creation . . . 131

Creating the Sketch Circle . . . 133

Creating Extruded Features . . . 133

Enabling Contour Selection for the Extrusion . . . 134

Creating Revolved Features . . . 135

Standard Commands . . . 137

View Commands. . . 137

Sketch Commands . . . 138

Sketch Tools Commands . . . 138

Features Commands . . . 139

Sketch Relations Commands . . . 139

Reference Geometry Commands . . . 139

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

Lesson 5: Assembly Automation Case Study: Automation Tool for Assemblies . . . 145

Transforms . . . 148

Creating MathTransforms. . . 148

The Transformation Matrix . . . 148

Activating Documents . . . 149

Invisible Documents . . . 149

Object Collections. . . 150

Establishing the Curve and Edge Collections. . . 150

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(6)

API Fundamentals

Establishing the Face Collection. . . 151

Getting Adjacent Faces . . . 152

Establishing the Points Collection . . . 153

Getting Curve Parameters . . . 153

Adding and Mating the Knobs to the Chassis. . . 154

Adding Components . . . 155

Adding Mates . . . 155

Exercise 9: Adding Components . . . 157

Lesson 6: Drawing Automation Case Study: Automating Drawing Creation . . . 161

Getting Configuration Names . . . 163

Creating Sheets . . . 164

Creating Views . . . 166

Inserting Annotations . . . 167

Traversing Drawing Views . . . 169

Saving Drawings in Different Formats . . . 170

Drawing Commands . . . 172

Annotation Commands . . . 172

Layer Commands . . . 172

Line Format Commands . . . 172

Exercise 10: Drawing Automation . . . 173

Lesson 7: Selection and Traversal Techniques Case Study: Programming With a Selected Object . . . 179

SelectionManager . . . 180

Accessing the Selection Manager . . . 180

Counting Selected Objects . . . 180

Accessing Selected Objects . . . 181

Getting Selected Object Types . . . 181

Getting Feature Type Names . . . 181

Feature Data Objects. . . 182

Accessing the Feature Data Object . . . 182

Accessing Selections. . . 182

Releasing Selections . . . 183

Modifying Feature Data Properties. . . 183

Modify the Object Definition . . . 184

The SolidWorks BREP Model . . . 185

Traversing Topology and Geometry. . . 186

Case Study: Body and Face Traversal . . . 187

Returning a List of Body Pointers . . . 188

Face Material Properties . . . 190

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(7)

API Fundamentals

v

Case Study: Feature Manager Traversal . . . 192

Traversing the FeatureManager from the Top . . . 192

Displaying Feature Names and Types . . . 193

Setting Feature Suppression . . . 194

Setting Feature UI State . . . 196

Obtaining a Feature by FeatureManager Position . . . 197

Exercise 11: Handling Preselection 1 . . . 199

Exercise 12: Handling Preselection 2 . . . 201

Exercise 13: Traversing the FeatureManager . . . 203

Lesson 8: Adding Custom Properties and Attributes Case Study: Custom Properties. . . 207

Adding Custom Properties to a SolidWorks Document . . . 208

Setting and Getting Custom Property Values . . . 209

Getting Custom Property Names . . . 210

Getting the Custom Property Count . . . 210

Case Study: Configurations With Custom Properties. . . 211

Returning Mass Properties From a SolidWorks Model . . . 213

Using the API to Return the Mass Properties . . . 213

Case Study: File Summary Information . . . 216

Adding Summary Information . . . 216

Case Study: Document Attributes. . . 217

Naming Attributes. . . 218

The Attribute Objects . . . 218

AttributeDef Object . . . 218

Attribute Object . . . 219

Parameter Object. . . 219

Case Study: Face Attributes . . . 221

Finding the Cylindrical Faces and Attaching Attributes . . . 223

Displaying Callouts in the Model View . . . 225

Callout Object . . . 225

Creating the CNC Code . . . 226

Types of Attribute Traversal. . . 226

A Final Word about Attributes . . . 229

Exercise 14: Adding Mass Properties as Custom Properties . . . 231

Exercise 15: Adding Attributes to Edges . . . 233

Lesson 9: The SolidWorks API SDK The API SDK . . . 239

Installing the SDK . . . 239

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

References. . . 246

Comparing Addin DLLs and Stand-Alone Executables. . . 249

Loading and Running an Add-in Application. . . 250

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

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(8)

API Fundamentals

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

Compiling a C++ Add-In . . . 257

Loading the C++ Add-In. . . 259

Debugging the C++ Add-in . . . 260

Choosing a Programming Language. . . 263

Lesson 10: Customizing the SolidWorks User Interface Case Study: Customizing the UI With VB.NET. . . 267

Debugging the DLL . . . 270

Debugger Keyboard Shortcuts . . . 271

Understanding The Add-in Code . . . 272

Importing Namespaces . . . 273

The Add-in Class . . . 273

Understanding the GUID . . . 274

Connecting to Solidworks. . . 275

Bidirectional Communication. . . 276

Setting Callback Information . . . 276

Custom Menus . . . 277

Custom Menu Items . . . 279

Creating and Adding Custom Toolbars to an Add-in . . . 281

Creating the Toolbar Bitmaps. . . 282

Adding Toolbar Bitmaps to a VB.NET Solution . . . 283

The Bitmap Handler Class . . . 284

Adding Toolbars . . . 285

Adding Toolbar Commands . . . 287

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

Creating a PropertyManager Page . . . 291

Property Page Groups and Controls . . . 292

Adding Group Boxes . . . 293

Group and control IDs . . . 293

Adding Controls . . . 294

Adding Picture Labels to Controls . . . 297

Removing Menus and Toolbars . . . 299

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(9)

API Fundamentals

vii

Other Areas of Customization . . . 302

Custom Status Bars . . . 302

Custom Pop-up Menus . . . 303

Custom ModelView Windows . . . 303

Exercise 16: Implement a New Menu. . . 305

Exercise 17: Implement Toolbar Buttons . . . 307

Exercise 18: Implement Controls on a Property Manager Page . . . . 309

Lesson 11: Notifications Notifications . . . 315

Notifications in VBA . . . 315

Case Study: Simple Notification. . . 316

The Class Module . . . 316

Case Study: Using Notifications in .NET . . . 318

The AddHandler Keyword . . . 321

The AddressOf Keyword . . . 321

The Event Handler Classes . . . 322

The Document Event Handler Class. . . 323

Attaching the DocumentEvent Handlers . . . 324

Inheritance . . . 326

Polymorphism . . . 326

The Derived Event Handler Classes . . . 328

The DocView Class . . . 330

Detaching the Document and Model View Event Handlers. . . . 333

Detaching the SolidWorks Event Handlers . . . 337

Interfaces That Support Notifications. . . 340

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

Solution . . . 348 Appendix Macro Feature . . . 350 Batch Conversion 1. . . 353 Batch Conversion 2. . . 355 Assembly Traversal . . . 356

Custom Model View . . . 358

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(10)

API Fundamentals

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(11)

API Fundamentals 1

Introduction

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(12)

API Fundamentals Introduction

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(13)

API Fundamentals

Introduction

About This Course 3

About This

Course

The goal of this course is to introduce you to the SolidWorks 2006 Application Programming Interface (API). The API is used to automate redundant and lengthy design tasks using SolidWorks. It is also used to create complete engineering applications that run inside or outside of the SolidWorks application. Everything a user leverages through the SolidWorks user interface can be automated by programming it

through the API. The SolidWorks API is so robust and feature rich that it is impractical to cover every detail and still have the course be a reasonable length. Therefore, the focus of this course is on the fundamental skills and concepts central to successfully building automation tools. Once you have developed a good foundation in basic skills, you can use the on-line help to collect information on more functionality available in the API.

Prerequisites Students attending this course are expected to have: I Mechanical design experience.

I Completed the course SolidWorks Essentials: Parts, Assemblies, and Drawings.

I Experience with the Windows™ operating system. I Experience with Visual Basic.

Course Design Philosophy

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

Using this Book This training manual is intended to be used in a classroom environment under the guidance of an experienced SolidWorks API instructor. It is not intended to be a self-paced tutorial. The examples and case studies are designed to be demonstrated “live” by an instructor.

Laboratory Exercises

Laboratory exercises give you the opportunity to apply and practice the material covered during the lecture/demonstration portion of the course. They are designed to represent typical programming and automation situations, while being modest enough to be completed during class time. However, many students work at different paces. Therefore, we have included more lab exercises than you can

reasonably expect to complete during the course. This ensures that even the fastest student will not run out of exercises.

Windows® XP The screen shots in this manual were created using SolidWorks 2006 running on Windows® XP. If you are running on a different version of Windows, you might notice subtle differences in the appearance of the menus and windows. These differences do not affect the performance of the software.

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(14)

API Fundamentals

Introduction

Conventions Used in this Book

This manual uses the following typographic conventions:

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

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

Convention Meaning

Bold Sans Serif SolidWorks commands and options appear in

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

Typewriter Feature names and file names appear in this style. For example, Macro1.swp.

Lucida Console Sample code appears in this style. Colors of

the text have special meaning. Gray is used to identify code that has already been entered.

Black and Blue indicates code to be entered.

Red indicates code to be removed. Green

indicates code to be commented. These color conventions follow those of Microsoft™ Visual Basic.

17 Do this step

Double lines precede and follow sections of the procedures. This provides separation between the steps of the procedure and large blocks of explanatory text. The steps

themselves are numbered in sans serif bold.

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(15)

API Fundamentals

Introduction

Getting Started 5

Getting Started

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

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

In Visual Basic.Net these files may be necessary: SolutionFiles(*.sln)

SourceCodeFiles(*.vb)

.NET Assembly/Dynamic-LinkLibrary(*.dll)

Option Explicit It is strongly recommended that you use the Option Explicit

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

In Visual Basic.NET this option can be turned on globally from the Tools, Options... then use the Projects, VB Defaults dialog box. Variables Variables are used to store temporary values during the execution of an

application. Variables are made up of two parts: Name and Data Type. Essentially, a variable is a place holder in memory for an unknown value. Declaring a variable tells the program about it in advance. You declare a variable with the Dim statement, supplying a name for the variable:

Dim variablename [As data type]

The optional, As data type, clause in the Dim statement allows you to define the data type or object type of the variable. It is good practice to define the type when you declare it. This will make the runtime set aside the required amount of memory ahead of time instead of having to dynamically resolve the amount of memory needed at run time. If you let the runtime decide, it may allocate larger chunks of memory then what is really required.

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(16)

API Fundamentals

Introduction

Choosing Data Types

Visual Basic supports these standard types of data:

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

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

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

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

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

Decimal - supports up to 29 significant digits and can represent values up to 7.9228 x 1028. It is particularly suitable for calculations, such as financial, that require a large number of digits but cannot tolerate rounding errors.

Date - holds date and time values between Jan 1, 1000 to midnight on December 31, 9999. To make sure a variable is of this type, surround assigned date with (# #)

Byte - holds integer values between 0 and 255

Boolean - holds values that are either True or False

Variant - holds values of all data types

Object - holds a 32 bit (4-byte) address that refers to objects. Using the

Set statement, a variable declared as an object can have any object reference assigned to it.

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

Dim swApp As Object 'Generic object

Dim swApp As SldWorks.SldWorks 'Specific object

Dim filename As String 'Simple string

Dim dvarArray(2) As Double 'Set of 3 doubles

There are additional data types available to the programmer once the SolidWorks 2006 type library has been referenced (e.g. SldWorks). API Units All APIs use meters and radians for length and angle units.

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(17)

API Fundamentals Introduction Getting Started 7 SolidWorks Constants Type Library

For SolidWorks API development, you should include the SolidWorks 2006 Constant type library to each project. This type library provides definitions used with SolidWorks API methods. The constants are passed to methods instead of the number values they represent. This ensures that when you install a new version of SolidWorks, the code will work the same as it did in the last release. The number values can change from release to release. The constant values will not change, they will only be appended to.

If you record a macro using the VBA environment in SolidWorks the type library will be automatically included. To check this, edit a macro recorded in SolidWorks 2006, and choose Tools, References... from the menu. The References dialog box will show you the type libraries that are included in your project. Notice that there are two SolidWorks type libraries used in each project.

We will discuss the SldWorks 2006 Type Library in more detail in Chapter 2.

Note Consider the case when a programmer forgets to include the

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

SolidWorks constants type library was missing from the project.

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(18)

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

I Plan the steps before recording a macro.

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

I If you need to change views while recording, remove extraneous code entries after the recording is completed, such as:

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.

SolidWorks 2006 API Help

The SolidWorks 2006 API help file is designed for programmers and end users who want to research information specific to API interfaces, methods, properties, and events. To open the file in SolidWorks, click Help, SolidWorks API and Add-In Help Topics.

API Object Interfaces

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

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(19)

API Fundamentals

Introduction

Macro Recording Tips 9

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

SolidWorks 2006 API Release Notes - This part of the help file has information on new functionality released in SolidWorks 2006. Included in this section are new interfaces, methods, properties and events in the API object model.

Programmer’s Guide - Useful information on getting started in Visual Basic, and programming topics such as adding macros to a menu, notifications, units, return values, and using safe arrays.

Examples - Code examples ranging from creating compound notes to getting curve spline points.

APIs - A complete documentation of the all interfaces and their methods, properties, and events supported in the SolidWorks API. Obsolete APIs - This part of the help file has information on APIs that are obsolete in SolidWorks 2006.

Index The Index tab of the API help file allows you to quickly locate API topics through it’s alphabetically ordered list of keywords.

Search The Search tab of the API help

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

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(20)

API Fundamentals

Introduction

Understanding API Interface Member Descriptions

1. API Member Name - Used to describe the API interface member. It is written with a general syntax name for clarity (Object::Member). The object name in this case is SldWorks. The double colons indicate where to place an access operator (a period). The member name (a method in this case) is ArrangeWindows, which cannot be changed.

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

3. API Description - This is an explanation of the API interface or the selected members functionality.

4. Syntax (OLE Automation) - This section describes the OLE syntax for using this interface object member. (commonly used by VB programmers.) 1 2 3 4 5 6 7 8 9

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(21)

API Fundamentals

Introduction

Macro Recording Tips 11

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

swApp.ArrangeWindows 0

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

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

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

Dim swPart As Object

Set swPart = swApp.NewPart

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

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

This is shown in the following example.

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

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(22)

API Fundamentals

Introduction

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

Dim style As Long

style = 1

swApp.ArrangeWindows (style)

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

swApp.ArrangeWindows 1

Note The name style is just a descriptive name for the variable, you can name this variable anything you like. Always try to give your variables descriptive names.

7. Parameters - Descriptions of possible values for each parameter (if the API call requires parameters). In this case, put a 0 to cascade, 1 tiles the windows horizontally, and 2 tiles the windows vertically. 8. Syntax (COM) - Devoted to COM programming syntax.

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

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(23)

API Fundamentals

13

Lesson 1

Using the Macro Recorder

Upon successful completion of this lesson, you will be able to: I Understand what a macro is, and how a macro can be used to

automate SolidWorks.

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.

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(24)

Lesson 1 API Fundamentals

Using the Macro Recorder

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(25)

API Fundamentals Lesson 1

Using the Macro Recorder

Macro Recording 15

Macro

Recording

You can record operations performed with the SolidWorks user

interface and replay them using SolidWorks macros. A macro contains calls to the Application Programming Interface (API) that are

equivalent to operations performed in the user interface. A macro can record mouse clicks, menu choices and keystrokes.

Macro Toolbar

The Macro toolbar contains shortcuts to the macro recording commands. You can also access these commands from the Tools, Macro menu.

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

Stop launches the Save As macro dialog box, where the user enters a valid name and extension for the macro. If the save is cancelled, a prompt appears that allows the user to continue or cancel the recording. Record/Pause allows the user to begin or pause macro recording. New performs three steps: First, it launches the New Macro dialog box where the user enters a valid name for the macro.

Next, the macro file is populated with standard lines of programming code to connect to SolidWorks.

Finally, the VBA editor opens the macro file for the user to begin programming.

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

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

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(26)

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.

2 View the Macro toolbar.

From the View menu, choose Toolbars, Macro.

3 Click Record .

4 Select the

Front

plane.

5 Click Sketch .

6 Click Circle .

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

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(27)

API Fundamentals Lesson 1

Using the Macro Recorder

Macro Toolbar 17

7 Click Extruded Boss/Base .

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

8 Click Stop .

9 Save the macro.

In the Save As dialog, save the macro as Macro1.swp. 10 Delete all features.

Remove the extruded base and sketch created previously. 11 Click Play .

Select Macro1.swp from the previous step.

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(28)

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

Click 1 - Select a plane.

Click 2 - Insert sketch command. Click 3 - Create circle command. Click 4 - Center of circle.

Click 5 - Approximate 40 mm radius of circle. Keyboard Entry 1 - Exact radius: 40 mm. Click 6 - OK button.

Click 7 - Extruded boss/base button.

Click 8 - Approximate 15 mm depth of extrusion. Keyboard Entry 2 - Exact depth: 15 mm.

Click 9 - OK button. Total Clicks: 9

Total Keyboard Entries: 2

All of the users input and time is eliminated simply by running the macro.

12 Customize the Macro toolbar.

From the Tools menu, choose Customize.... On the Commands tab, highlight the Macro category.

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

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

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(29)

API Fundamentals Lesson 1

Using the Macro Recorder

Macro Toolbar 19

13 Program a custom button.

When the new button is dropped on a toolbar, the

Customize Macro Button dialog appears automatically.

Set the Macro field to launch Macro1.swp by browsing for the file. The Method field will update automatically with available sub routines in the file.

Keep the default image, and enter

helpful text for the Tooltip and Prompt (optional). Click OK.

14 Click Custom Macro .

Again, before running the macro, it is good practice to delete the boss and sketch so you can see the new part creation without overlapping features.

15 Visual Basic for Applications editor.

Click the Edit button from the Macro toolbar. Select Macro1.swp.

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(30)

Lesson 1 API Fundamentals

Using the Macro Recorder

Understanding

How Macro

Code Works

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

Variable Declaration

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

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

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

Entry Point Procedure

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

Sub main()

SolidWorks

Application Object

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.

Set swApp = Application.SldWorks

SolidWorks Document Object

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

Set Part = swApp.ActiveDoc

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

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

Procedure End End Sub

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(31)

API Fundamentals Lesson 1

Using the Macro Recorder

Understanding How to Call Members on API Interfaces 21

Understanding

How to Call

Members on

API Interfaces

API members, often referred to as events, properties, methods, functions or simply APIs, are called to interact with the actual object members that are exposed by the SolidWorks application.

In order to call members on API objects, a few steps are required. 1. Declare and instantiate the highest level object in the SolidWorks

API. The API represents this object as SldWorks. A macro will use the default name swApp for this variable declaration.

Dim swApp As Object

Set swApp = Application.SldWorks

2. Declare and instantiate a document object. The following lines of code declare the variable used to store the documents object pointer. Then it instantiates this object by calling an accessor method on the SldWorks object.

Dim Part As Object

Set Part = swApp.ActiveDoc

3. Once the application and document objects are instantiated, members on those objects are called. To access these members the object name is written first, separated by a period, and followed by the full name of the API call:

Part.InsertSketch2 True

Some APIs members require additional parameters such as the following method call:

Part.CreateCircleByRadius2 0, 0, 0, 0.04

Some APIs require additional objects:

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

0.01745, 0.01745, False, False, False, False, 1, 1, 1, _ 0, 0, False

Some APIs utilize return values:

Dim boolstatus As Boolean

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

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(32)

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

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

Output: pFeat Pointer to the feature object.

Input: sd TRUE for single ended, FALSE for double ended.

Input: flip TRUE to flip the direction to cut.

Input: dir TRUE to flip the direction to extrude.

Input: t1 Termination type for first end from

swEndConditions_e enumeration. swEndCondBlind swEndCondThroughAll swEndCondThroughNext swEndCondUpToVertex swEndCondUpToSurface swEndCondOffsetFromSurface swEndCondMidPlane swEndCondUpToBody

Input: t2 Termination type for second end from

swEndConditions_e enumeration. (see above)

Input: d1 Depth of extrusion for first end in meters.

Input: d2 Depth of extrusion for second end in meters.

Input: dchk1 TRUE allows draft angle in first direction, FALSE does

not allow drafting.

Input: dchk2 TRUE allows draft angle in second direction, FALSE

does not allow drafting.

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

outward.

Input: ddir2 TRUE for second draft angle to be inward, FALSE to be

outward.

Input: dang1 Draft angle for first end.

Input: dang2 Draft angle for second end.

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(33)

API Fundamentals Lesson 1

Using the Macro Recorder

Passing Parameters 23

Input: offsetReverse1 If you chose to offset the first end condition from

another face or plane, then TRUE specifies offset in

direction away from the sketch, FALSE specifies offset from the face or plane in direction toward the sketch. Input: offsetReverse2 If you chose to offset the second end condition from

another face or plane, then TRUE specifies offset in

direction away from the sketch, FALSE specifies offset from the face or plane in direction toward the sketch. Input: translateSurface1 When you choose swEndcondOffsetFromSurface as

the termination type for the first end, then TRUE

specifies that the end of the extrusion is a translation of the reference surface, FALSE specifies to use a true offset.

Input: translateSurface2 When you choose swEndcondOffsetFromSurface as

the termination type for the second end, then TRUE

specifies that the end of the extrusion is a translation of the reference surface, FALSE specifies to use a true offset.

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

not.

Input: useFeatScope TRUE if the feature only affects selected bodies, FALSE

if the feature affects all bodies.

Input: useAutoSelect TRUE to automatically select all bodies and have the

feature affect those bodies, FALSE to select the bodies the feature affects

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

Input: t0 Start condition from swStartConditions_e

enumeration.

swStartSketchPlane swStartSurface swStartVertex swStartOffset

Input: startOffset If t0 set to swStartOffset, then specify offset value.

Input: flipStartOffset If t0 set to swStartOffset, then TRUE to flip the

direction or FALSE to not.

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(34)

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.

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

parameters: xc, yc, zc, radius. This API call is more in line with what we performed manually and it is perfectly okay to use as a replacement.

Option Explicit

These comments are not functional and can be deleted.

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

'********************************************************** Dim swApp As Object

Dim Part As Object

This variable is not needed Dim SelMgr As Object Dim boolstatus As Boolean

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

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

Sub main()

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

This call is unnecessary Set SelMgr = Part.SelectionManager

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

Part.InsertSketch2 True Part.ClearSelection2 True

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

These calls are unnecessary. Part.ShowNamedView2 "*Trimetric", 8 Part.ClearSelection2 True

boolstatus = Part.Extension.SelectByID2("Arc1", "SKETCHSEGMENT", 0, 0, 0, False, 0, Nothing, 0)

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

This call is unnecessary. Part.SelectionManager.EnableContourSelection = 0 End Sub

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(35)

API Fundamentals Lesson 1

Using the Macro Recorder

Cleaning Up Code 25

Tip As you study the API help file, you’ll notice that some methods have a number suffixed to the end of the method name

(i.e. ModelDoc2.CircleCircleByRadius2.) This number represents the version of the method. If you want to use a method in your program you should consider using the latest version. This will ensure the longevity of your code. The same practice should be done when you choose a particular interface to use in your code.

ModelDoc2 is the current version of the SolidWorks document pointer. Although the older versions may continue to show up and be functional in newer releases of SolidWorks, they are generally left there so that older software that used those APIs will still work. In many cases older APIs may have a shorter parameter list and you may feel compelled to use them because less typing is required.

The method SldWorks.SendMsgToUser, for example, has two versions. The older version requires one parameter. For testing code it is

convenient to use this method because you don’t have to satisfy the four parameters required by SendMsgToUser2. That may be okay for your simple utility or for testing, but for production quality code you should use the latest versions of the APIs. This will eliminate problems when your program is run on a newer version of SolidWorks.

Commenting Code Now that we’ve identified what lines of code to remove or modify, we can insert comments. To add comments to the code, prefix the

comment with an apostrophe character. The apostrophe tells the compiler to ignore anything on that line that follows it.

16 Modify the code.

Modify the code and add comments. Also change the code to use CreateCircleByRadius2 instead of CreateCircle.

Option 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

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(36)

Lesson 1 API Fundamentals

Using the Macro Recorder

Debugging Code Although this manual does not go into detail about debugging

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

17 Add a breakpoint.

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

18 Debug the macro.

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

Breakpoint

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(37)

API Fundamentals Lesson 1

Using the Macro Recorder

Cleaning Up Code 27

19 Begin stepping into code.

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

20 Press F8.

21 Press F8.

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

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(38)

Lesson 1 API Fundamentals

Using the Macro Recorder

22 Press F8.

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

23 Continue to end of code. Press F5.

Alternatively, we can continue stepping into the code as before, line by line, until the end of the procedure.

Adding Forms

to a Macro

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

Where to Find It I In VBA, click Insert, UserForm.

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

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(39)

API Fundamentals Lesson 1

Using the Macro Recorder

Adding Forms to a Macro 29

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

With the userform highlighted, enter the following property values into the properties window for this userform object:

UserForm1:

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

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(40)

Lesson 1 API Fundamentals

Using the Macro Recorder

27 Add a click event to each button.

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

Private Sub cmd100mm_Click() End Sub

Private Sub cmd500mm_Click() End Sub

Private Sub cmd1m_Click() End Sub

Private Sub cmd5m_Click() End Sub

Private Sub cmdExit_Click() End Sub

Tip Use the Ctrl + Tab key to switch back to the userform every time you add a new event handler. In VBA the form is separated from the source code that runs behind the form.

28 Move code from the module to the button events.

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

Private Sub cmd100mm_Click()

Dim swApp As Object Dim Part As Object

Dim boolstatus As Boolean ‘Connect to SolidWorks

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

‘Create a cylinder on the front plane

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

Part.InsertSketch2 True

Part.CreateCircleByRadius2 0, 0, 0, 0.04

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

End Sub

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(41)

API Fundamentals Lesson 1

Using the Macro Recorder

Adding Forms to a Macro 31

Private Sub cmd500mm_Click()

Dim swApp As Object Dim Part As Object

Dim boolstatus As Boolean ‘Connect to SolidWorks

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

‘Create a cylinder on the front plane

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

Part.InsertSketch2 True

Part.CreateCircleByRadius2 0, 0, 0, 0.04

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

End Sub

Private Sub cmd1m_Click()

Dim swApp As Object Dim Part As Object

Dim boolstatus As Boolean ‘Connect to SolidWorks

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

‘Create a cylinder on the front plane

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

Part.InsertSketch2 True

Part.CreateCircleByRadius2 0, 0, 0, 0.04

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

End Sub

Private Sub cmd5m_Click()

Dim swApp As Object Dim Part As Object

Dim boolstatus As Boolean ‘Connect to SolidWorks

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

‘Create a cylinder on the front plane

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

Part.InsertSketch2 True

Part.CreateCircleByRadius2 0, 0, 0, 0.04

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

End Sub

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

(42)

Lesson 1 API Fundamentals

Using the Macro Recorder

29 Program the Exit button.

Private Sub cmdExit_Click()

End

End Sub

30 Add code to the module.

In order for the userform to appear in SolidWorks, the entry point procedure on the module needs to show the userform. Enter the following line of code:

Sub main()

frmMacro1a.Show

End Sub

31 Save and run the macro.

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

32 Exit the macro.

Click the Exit button to end the macro and return to VBA. 33 Add a second userform.

Click Insert, UserForm. Enter the following property values:

UserForm2:

(Name): frmMacro1b Caption: Custom Cylinder

Startup Position: 2 - CenterScreen ShowModal: False 100mm 500mm 1m 5m

Pr

e-R

elea

se

Do

no

t co

py

or

dis

trib

ute

References

Related documents

14 When black, Latina, and white women like Sandy and June organized wedding ceremonies, they “imagine[d] a world ordered by love, by a radical embrace of difference.”

Results of the survey are categorized into the following four areas: primary method used to conduct student evaluations, Internet collection of student evaluation data,

See, e.g., In re Sage Realty Corp., 91 N.Y.2d 30, 35 (NY 1997) (“We conclude that the majority position, as adopted in the final draft of the American Law Institute Restatement

a. Written notices sent home with the students or children attending the CDC or school and given to staff members. Letters mailed at least 1 week before the application.

The resilience study is based on information from the inventory and the comparative case study including demographic information and the contextual attributes (political, economic

Miles divided by hours must give the answer as miles per hour mph Example If the distance were in feet and the time in seconds, what units would the speed be in..

The exclusion of coverage for the dishonest acts of owners, partners, principals of an insured does not apply when a management company is an insured under an

SACK may not be used for every connection, as it is not always supported locally or a TCP peer does not want to use the option. In cases of multiple segments loss when.. using