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