← LibrarySolidWorks Add-ins: Structure, Registration and DeploymentEngineering · ComputersLesson 10/10← PrevNext →
ArticlePublished 4 Aug 20269 min readBy Kevin JoginSolidWorks APIadd-insdeploymentCOM registration

Engineering / Computers / Part 9 of 9

Add-ins & Deployment

An add-in is the only delivery vehicle that makes automation feel like part of SOLIDWORKS rather than something bolted alongside it. It is also the only one that requires you to think seriously about registration, versioning and removal — which is precisely why it belongs at the end of the series rather than the beginning.

  • Part 9 · Deployment
  • Connect / disconnect
  • COM registration
  • Clean removal

KL-ENG-COMP-1509 · KEVOS® Knowledge Library · Australian English

An add-in is a library that SOLIDWORKS loads into its own process at start-up. It implements a small published contract, and in return it may add menus, toolbars, task panes and PropertyManager pages that behave exactly like the application's own. Everything from Parts 1 to 8 works unchanged inside it.

2Methods in the contract you must implement
1Unique identifier per add-in, permanently
2Registry locations involved in loading

01What an add-in actually is

Structurally it is a .NET class library, visible to COM, carrying a unique identifier, implementing the published add-in interface, and registered so that SOLIDWORKS knows to load it.

A class library Not an executable. It has no entry point of its own; SOLIDWORKS starts it.
Visible to COM SOLIDWORKS creates the object through COM, so the class must be exposed to it.
Carrying a unique identifier A globally unique identifier attached to the class, generated once and never changed for the life of the add-in.
Implementing the add-in interface Two methods: one called when SOLIDWORKS loads the add-in, one when it unloads it.
Registered Registry entries tell SOLIDWORKS the add-in exists, describe it in the add-ins dialogue, and record whether it loads at start-up.
Generate the identifier once

The unique identifier is the add-in's permanent identity. Changing it in a later release creates what the system regards as an entirely different add-in: the old entry remains registered and orphaned, and users may end up with both loaded. Generate it once, record it, and never edit it.

02The connect and disconnect contract

Two methods carry the whole lifecycle. Everything your add-in offers is created in the first and removed in the second.

C#the add-in contract
[ComVisible(true)]
[Guid("PUT-YOUR-OWN-GENERATED-IDENTIFIER-HERE")]
public class KevosTools : ISwAddin
{
    private ISldWorks      swApp;
    private ICommandManager cmdMgr;
    private int             addinCookie;

    public bool ConnectToSW(object thisSw, int cookie)
    {
        swApp       = (ISldWorks)thisSw;
        addinCookie = cookie;

        // Register this object to receive command callbacks.
        swApp.SetAddinCallbackInfo2(0, this, addinCookie);

        cmdMgr = swApp.GetCommandManager(addinCookie);
        BuildCommands();

        return true;      // false tells SOLIDWORKS the add-in failed to start
    }

    public bool DisconnectFromSW()
    {
        RemoveCommands();
        cmdMgr = null;
        swApp  = null;
        return true;
    }
}
thisSw
The application object, handed to you directly. No attaching is required — an add-in runs inside the session.
cookie
The identifier SOLIDWORKS assigns to this add-in for this session. Store it; the command manager and the callback registration both need it.
Return value
Reporting false tells SOLIDWORKS the add-in did not start. Use it — an add-in that fails silently is very difficult to diagnose from the outside.
Disconnect
Remove what you added and release references. Anything left behind can prevent the application closing cleanly.
Keep connect fast

Everything in the connect method runs while SOLIDWORKS is starting, and the user is watching a splash screen. Build the interface and nothing else. Loading configuration files, querying databases or checking for updates belongs on a background path or on first use, not here.

03Command groups and items

The command manager turns your methods into menu entries and toolbar buttons. A group holds items; a group becomes both a menu and a toolbar.

1Create a groupWith your own identifier, a title, a tooltip, a status-bar hint and a position.
2Assign iconsSupply the icon lists the group will use at the sizes the interface requests.
3Add itemsEach names the method to call and, optionally, a method that reports whether it should be enabled.
4ActivateNothing appears until the group is activated.
5Remove on disconnectRemove the group by its identifier so nothing is left behind.
Callbacks are resolved by name

The method invoked by a command item is identified by a string holding its name, resolved at run time. Rename or move the method and nothing fails to compile — the button simply stops working. Keep callback names in constants next to the item definitions, and treat renaming a callback as a change requiring a test.

Enable methods

Each item may name a second method that SOLIDWORKS calls to decide whether the command should currently be available. It returns a small integer describing both whether the item is enabled and whether it appears selected. This is how a command that requires an assembly greys itself out when a part is open — and it is far better user experience than an error message after the fact.

Icons

Older add-ins supply a single wide bitmap containing every icon side by side, indexed by position. Current releases accept lists of image files at several sizes, which is what you should use for anything new: interfaces scale, and a single low-resolution strip looks obviously wrong on a modern display. Supply every size the interface asks for.

04Registration

Registration does two things: it makes the class creatable through COM, and it tells SOLIDWORKS the add-in exists. Both happen when the library is registered, and the second is code you write yourself.

