← LibrarySolidWorks API: Event and Notification ArchitectureEngineering · ComputersLesson 6/10← PrevNext →
GuidePublished 4 Aug 20266 min readBy Kevin JoginSolidWorks APIeventsnotificationsadd-in development

KEVOS® Knowledge Library · SolidWorks API Add-in Development

Event and Notification Architecture

Application events, per-document-type notifications and page callbacks — the three tiers of signal an add-in can receive, and the attach and detach discipline that keeps them from becoming defects.

01Executive summary

Notifications are the reason to build an add-in rather than a stand-alone client. They arrive in three tiers: application-level events about the session, document-level events about a specific open model, and interface callbacks from your own pages and commands. The tiers behave differently, and the difference that catches people out is lifetime — an application event source lives as long as the session, whereas a document event source lives only as long as that document is the one you have hooked.

Every handler you attach must be detached. Handlers left attached to a closed document, or attached twice because a document was reactivated, produce the two classic event defects: work that never happens, and work that happens twice.

02Three tiers of signal

Tier 01

Application events

Raised by the SolidWorks application object and broadcast to every loaded add-in. Active document changes, session-level file operations. Attach during connect, detach during disconnect.

Tier 02

Document events

Raised by a specific open document through a type-specific interface — one for parts, one for assemblies, one for drawings. Attach when a document becomes the one you are tracking; detach before you move on.

Tier 03

Interface callbacks

Raised by your own commands and pages, routed through the cookie and identifier model rather than through delegates. Covered in Parts 04 and 05.

03Application events and the tracking pattern

The application event most add-ins need first is the one announcing that the active document has changed. It is the trigger for re-pointing everything else the add-in is tracking.

C# — attaching and detaching an application eventIllustrative
private void AttachApplicationEvents()
{
    _sw.ActiveModelDocChangeNotify +=
        new DSldWorksEvents_ActiveModelDocChangeNotifyEventHandler(
            OnActiveModelDocChange);
}

private void DetachApplicationEvents()
{
    _sw.ActiveModelDocChangeNotify -=
        new DSldWorksEvents_ActiveModelDocChangeNotifyEventHandler(
            OnActiveModelDocChange);
}

// Notification handlers return an integer status; zero means
// handled without error.
private int OnActiveModelDocChange()
{
    DetachDocumentEvents();          // release the previous document
    _activeDoc = (IModelDoc2)_sw.ActiveDoc;
    AttachDocumentEvents();          // hook the new one
    RefreshInterface();
    return 0;
}
Broadcast, not addressed

Application events are sent to every add-in loaded in the session, not only to yours. Your handler should therefore make no assumption that it is the only party reacting, and should not depend on running before or after anyone else.

04Document events by document type

Document notifications are exposed through a different interface for each document type. The active document's type therefore has to be resolved before you can attach anything, which makes a type switch the natural shape of the attach method.

C# — attaching by document typeIllustrative
private swDocumentTypes_e _docType;

private void AttachDocumentEvents()
{
    if (_activeDoc == null) return;

    _docType = (swDocumentTypes_e)_activeDoc.GetType();

    switch (_docType)
    {
        case swDocumentTypes_e.swDocPART:
            _part = (PartDoc)_activeDoc;
            _part.NewSelectionNotify +=
                new DPartDocEvents_NewSelectionNotifyEventHandler(
                    OnPartSelection);
            break;

        case swDocumentTypes_e.swDocASSEMBLY:
            _assembly = (AssemblyDoc)_activeDoc;
            _assembly.NewSelectionNotify +=
                new DAssemblyDocEvents_NewSelectionNotifyEventHandler(
                    OnAssemblySelection);
            break;

        case swDocumentTypes_e.swDocDRAWING:
            _drawing = (DrawingDoc)_activeDoc;
            _drawing.NewSelectionNotify +=
                new DDrawingDocEvents_NewSelectionNotifyEventHandler(
                    OnDrawingSelection);
            break;
    }
}
Event sources by document type
Document typeEvent interface familyTypical signals consumed
PartPart document eventsSelection changed, feature added or modified, custom property changed, save and reload
AssemblyAssembly document eventsSelection changed, component added, suppression state changed, custom property changed
DrawingDrawing document eventsSelection changed, active sheet changed, view added or modified, sheet added

