Engineering / Computers / Series overview
SolidWorks API Programming & Automation
Every engineering office carries a tax it never records: the hours spent repeating work a computer could do exactly, every time, without fatigue. This nine-part reference sets out how the SOLIDWORKS API is structured, what it can reach, and how to build automation an engineering business can actually depend on.
- 9-part series
- Engineering · Computers
- Object model · API help
- Macro → add-in path
KL-ENG-COMP-1500 · KEVOS® Knowledge Library · Australian English
The SOLIDWORKS API is a COM interface that exposes almost everything the application can do to an external program. Anything a user can click, a program can generally call — create documents, drive dimensions, mate components, read and write custom properties, generate drawings, export files and extend the user interface itself.
What the API does not supply is engineering judgement. Automation multiplies whatever process it is pointed at, including a bad one. This series therefore treats API programming the way KEVOS® treats any capital process: define the duty first, choose the smallest mechanism that meets it, verify against real cases, and design for the day the release changes underneath you.
01Where automation actually pays
Automation earns its keep where a task is frequent, rule-governed and error-prone by hand. Where any one of those three is missing, the payback usually is too.
Repetitive output generation
Exporting every sheet of every drawing to DXF or PDF on a release; producing a standard drawing from a model; renaming and filing outputs to a naming convention. The rules are fixed and the volume is real.
Data integrity across a set
Checking that every configuration of every part carries the custom properties your ERP or PDM expects, and correcting the ones that do not. Humans are poor at auditing hundreds of near-identical records; software is excellent at it.
Enforcing a standard
Applying a company material list, a title-block rule or a mate convention consistently. The value is not the keystrokes saved — it is the variance removed.
One-off geometry work
Modelling a bespoke part through the API is almost always slower to write than to model by hand, and far harder to change.
Tasks that need judgement
If the rule cannot be written down without the word "usually", the process is not ready to be automated. Fix the process first.
Unstable inputs
Automation against inconsistent legacy files spends its life in exception handling. Clean the data or scope the tool to the subset that is clean.
Estimate payback in rework avoided, not minutes saved. A DXF exporter that removes a whole class of "wrong revision issued to the laser cutter" events is worth more than its time saving suggests, because the cost it removes is a scrap-and-reissue cost, not a labour cost.
02The object model in one page
Nearly every API session follows the same shape: acquire the application object, ask it for a document, then ask the document for the specialised managers that do the real work. Learn this spine and the rest of the API becomes navigable.
ISldWorks
The application itself. One per running session. Source of the active document,
new documents, the command manager, user preferences and selection filters.IModelDoc2
Any open document, whatever its type. Title, path, save state, rebuild, selection
manager, configurations, summary information.IPartDoc · IAssemblyDoc · IDrawingDoc
Type-specific behaviour. Materials and bodies; mates and components; sheets and
views. You obtain these by casting the same document handle.IModelDocExtension
The overflow interface. Newer capability is added here rather than to
IModelDoc2 — selection by identifier, custom property managers,
printing, mass properties, save operations.ISelectionMgr
What the user has picked, in what order, under which mark.IConfiguration → IComponent2 → IFeature
The route into an assembly tree. Configuration first, because components and
suppression states are configuration-specific.ICustomPropertyManager
Document-level or configuration-specific metadata — the bridge between CAD
and every downstream business system.The published reference documents interfaces with an I prefix
(ISldWorks, IModelDoc2). In VBA and in .NET you will commonly
declare the un-prefixed co-class name instead. They describe the same thing; the prefix is
a documentation convention, not a different object.
03Three ways to deliver the same logic
The same fifty lines of API code can be shipped three different ways. The choice is a deployment decision, not a programming one, and it should be made before the first line is written.
| Criterion | Recorded / VBA macro | Stand-alone .NET client | Add-in |
|---|---|---|---|
| Lives where | A .swp file on disk or a shared drive | An executable run from Windows | A registered library loaded by SOLIDWORKS at start-up |
| Starts how | User runs it from the macro menu or a toolbar button | User launches the program, which attaches to the session | Appears as a menu, toolbar or task pane inside SOLIDWORKS |
| Best for | Personal shortcuts, prototypes, proving a sequence works | Batch work over many files, jobs run outside the modelling session | Anything a whole team uses daily |
| User interface | Basic dialogs only | Full application windows | Native PropertyManager pages and command groups |
| Deployment effort | Copy a file | Copy or install an executable | Registration required on each machine; version control matters |
| Maintenance risk | High — copies diverge silently | Moderate | Lowest once a release process exists |
A macro that proves useful gets emailed around, edited locally, and within a year six incompatible versions are in circulation with no record of which produced which drawing. Decide early whether a tool is personal or organisational. If it is organisational, it needs a home, a version number and an owner — the same governance any other engineering artefact receives.
04The one skill worth learning first
Reading the API reference fluently is worth more than memorising any number of code samples. Four conventions unlock most of it.
1 · The trailing digit is a version, not a variant
Methods ending in a number — SaveAs3, Add3,
Get6, SelectByID2, AddMate5 — are successive
revisions of the same call. Each new version usually adds arguments and leaves the older
one in place for compatibility. Always write against the highest-numbered variant
your target release exposes, and record which release that is; it is the single
most common reason code that worked last year fails to compile this year.
2 · Enumerations carry the meaning
Integers returned and accepted by the API are almost always members of a named
enumeration — swDocumentTypes_e, swSaveAsOptions_e,
swSelectType_e, swCustomInfoType_e. Reference the enumeration
member by name rather than the literal value. The literal will be correct and unreadable;
worse, it will still compile after the meaning changes.
3 · Option arguments are bit flags
Where the help lists several options for one argument, they are designed to be combined with a bitwise OR. A silent, copy-mode save is one argument holding two flags, not two calls.
4 · Errors arrive as output parameters
Many calls report success through arguments passed by reference rather than through the return value. A save operation that appears to succeed may have set a warning code you never read. Capture them, test them, and log them.
Before writing any new call, open its reference page and read three things in this order: the argument list, the remarks section, and the release in which it was introduced. The remarks section is where the behaviour that will surprise you is documented.
05The nine parts
Each part is a self-contained reference. Read in order for a learning path, or jump directly to the capability you need.
Macro Fundamentals
What the recorder captures and what it silently omits; reading a recorded macro; writing one from scratch; document creation and saving; why recorded code is evidence rather than architecture.
Connecting from Visual Studio
Interop references and the settings that trip everyone up; attaching to a running session; starting one; casting rules; COM object lifetime and release discipline.
First Automation Tasks
The guard preamble every tool needs; batch export of drawing sheets; save options and error codes; reading document information; the system-units trap.
Working with Selections
Selection as a contract with the user; marks and ordering; identifying picked entities; mating, materials and dimension values; programmatic selection and filters.
PropertyManager Pages
Building native user interface inside SOLIDWORKS: the handler interface, control identifiers, page options, groups and controls, and the event lifecycle.
Traversing Assemblies & Features
Recursive component traversal, the feature and sub-feature chain, filtering by type name, suppression states, and presenting a tree the user recognises.
Custom Properties & Configurations
Document-level versus configuration-specific metadata, adding, updating, deleting and auditing properties, and why this is the highest-value automation in most businesses.
Drawing Automation
Creating drawings from templates, standard view sets, walking sheets and views, counting and auditing, and printing with real control over ranges and devices.
Add-ins & Deployment
The add-in contract, connect and disconnect, command groups and icons, COM registration and the registry entries involved, clean removal and rollout.
06A suggested learning path
- Record something trivial and read itCreate and save an empty part with the recorder running, then open the result. The goal is not the code — it is recognising the boilerplate you will see in every example from now on.
- Write one macro without the recorderOpen a document, check its type, report its title. Small, but it forces you to set references and handle the case where nothing is open.
- Move the same logic into a .NET projectThe code barely changes; the packaging, casting and error handling all do. This is where most of the friction lives, so meet it early on something you already understand.
- Automate one real, annoying task end to endBatch DXF export is the classic choice because the rules are unambiguous and the benefit is immediate.
- Add a proper user interfaceA PropertyManager page turns a personal script into something a colleague will use without being taught.
- Traverse, audit and reportWalk an assembly, collect what you find, and write a report. Auditing tools are low-risk, high-value, and they make the case for further automation with evidence.
- Package it as an add-inOnly once the logic is proven. Deployment is a separate discipline and deserves its own attention.
07Governance: making automation dependable
A macro that works on the author's machine is a demonstration. The difference between that and a tool the business can rely on is a short, unglamorous list.
Record the target release
State in the source header which SOLIDWORKS release the tool was written and tested against. When a call disappears or a suffix increments, this is the first thing anyone needs to know.
Fail loudly, never silently
Check every handle before use and every error output after use. An automation tool that quietly skips a file is worse than one that stops, because nobody finds out until the file is needed.
Keep a log
Write what was processed, what was skipped and why, with timestamps. This converts "the exporter is broken" into a diagnosable statement, and it is the evidence trail an audit will ask for.
Make it idempotent
Running the tool twice should produce the same result as running it once. Anything that appends, increments or renames on each pass will eventually be run twice.
Restore the user's state
If you clear a selection, change a configuration or open documents, put things back. Users who lose work to a tool stop using it, and tell others.
Test against ugly data
Validate on real legacy files, not the clean model you built for the purpose. The exceptions are the specification.
Treat an automation tool as a controlled engineering document. Version it, note what changed, and keep the superseded version retrievable. If a tool produced a manufacturing output, you must be able to say later which version produced it.
08Quick reference
| Interface | Responsibility | Typically obtained from |
|---|---|---|
| ISldWorks | The application session | The programming environment, or a COM attach from an external program |
| IModelDoc2 | Any open document | ActiveDoc, NewDocument, OpenDoc6 |
| IModelDocExtension | Newer document capability | The Extension property of a document |
| IPartDoc | Part-specific behaviour, materials, bodies | Cast from a document of part type |
| IAssemblyDoc | Components and mates | Cast from a document of assembly type |
| IDrawingDoc | Sheets and views | Cast from a document of drawing type |
| ISelectionMgr | What is currently selected | The SelectionManager property of a document |
| IConfiguration | A named configuration and its tree root | GetActiveConfiguration |
| IComponent2 | One instance in an assembly tree | GetRootComponent, then GetChildren |
| IFeature | One entry in the feature tree | FirstFeature, then GetNextFeature |
| ICustomPropertyManager | Document or configuration metadata | Extension.CustomPropertyManager |
| ICommandManager | Menus and toolbars added by an add-in | GetCommandManager, using the add-in cookie |