C#registration hooks
[ComRegisterFunction]
public static void RegisterFunction(Type t)
{
    // Describe the add-in to SOLIDWORKS, and set whether it loads at start-up.
    // Machine-wide entry:  HKEY_LOCAL_MACHINE\SOFTWARE\SolidWorks\AddIns\{guid}
    //   default value  1 = load at start-up, 0 = available but not loaded
    //   "Title"        the name shown in the add-ins dialogue
    //   "Description"  the explanatory line beneath it
    // Per-user entry:      HKEY_CURRENT_USER\Software\SolidWorks\AddInsStartup\{guid}
    //   1 = this user loads it at start-up
}

[ComUnregisterFunction]
public static void UnregisterFunction(Type t)
{
    // Remove both entries. Leaving them behind is what produces
    // "add-in not found" errors long after the file has gone.
}
What each registration entry controls
LocationScopeControls
Machine-wide add-ins keyAll usersThat the add-in exists, its title and description, and whether it is loaded at start-up by default
Per-user start-up keyThe current userWhether this particular user has it loaded at start-up — what the tick box in the add-ins dialogue writes
COM class registrationAll usersThat the class can be created at all. Written by the registration tool, not by your code
Architecture and privilege

Registration writes to a machine-wide location and therefore requires administrative privilege. It must also be performed by the 64-bit registration tool, since SOLIDWORKS is a 64-bit application. Using the 32-bit tool appears to succeed and produces an add-in that never appears in the dialogue — a failure with no error message anywhere.

05Removal and diagnosis

Removing an add-in cleanly matters more than it sounds, because the failure mode is a persistent error at every start-up on somebody else's machine.

  1. Unregister first, delete secondRunning the unregister step while the file is still present removes the entries properly. Deleting the file first leaves entries pointing at nothing, and SOLIDWORKS will complain at every start-up.
  2. Clear both locationsThe machine-wide entry and the per-user start-up entry are separate. Removing one leaves the other.
  3. Check for orphans after an identifier changeIf the identifier was ever changed, older entries remain and must be removed by hand.
  4. Verify in the dialogueThe add-ins dialogue is the plain check: the entry should be gone, with no error on restart.
Add-in failures and their usual causes
SymptomUsual cause
Not listed in the add-ins dialogueRegistered with the wrong architecture's tool, or registration was not run with sufficient privilege
Listed but will not loadAn exception in the connect method, or a dependency the add-in cannot find at the registered location
Loads, but no menu appearsThe command group was created but never activated
Buttons do nothingCallback name string no longer matches the method name
Error at every start-upRegistry entries pointing at a file that has been deleted
Two versions both loadedThe unique identifier was changed between releases
SOLIDWORKS will not closeReferences not released in the disconnect method

06Deploying to a team

The engineering is finished; the rollout is not. An add-in used by twenty people is a small piece of software with real deployment obligations.

Package it properly

An installer that places the files, registers with the correct architecture and privilege, and unregisters cleanly on removal. Manual registration on twenty machines will not stay consistent for long.

Version visibly

Put the version in the assembly, in the add-ins description and somewhere the user can read it. The first question about any defect is which version produced it.

Pin the release

Record which SOLIDWORKS release the add-in was built and tested against, and test before the business upgrades — not afterwards.

Fail visibly, not silently

Report a failed start-up to the user with something they can pass on. Silent failure turns into "the tool is unreliable", which is very hard to recover from.

Log to a known place

A log file in a predictable location is the difference between a five-minute diagnosis and a remote session.

Name an owner

Every deployed tool needs somebody responsible for it. An add-in whose author has left and whose source nobody can find is a liability sitting inside a critical process.

Where the series ends

The API is broad, and this series covers the spine of it: connecting, acting on documents and selections, presenting an interface, traversing structure, managing data, producing drawings and deploying the result. What separates useful automation from impressive automation is not more API surface — it is the discipline around it. Define the duty, verify against real cases, log what happened, and control the versions. That is ordinary engineering practice, applied to software.

07Quick reference

ISwAddin
The add-in contract. Two methods: connect and disconnect.
ConnectToSW(thisSw, cookie)
Called at load. Store the application object and the cookie, build the interface, return whether start-up succeeded.
DisconnectFromSW()
Called at unload. Remove the interface and release references.
ISldWorks::SetAddinCallbackInfo2
Registers the object that will receive command callbacks.
ISldWorks::GetCommandManager
The command manager for this add-in, obtained with the cookie.
ICommandManager::CreateCommandGroup2
Creates a group that becomes a menu and a toolbar.
ICommandGroup::AddCommandItem2
Adds an item naming the callback method and, optionally, an enable method.
ICommandGroup::Activate
Makes the group appear. Nothing shows without it.
ICommandManager::RemoveCommandGroup2
Removes a group by identifier, on disconnect.
ComVisible / Guid attributes
Expose the class to COM and give it its permanent identity.
ComRegisterFunction / ComUnregisterFunction
Hooks where the SOLIDWORKS registry entries are written and removed.
Add-in registry keys
A machine-wide entry describing the add-in, and a per-user entry controlling start-up loading.

Continue learning

SolidWorks Drawing Automation: Creation, Views and PrintingArticle · ComputersSolidWorks Custom Properties and Configurations Through the APIArticle · ComputersTraversing SolidWorks Assemblies and Feature TreesArticle · ComputersSolidWorks PropertyManager Pages: Building Native User InterfaceArticle · Computers