05Reading a selection safely

Selection notifications tell you that something changed, not what it is. Resolving the selected object is a separate step through the selection manager, and it is where most selection-handling defects live.

  1. Ask the type first

    Query the selected object's type before casting. It is cheaper than an exception and it lets you ignore selections you do not care about without any error handling at all.

  2. Cast defensively

    Where many selectable things can legitimately resolve to the type you want, an attempted cast inside a guard is more practical than enumerating every acceptable type.

  3. Handle nothing

    A cleared selection raises the notification too. Every handler needs a defined behaviour for having nothing selected.

  4. Return promptly

    The handler runs inside the host on the user's interaction path. Read what you need, update your interface, return.

C# — resolving a selectionIllustrative
private int OnAssemblySelection()
{
    var selMgr = (ISelectionMgr)_activeDoc.SelectionManager;

    var type = (swSelectType_e)selMgr.GetSelectedObjectType3(1, -1);
    if (type != swSelectType_e.swSelCOMPONENTS)
    {
        ClearComponentFields();
        return 0;
    }

    var component = (IComponent2)selMgr.GetSelectedObject6(1, -1);
    if (component == null) return 0;

    ShowComponent(component);
    return 0;
}
Lightweight components

A component that is loaded lightweight will not always yield its underlying document object, so code that reaches through a selected component to read its properties can fail on exactly the assemblies where performance mattered enough to load them lightweight. Detect the condition and either skip the component or offer to resolve it — do not let it surface as an exception.

06Handler hygiene

Rule 01Detach before you re-attach. Every document change should release the previous document's handlers before hooking the new one, or handlers accumulate and work happens more than once.
Rule 02Detach before you null. A handler keeps its event source alive. Nulling the field without detaching leaks the document.
Rule 03Never throw from a handler. The exception unwinds inside the host, on the user's interaction path.
Rule 04Return the status value. Notification handlers return an integer; return zero rather than falling off the end.
Rule 05Keep handlers idempotent. Assume the same notification can arrive twice and make the second arrival harmless.
Rule 06Mirror in disconnect. Whatever the document-change path attaches, the disconnect path must be able to detach.

07Choosing which events to consume

The available notification surface is far larger than any one add-in needs. Selecting a minimal set is a design decision worth making explicitly.

Common notification requirements and where they are met
RequirementTierNotes
React when the user switches documentApplicationThe anchor event for almost every stateful add-in
Track what the user has selectedDocumentType-specific; resolve the object through the selection manager
Follow the active drawing sheetDocumentPair with a control on your page so selection stays synchronised in both directions
Notice a document being reloadedDocumentNeeded or your cached model reference becomes stale after a reload
Notice a save-as that renames the documentDocumentAny interface element displaying the file name must be refreshed
Notice a custom property changeDocumentRequired if your page both reads and writes the same property
Two-way synchronisation

When a page control mirrors a model state — a drop-down of drawing sheets, for example — the synchronisation has to run in both directions: the notification updates the control, and the control's callback updates the model. Build both halves at the same time, and guard against the update loop where each triggers the other.

08Quick reference

Tiers
Application events, document events, interface callbacks.
Anchor event
Active document change — detach old handlers, re-point, attach new handlers, refresh.
Document interfaces
Separate event interface families for parts, assemblies and drawings.
Handler signature
Notification handlers return an integer; return zero for handled without error.
Selection
Notification says something changed; the selection manager says what.
Hygiene
Detach before re-attach, detach before null, never throw, stay idempotent.

09Where this leads

Continue in this pathway

Continue learning

SolidWorks API: Property Manager Pages and the Control ModelGuide · ComputersNEXT LESSON →SolidWorks API: Add-in, Stand-alone or HybridGuide · ComputersSolidWorks API: Command Manager, Menus and ToolbarsGuide · ComputersSolidWorks API: Planning, Structure and Debugging DisciplineGuide · Computers