Headlines
| SolidWorks API | ||
|---|---|---|
|
|
Updated | Wed, 27 Mar 2013 14:11:44 +0000 |
| Description | programming the best 3D CAD | |
| Webmaster | ||
| Category | ||
| Generator | http://wordpress.com/ | |
| Language | en | |
| What does it take to learn the SolidWorks API? | ||
| Category | training | |
| Published: | ||
| Description: | Keith here. First, let me publicly thank P. Guglielmetti for bestowing upon me the admin rights to this blog. In the coming months I hope to continue adding macro samples and API advice. Those interested in the SolidWorks API typically fall into one of two categories: Those wanting to hire someone who knows the SolidWorks [...] |
|
Keith here. First, let me publicly thank P. Guglielmetti for bestowing upon me the admin rights to this blog. In the coming months I hope to continue adding macro samples and API advice. Those interested in the SolidWorks API typically fall into one of two categories:
As with any other disciple, there is always a tradeoff between time and money. If you have money but not time, you need a consultant. If you have time but not money, you may consider learning the discipline yourself. Most engineers interested in the API fall into the second category. Then again, what engineer really has gobs of time to spend learning a new discipline? Not many of us do. Nevertheless, I can help you develop a general idea of how long it will take you to learn the API—assuming you use the best resources available.
Three Essential Skills to SolidWorks API ProgrammingFirst, let’s consider the skills that an API programming novice will need to learn in order to use the SolidWorks API:
Why Are These Skills Important?
Fastest Way to Learn These Skills?As with learning any discipline, you’re more than welcome to dive right in without any professional instruction or guidance. You can play around with the macro recorder, look at code samples you find online, try cutting and pasting your own macros together, etc. Needless to say, if you have no prior programming experience, you’ll end up with 1) sloppy code that doesn’t do a whole lot, 2) a lot of frustration because you don’t really understand how the code works (and therefore how to modify it to your needs). Alternatively, what if you could have a professional SolidWorks API programmer sit beside you and walk you through all of the basics, and well beyond? This exact experience may not be possible, but you can get pretty close using SolidWorks API video tutorials like those found here. In particular, I recommend using dual monitors—have the video on one screen and your code editor on the other screen. Do you know of any faster ways to learn the SolidWorks API? So what’s it really going to cost me?The truth is, learning the SolidWorks API isn’t like learning any other SolidWorks feature. It requires skills that may be completely new to you. This means you’ll have to put in the time to practice and get better. Of course, the end result is more than worth it. Who doesn’t want to automate some or all of their workflow? Who doesn’t want to increase their company’s bottom line? Who doesn’t want to learn skills that separate them from their peers? Do you want these things and enjoy learning? The API is for you. If you’re considering taking your first plunge into the SolidWorks API, feel free to email me if you want more advice. |
||
| Redlight forever! | ||
| Category | addin, solidworks api | |
| Published: | ||
| Description: | I’m pleased to see that some people are still looking for the “RedLight” tool I developed at DynaBits back in 2003. I therefore decided to make it available again here, especially because it has a button that points to my PayPal account which is still valid, and, just to mention, no one never ever paid [...] |
|
I’m pleased to see that some people are still looking for the “RedLight” tool I developed at DynaBits back in 2003. I therefore decided to make it available again here, especially because it has a button that points to my PayPal account which is still valid, and, just to mention, no one never ever paid a single $, ? or CHF for RedLight … Technically, since this is a blog about API, the trick is to stop a rebuild when it starts by handling the RegenNotify event and exploiting this information from the API help : “Return S_FALSE to stop from proceeding with the action that caused the notification.”
Below is a copy of the (old) page about RedLight on DynaBits’ web site:
|
||
| OBJ+MTL exporter | ||
| Category | macro, solidworks api | |
| Published: | ||
| Description: | This macro exports parts and (simple) assemblies to Alias OBJ format, generating a corresponding MTL material file at the same time. This will evolve towards an exporter to Hyperion soon … 'OBJ+MTL exporter : exports parts and (simple) assemblies to Alias OBJ format, 'generating a corresponding MTL material file at the same time. 'Author : [...] |
|
This macro exports parts and (simple) assemblies to Alias OBJ format, generating a corresponding MTL material file at the same time. This will evolve towards an exporter to Hyperion soon …
'OBJ+MTL exporter : exports parts and (simple) assemblies to Alias OBJ format,
'generating a corresponding MTL material file at the same time.
'Author : Ph. Guglielmetti, (www.goulu.net) Switzerland, all rights reserved
'Licence: you may use this macro for free, as long as this header is kept untouched.
'License: no support is provided
'Licence: it is forbidden to sell this code or publish it elsewhere without our permission
'Note : "Microsoft Scripting Runtime" must be added to support "Dictionary" data type
'Revision : PGu 2007/03/25 first step towards a Hyperion exporter (http://www.hypergraphics3d.com/)
Const mm As Double = 0.001
Const scal = 1 / mm ' factor the scale the export
Public swApp As SldWorks.SldWorks
Private materials As New dictionary
Private offset As Long ' to append meshes in same OBJ file
Sub main()
Set swApp = Application.SldWorks
Dim doc As SldWorks.ModelDoc2
Set doc = swApp.ActiveDoc
Open doc.GetPathName + ".obj" For Output As 1
Print #1, "# SolidWorks to OBJ exporter by Dr. Goulu"
Dim mtlfile As String: mtlfile = doc.GetPathName + ".mtl"
mtlfile = Mid(mtlfile, InStrRev(mtlfile, "\") + 1) ' remove path
Print #1, "mtllib "; Replace(mtlfile, " ", "")
offset = 1 'vertices are numbered from 1 in OBJ format
Select Case doc.GetType
Case swDocPART:
Call AddMaterial(doc.MaterialUserName, doc.MaterialPropertyValues)
Call ExportOBJ(doc.GetBodies2(swSolidBody, True), doc.MaterialUserName)
Case swDocASSEMBLY:
Call Traverse(doc.GetActiveConfiguration.GetRootComponent)
End Select
Close 1
Call ExportMTL(mtlfile)
End Sub
Private Sub Traverse(comp As SldWorks.Component2)
Dim mat As String: mat = comp.GetMaterialUserName
If Not AddMaterial(mat, comp.GetMaterialPropertyValues2(swThisConfiguration, Nothing)) Then
On Error Resume Next ' dirty way to skip assemblies
mat = comp.GetModelDoc.MaterialUserName
Call AddMaterial(mat, comp.GetModelDoc.MaterialPropertyValues)
On Error GoTo 0
End If
Call ExportOBJ(comp.GetBodies2(swSolidBody), mat, comp.Transform2)
Dim children As Variant: children = comp.GetChildren
Dim c As Variant
For Each c In children
Dim child As Component2: Set child = c
Call Traverse(child) 'recurse in parts
Next c
End Sub
Private Sub ExportOBJ(bodies As Variant, material As String, Optional transform As SldWorks.MathTransform)
If IsEmpty(bodies) Then Exit Sub
Dim b As Variant
For Each b In bodies
Dim body As SldWorks.Body2: Set body = b
Print #1, "": Print #1, "#Body "; body.name
Print #1, "g"
Dim mat As String: mat = body.GetMaterialUserName2
If mat <> "" Then
Call AddMaterial(body.GetMaterialUserName2, body.MaterialPropertyValues2)
Else
mat = material 'default material
End If
If mat <> "" Then Print #1, "usemtl "; material
Dim tess As SldWorks.Tessellation
Dim e As Variant 'empty
Set tess = body.GetTessellation(e)
tess.NeedFaceFacetMap = True
tess.MatchType = swTesselationMatchFacetTopology
Debug.Assert tess.Tessellate
Dim n As Long: n = tess.GetVertexCount
Dim i As Long
For i = 0 To n - 1
Dim xyz As Variant
If Not transform Is Nothing Then
Dim v As SldWorks.MathPoint
Set v = swApp.GetMathUtility.CreatePoint(tess.GetVertexPoint(i))
Set v = v.MultiplyTransform(transform)
xyz = v.ArrayData
Else
xyz = tess.GetVertexPoint(i)
End If
Const fmt = "0.000000"
Print #1, "v "; Format(xyz(0) * scal, fmt); " "; Format(xyz(1) * scal, fmt); " "; Format(xyz(2) * scal, fmt)
Next i
Dim f As SldWorks.Face2
Set f = body.GetFirstFace
n = 0
While Not f Is Nothing
n = n + 1
Print #1, "g "; body.name; " "; f.GetFeature.name; " face"; n
Dim facets As Variant: facets = tess.GetFaceFacets(f)
For i = LBound(facets) To UBound(facets)
Dim fins As Variant: fins = tess.GetFacetFins(facets(i))
Debug.Assert (UBound(fins)) = 2 ' make sure we have only triangles
Dim pts(2) As Long ': ReDim pts(UBound(fins))
Dim j As Long
For j = LBound(fins) To UBound(fins)
Dim vert As Variant: vert = tess.GetFinVertices(fins(j))
pts(j) = vert(0)
Next j
Print #1, "f "; pts(0) + offset; pts(1) + offset; pts(2) + offset
Next i
Set f = f.GetNextFace
Wend
offset = offset + tess.GetVertexCount
Next b
End Sub
Private Function AddMaterial(name As String, properties As Variant) As Boolean
If name = "" Then Exit Function
If Not materials.Exists(name) Then
Call materials.Add(name, properties)
AddMaterial = True
End If
End Function
Private Sub ExportMTL(mtlfile As String)
Open mtlfile For Output As 1
Dim mat As Variant
For Each mat In materials
Print #1, "newmtl "; mat
Dim p As Variant: p = materials(mat) '[ R, G, B, Ambient, Diffuse, Specular, Shininess, Transparency, Emission ]
Dim r As Double: r = p(0)
Dim g As Double: g = p(1)
Dim b As Double: b = p(2)
Print #1, "Ka "; r * p(3); g * p(3); b * p(3) 'Ambient
Print #1, "Kd "; r * p(4); g * p(4); b * p(4) 'Diffuse
Print #1, "Ks "; r * p(5); g * p(5); b * p(5) 'Specular
'shininess ?
Print #1, "Tf "; r * p(7); g * p(7); b * p(7)
'emission ?
Next mat
Close 1
End Sub
|
||
| Layers | ||
| Category | macro, solidworks api | |
| Published: | ||
| Description: | SolidWorks macro to organise segments from an imported dxf/dwg by color on layers Imagine you get a large dxf or dwg which has been colorized by hand, without using layers. This macro will let you edit the drawing cleanly in SolidWorks, by placing all segments with the same color on specific layers. 'Layerize: SolidWorks macro [...] |
|
SolidWorks macro to organise segments from an imported dxf/dwg by color on layersImagine you get a large dxf or dwg which has been colorized by hand, without using layers. This macro will let you edit the drawing cleanly in SolidWorks, by placing all segments with the same color on specific layers.
'Layerize: SolidWorks macro to organise segments from an imported dxf/dwg by color on layers
'Author : Ph. Guglielmetti, (c) 2007, e-Systems Consulting Switzerland, all rights reserved
'Licence : you may use this macro for free, as long as this header is kept untouched.
'License : no support is provided, except for e-Systems customers
'Licence : it is forbidden to sell this code or publish it elsewhere without our permission
'Revision: 2007/01/30 PGu for AMBT
'Notes :
' 1) Don't forget to check "Microsoft Scripting Runtime" in References, needed for the Dictionary object
' 2) This macro is extremely slow if the drawing doc is visible. Minimize it when the macro runs to go faster
Sub main()
Dim swApp As SldWorks.SldWorks: Set swApp = Application.SldWorks
Dim doc As SldWorks.DrawingDoc: Set doc = swApp.ActiveDoc
Dim view As SldWorks.view: Set view = doc.GetFirstView
Dim sketch As SldWorks.sketch: Set sketch = view.GetSketch
Dim segs As Variant: segs = sketch.GetSketchSegments
Debug.Print UBound(segs)
Dim layermgr As SldWorks.layermgr: Set layermgr = doc.GetLayerManager
Dim layers As New dictionary
Dim s As Variant
For Each s In segs
Dim seg As SldWorks.SketchSegment: Set seg = s
Dim c As Long: c = seg.Color
If Not layers.Exists(c) Then ' create it
Dim name As String: name = "color " + Str(c)
Debug.Assert layermgr.AddLayer(name, "created by Layerize macro", seg.Color, seg.Style, seg.Width)
Call layers.Add(c, name)
Debug.Print "layer"; name; "created"
End If
seg.Layer = layers(c)
seg.LayerOverride = False
DoEvents
Next s
Debug.Print "finished"
End Sub
|
||
| ViewSize | ||
| Category | macro, solidworks api | |
| Published: | ||
| Description: | Macro to resize the model view for screen captures Saving your models as pictures for documentation ? Then you know the problem : the images will have 912×534 pixels one day and 1143×712 the day after. If you don’t want to edit your images in a second step, here is a macro that sets the [...] |
|
Macro to resize the model view for screen capturesSaving your models as pictures for documentation ? Then you know the problem : the images will have 912×534 pixels one day and 1143×712 the day after. If you don’t want to edit your images in a second step, here is a macro that sets the graphic area to a specified size:
'ViewSize : SolidWorks macro to size the view (for screen captures) 'Author : Ph. Guglielmetti, (c) 2004, DynaBits sārl Switzerland, all rights reserved 'Licence: you may use this macro for free, as long as this header is kept untouched. 'License: no support is provided, except for e-Systems customers 'Licence: it is forbidden to sell this code or publish it elsewhere without our permission 'Revision : 2004-01-12 PhG v 1.0 Tricky! : uses a WinAPI call to read the Frame's DIBSECTION size values Option Explicit Private Const fh As Long = 800 ' horizontal size in pixels Private Const fv As Long = 600 ' vertical size in pixels Private Declare Sub RtlMoveMemory Lib "kernel32" _
(ByVal pDest As Long, ByVal pSource As Long, ByVal cbCopy As Long) ' see function Peek below
Sub ViewSize() ' main
Dim swApp As SldWorks.SldWorks
Set swApp = Application.SldWorks
Dim doc As SldWorks.ModelDoc2
Set doc = swApp.ActiveDoc
Dim view As SldWorks.ModelView
Set view = doc.ActiveView
Call SetFrameSize(view, fh, fv)
End Sub
' works from SW2004. Before, ModelView::FrameHeight was only a Get property
Sub SetFrameSize(view As SldWorks.ModelView, fh As Long, fv As Long)
view.FrameState = swWindowNormal
Dim dib As Long
dib = view.GetViewDIB
Dim h As Long, v As Long
h = Peek(dib + 4, vbLong)
v = Peek(dib + 8, vbLong)
view.FrameWidth = fh + view.FrameWidth - h
view.FrameHeight = fv + view.FrameHeight - v
End Sub
Function Peek(Adresse As Long, VType As Long)
Dim cbCopy As Long
Select Case VType
Case vbByte
cbCopy = 1
Case vbInteger, vbBoolean
cbCopy = 2
Case vbLong, vbSingle
cbCopy = 4
Case vbDouble
cbCopy = 8
Case Else
Err.Raise 13
End Select
RtlMoveMemory VarPtr(Peek), VarPtr(VType), 4
RtlMoveMemory VarPtr(Peek) + 8, Adresse, cbCopy
End Function
|
||
| AddWeldMass | ||
| Category | macro, solidworks api | |
| Published: | ||
| Description: | Solidworks macro to add mass/weight custom properties for cut lists If you want to list weights of welded parts in a cut list, you’ll have to add properties to weldments by hand, one by one ? Here is a macro that does it automatically. 'AddWeldMass Solidworks macro to add a mass/weight custom property to each [...] |
|
Solidworks macro to add mass/weight custom properties for cut listsIf you want to list weights of welded parts in a cut list, you’ll have to add properties to weldments by hand, one by one ? Here is a macro that does it automatically.
'AddWeldMass Solidworks macro to add a mass/weight custom property to each weldment 'so that it can be displayed in a cut list 'Author : Ph. Guglielmetti, e-Systems Switzerland, all rights reserved 'Licence: you may use this macro for free, as long as this header is kept untouched. 'License: no support is provided, except for e-Systems customers 'Licence: it is forbidden to sell this code or publish it elsewhere without our permission 'Revision : PGu 2007/01/11 because I was tired to do this by hand ? Option Explicit Private Const propname As String = "POIDS" ' change to "MASS" or whatever you prefer Private Const proptype As String = "Texte" ' in english you must change to "Text". See comment in code? Sub AddMassProps() ' main
Dim swApp As SldWorks.SldWorks
Set swApp = Application.SldWorks
Dim doc As SldWorks.ModelDoc2
Set doc = swApp.ActiveDoc
'Traverse all features
Dim f As Feature: Set f = doc.FirstFeature
Do While Not f Is Nothing
If f.GetTypeName = "CutListFolder" Then ' not "SubWeldFolder" as captured by macro recorder ?
'the following API call is a typical example of mindless localization :
'the "proptype" string constant depends on the user language, which
'prevents the macro from running everywhere without adaptation !
'this was corrected in the Add2 call available from SW2007?
If f.CustomPropertyManager.Add(propname, proptype, Chr(34) + _
"SW-Mass@@@" + f.Name + "@" + doc.GetTitle + ".SLDPRT" + Chr(34)) Then
Debug.Print "Property "; propname; " added to feature "; f.Name
End If
End If
Set f = f.GetNextFeature
Loop
End Sub
|
||
| Scale Texture | ||
| Category | macro, solidworks api | |
| Published: | ||
| Description: | SolidWorks Macro to adjust texture scale to configurations sizes If you need to adjust the material texture to many different sizes (configurations) of a part, here is a macro for you: 'ScaleTexture : Solidworks macro to scale material texture on each config of current part 'so that it looks the same for different sizes of [...] |
|
SolidWorks Macro to adjust texture scale to configurations sizesIf you need to adjust the material texture to many different sizes (configurations) of a part, here is a macro for you: 'ScaleTexture : Solidworks macro to scale material texture on each config of current part 'so that it looks the same for different sizes of the part 'Author : Ph. Guglielmetti, e-Systems Switzerland, all rights reserved 'Licence: you may use this macro for free, as long as this header is kept untouched. 'License: no support is provided, except for e-Systems customers 'Licence: it is forbidden to sell this code or publish it elsewhere without our permission 'Revision : PGu 2007/01/11 Written for my colleague Arnaud who needed it for gem stones Option Explicit Dim swApp As SldWorks.SldWorks Dim part As SldWorks.PartDoc Sub ScaleTexture ()
Set swApp = Application.SldWorks
Set part = swApp.ActiveDoc
' find texture scale factor for current config
Dim texture As SldWorks.texture
Set texture = part.Extension.GetTexture(part.GetActiveConfiguration.Name)
Dim s As Double: s = texture.ScaleFactor * boxsize
' apply it to all configs
Dim confnames As Variant
confnames = part.GetConfigurationNames
Dim conf As Variant
For Each conf In confnames
Call part.ShowConfiguration(conf)
Set texture = part.Extension.GetTexture(conf)
If Not texture Is Nothing Then
Dim d As Double: d = boxsize
texture.ScaleFactor = s / d
End If
Debug.Assert part.Extension.SetTexture(conf, texture)
part.ViewZoomtofit2
DoEvents
continue:
Next conf
End Sub
' returns the part's size (diagonal of the bounding box) in current configuration
Function boxsize(Optional body_index As Integer = 0) As Double
Dim bodies As Variant
bodies = part.GetBodies(swSolidBody)
If IsEmpty(bodies) Then Exit Function ' no solid body ?
Dim box As Variant
box = bodies(body_index).GetBodyBox
boxsize = Sqr((box(3) - box(0)) * (box(3) - box(0)) + _
(box(4) - box(1))* (box(4) - box(1)) + _
(box(5) - box(2)) * (box(5) - box(2)))
End Function
|
||
| About DynaBits | ||
| Category | solidworks api | |
| Published: | ||
| Description: | DynaBits is now out of business. Read its story, achievements and my personal (bitter) thoughts about this defunct startup. History 1999/2 Ph. Guglielmetti starts his own business as a consultant for technical software (LabView, Matlab, …) 1999/6 reseller of MSC Working Model (Visual Nastran) 1999/10 first contact with SolidWorks through e-Systems 1999/12 purchase of source [...] |
|
DynaBits is now out of business. Read its story, achievements and my personal (bitter) thoughts about this defunct startup.
History
the Bottom lineDeveloping CAD add-ins is fun, but definitely doesn?t pay back because:
Ex-products
|
||

“RedLight” is a FREE add-in for SolidWorks to avoid (automatic) rebuilds and measure edit/idle time.
, right-click the window frame and check the “RedLight” toolbar.
