To use the SOLIDWORKS API with C#, you create a .NET Framework class library, reference the SOLIDWORKS interop assemblies (SolidWorks.Interop.sldworks, swconst and swpublished), implement the ISwAddin interface with its ConnectToSW and DisconnectFromSW methods, and register the DLL for COM with regasm /codebase using the 64-bit tool. SOLIDWORKS then loads your add-in at startup and you can add menu and toolbar commands that call the same API you used in VBA. This is Part 2 of our beginner series. Part 1 wrote a VBA macro that reads and writes custom properties; here we turn that into a C# add-in.
When to move from VBA to C
VBA is the right place to start, but it has limits. These are the signals we look for when advising teams:
| Situation | Stay in VBA | Move to C# |
|---|---|---|
| One user, one task, under a few hundred lines | Yes | |
Code shared across many macros (copy and paste between .swp files) |
Yes | |
| Need source control, code review, automated builds | Yes | |
| Rich UI: task panes, property manager pages, WPF or WinForms dialogs | Yes | |
| React to events (document opened, saved, rebuilt) all session long | Yes | |
| Integrate with databases, web services, SOLIDWORKS PDM | Yes |
C# also gives you a modern editor (Visual Studio), proper debugging, NuGet packages and a much larger talent pool. If you are still choosing between VB.NET and C#, our beginner’s guide to C#, VBA and VB.NET for SOLIDWORKS compares them. Everything below works in VB.NET too; only the syntax changes.
Standalone exe vs add-in
There are two ways to run C# code against SOLIDWORKS.
Standalone application
A console or Windows app that connects to SOLIDWORKS from outside:
var swApp = (ISldWorks)Activator.CreateInstance(
Type.GetTypeFromProgID("SldWorks.Application"));
swApp.Visible = true;
This is good for batch jobs and tools launched from a scheduler or another application. The cost: every API call crosses a process boundary, which makes chatty code (loops over thousands of entities) noticeably slower, and you are responsible for starting and shutting down SOLIDWORKS cleanly.
Add-in
A DLL that SOLIDWORKS loads into its own process. Calls are in process and fast, you can add commands to menus, toolbars and the CommandManager, and you can subscribe to application and document events. This is what users see listed under Tools > Add-Ins.
For interactive tools that users click on, an add-in is the right choice. For unattended batch processing, a standalone exe (or a PDM task) is often better.
Setting up a SOLIDWORKS C# project
- In Visual Studio, create a Class Library (.NET Framework) project. SOLIDWORKS add-ins run on the .NET Framework, so target a 4.x version, not .NET 6 or later.
- Set the platform target to x64. SOLIDWORKS is 64-bit.
- Add references to the three interop assemblies listed below. You will find them in the
api\redistfolder of your SOLIDWORKS installation. - For each interop reference, set Embed Interop Types to
False. Embedding can cause casting problems with some SOLIDWORKS interfaces. - In project properties, under Assembly Information, tick Make assembly COM-Visible, or mark your add-in class with
[ComVisible(true)].
| Interop assembly | What it contains |
|---|---|
SolidWorks.Interop.sldworks.dll |
The main object model (ISldWorks, IModelDoc2, and so on) |
SolidWorks.Interop.swconst.dll |
Enumerations (swDocumentTypes_e, swCustomInfoType_e) |
SolidWorks.Interop.swpublished.dll |
Interfaces you implement, including ISwAddin |
The ISwAddin interface: ConnectToSW and DisconnectFromSW
ISwAddin has only two methods:
ConnectToSW(object ThisSW, int Cookie): called when SOLIDWORKS loads your add-in.ThisSWis the application object (your newswApp) andCookieidentifies your add-in in later calls. Returntrueif you loaded successfully.DisconnectFromSW(): called when the add-in is unloaded or SOLIDWORKS closes. Remove your UI, unsubscribe from events and release COM objects here.
Here is a minimal add-in with one command that does what our Part 1 macro did: set a CheckedBy property on the active document.
using System;
using System.Runtime.InteropServices;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using SolidWorks.Interop.swpublished;
[ComVisible(true)]
[Guid("6B1C2E7A-3F4D-4E8B-9A21-5C0D7E9F1A23")]
public class CheckedByAddin : ISwAddin
{
private ISldWorks swApp;
private ICommandManager cmdMgr;
private int cookie;
private const int GroupId = 1;
public bool ConnectToSW(object ThisSW, int Cookie)
{
swApp = (ISldWorks)ThisSW;
cookie = Cookie;
swApp.SetAddinCallbackInfo2(0, this, cookie);
cmdMgr = swApp.GetCommandManager(cookie);
int err = 0;
ICommandGroup grp = cmdMgr.CreateCommandGroup2(GroupId, "Blue Byte Tools",
"Blue Byte Tools", "", -1, true, ref err);
grp.AddCommandItem2("Set CheckedBy", -1, "Set CheckedBy property",
"Set CheckedBy", 0, "SetCheckedBy", "", 0,
(int)(swCommandItemType_e.swMenuItem | swCommandItemType_e.swToolbarItem));
grp.HasToolbar = true;
grp.HasMenu = true;
grp.Activate();
return true;
}
public bool DisconnectFromSW()
{
cmdMgr.RemoveCommandGroup(GroupId);
Marshal.ReleaseComObject(cmdMgr);
cmdMgr = null;
Marshal.ReleaseComObject(swApp);
swApp = null;
GC.Collect();
GC.WaitForPendingFinalizers();
return true;
}
public void SetCheckedBy()
{
var model = swApp.ActiveDoc as IModelDoc2;
if (model == null) { swApp.SendMsgToUser("Open a document first."); return; }
ICustomPropertyManager props = model.Extension.CustomPropertyManager[""];
int ret = props.Add3("CheckedBy", (int)swCustomInfoType_e.swCustomInfoText,
Environment.UserName, (int)swCustomPropertyAddOption_e.swCustomPropertyReplaceValue);
if (ret == (int)swCustomInfoAddResult_e.swCustomInfoAddResult_AddedOrChanged)
model.SetSaveFlag();
}
}
A few things to notice:
SetAddinCallbackInfo2tells SOLIDWORKS which object receives callbacks. The string"SetCheckedBy"inAddCommandItem2is the name of a public method on that object.- Generate your own GUID (Visual Studio: Tools > Create GUID). Never reuse one from a sample, or two add-ins will collide.
- The command logic is almost identical to the VBA version. The API is the same; only the language changed.
A production add-in also handles icons (image lists for the toolbar) and checks whether the command group already exists with different items. The official add-in templates and samples in the API Help show both.
COM registration: regasm /codebase, 64-bit
SOLIDWORKS discovers add-ins through COM and the registry, so two things must happen.
Register the DLL for COM
Use the 64-bit RegAsm from an elevated prompt:
& "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe" /codebase "C:\Tools\CheckedByAddin\CheckedByAddin.dll"
The Framework64 part matters. The 32-bit RegAsm writes to the wrong registry view and SOLIDWORKS will never see your add-in (registration errors such as Error creating the add-in COM object from the DLL come up regularly on CADOverflow). /codebase records the DLL’s path, which is needed for assemblies that are not in the GAC (RegAsm warns about unsigned assemblies; signing with a strong name removes the warning).
Tell SOLIDWORKS it is an add-in
SOLIDWORKS lists add-ins from a key named after your GUID under HKEY_LOCAL_MACHINE\SOFTWARE\SolidWorks\Addins, with Title and Description values, and optionally a key under HKEY_CURRENT_USER\Software\SolidWorks\AddInsStartup to load it at startup. The usual practice is to write these keys in methods marked with [ComRegisterFunction] and [ComUnregisterFunction], so regasm creates and regasm /u removes them automatically.
We walk through the full process, including common mistakes, in how to register a SOLIDWORKS add-in DLL (64-bit).
Tip: during development, set Start external program in the project’s Debug settings to
SLDWORKS.exe. Press F5 and Visual Studio starts SOLIDWORKS with the debugger attached to your add-in.
Releasing COM objects
Every SOLIDWORKS object you touch from .NET is a COM object wrapped by a runtime callable wrapper. The garbage collector releases these eventually, but “eventually” is the problem in a long-running add-in.
Practical rules:
- Do not hold references to documents, features or entities longer than you need them. Store IDs or names, not objects, between commands.
- Release objects you created in loops (for example while traversing thousands of components) with
Marshal.ReleaseComObjectwhen you are done with them. - In
DisconnectFromSW, release your stored references, set them tonull, and force a collection, as in the sample above. If you skip this, SOLIDWORKS may keep running in the background after the user closes it. - Unsubscribe from every event you subscribed to.
Unreleased COM objects can lead to resource leaks and, in bad cases, crashes. We dig into one such case in memory access violations caused by GDI object count and unreleased COM objects.
Migrating your VBA habits
Most VBA knowledge transfers directly. The differences that trip people up:
| VBA | C# |
|---|---|
Set swModel = swApp.ActiveDoc |
var model = swApp.ActiveDoc as IModelDoc2; |
| Enum names used directly | Cast to int: (int)swDocumentTypes_e.swDocPART |
| Output parameters passed normally | out or ref arguments, as shown in the member’s C# syntax |
Properties with arguments, Extension.CustomPropertyManager("") |
Indexer syntax, Extension.CustomPropertyManager[""] |
Late binding with As Object works |
Always use the typed interfaces |
That last point is why we push early binding even in VBA: macros written with typed declarations translate to C# almost line for line. See early binding vs late binding.
Next steps
From here, the typical path is:
- Add a second command and organize the code so each command lives in its own class.
- Subscribe to
ISldWorksevents such as active document changes, and to document events like file save. - Build a task pane or property manager page for input.
- Create an installer that registers the add-in on user machines.
If your team prefers a structured path, our training takes developers from VBA macros to production C# add-ins with exercises based on real customer projects. Get in touch to ask about it.
Community discussions
- Add-in installer for SOLIDWORKS add-ins on CADOverflow
- Creating installer for SOLIDWORKS add-in with WiX on CADOverflow
- Add logging to a SolidWorks add-in on CADOverflow
- C# addin not loading on the SOLIDWORKS Forum
FAQ
Can I use .NET 8 for a SOLIDWORKS add-in?
SOLIDWORKS add-ins are built on the .NET Framework (4.x). Target the .NET Framework for in-process add-ins. A separate standalone application can use other runtimes, but that adds complexity most teams do not need.
Why does my add-in not appear in Tools > Add-Ins?
Usually the DLL was registered with the 32-bit RegAsm, the add-in registry key under SolidWorks\Addins is missing, or the class is not COM visible. Re-register with the Framework64 RegAsm from an elevated prompt.
Do I need a license to use the SOLIDWORKS API from C#?
The SOLIDWORKS API is available with any licensed SOLIDWORKS seat. You do not need an extra license to build add-ins. The Document Manager API is the exception and requires a key.
Should I start with a standalone exe or an add-in?
For tools users click on inside SOLIDWORKS, start with an add-in. For unattended batch jobs, a standalone program is simpler to schedule.
Need help with this?
If you want help building or reviewing a SOLIDWORKS add-in, or want your team trained on the SOLIDWORKS API, contact us. If your automation is really about vault data rather than CAD geometry, PDMShell may get you there without writing an add-in at all.