Adding FeatureScripts to your toolbar
How to add a custom feature to your toolbar?
ㅤ
- Open the Onshape document containing the custom feature.
- While viewing the Onshape document, click on the
icon near the top of the page.
- Select the custom feature from the list.
- The custom feature will be added to your toolbar for use in any document.
Looking for custom features? Check out our FeatureScript Library.
What’s New In the 2024 SOLIDWORKS API
The most notable news with the SOLIDWORKS 2024 release is the addition of the ability to save 2024 models to 2023 or 2022 versions. This entirely solves the complaint of lack of backwards compatibility that has generated countless complaints over the decades. This is interesting for me, personally, because in 2014 I wrote a tool called SolidTranslate that used the SOLIDWORKS API to translate models from newer to older versions. I didn’t release it for personal, legal, and business reasons, but the codebase lives on in other interoperability software that will be released at the end of this year. Stay tuned!
Now, onto the API… and not just the SOLIDWORKS API. This post will also cover the PDM API and Document Manager API. And if that’s not enough, I’m also going to cover back to 2020 for completeness’ sake, since the last time I did a “what’s new” post like this was in 2019. Before I do that, please note that this list only covers notable enhancements. You can see all additions and their related API calls in the Release Notes article in the API Help. You can find it in the local API Help by searching for “Release Notes” in the category tab. Note that the local API Help Release Notes will only be as up-to-date as the service pack you have downloaded.
New SOLIDWORKS API Calls and Interfaces
- 2020
- Support for opening and saving documents in SOLIDWORKS Connected.
- Sort cut list
- Explode multi-body parts
- Redesign of mass property API
- 2021
- API calls available to SOLIDWORKS Connected only.
- Get the type of 3DEXPERIENCE application that owns a given model.
- Get all of the unobscured drawing components in a drawing view of an assembly drawing.
- API calls available to SOLIDWORKS Connected only.
- 2022
- Creation of the SOLIDWORKS Inspection API.
- Support for belt/chain assembly features.
- Close and reopen a specified drawing document with an ExitDetailingMode option.
- Reload or replace a model document with a force reload option.
- Prompt users for the name of the file to open with options.
- 2023
- Many enhancements to sheet metal API calls. See here.
- Determine whether a configuration is a defeature configuration.
- 2024
- Access the configuration-specific custom property manager of cut-lists.
- Access the configuration-specific custom property manager of components.
- Retrieve errors that occurred during the last call to IFeatureManager::CreateFeature
- Set whether to save as a previous version during model save
New PDM API Calls and Interfaces
- 2020
- Extended search functionality includes the ability to:
- Create an extended search object. See IEdmVault21::CreateSearch2.
- Use new search syntax. See Search Syntax.
- Get whether a document has cut list items
- Get and set whether focus is on the data card view.
- Get whether a BOM row is a virtual component.
- Extended search functionality includes the ability to:
- 2021
- New interfaces for creating and modifying SOLIDWORKS BOMs.
- 2022
- Creation of the SOLIDWORKS PDM Professional Web API.
New Document Manager API Calls and Interfaces
- 2020
- Get how SOLIDWORKS Connected views this configuration.
- Gets the physical product represented by this configuration in SOLIDWORKS Connected.
- 2021
- Get the type of 3DExperience application that created this document.
Does anything we’ve covered stand out to you as particularly useful or exciting? If so then let us know in the comments!
Want to keep up with future CADSharp.com content and training events? Join our newsletter!
Event Handlers in SOLIDWORKS Addins
Written by Sean Stubbe
Introduction
Event handlers in SOLIDWORKS addins appear relatively straightforward to implement but they lack good documentation and I have not been able to find a full example online. There are also some caveats that can easily trip you up. Firstly, event handlers are called ‘Delegates’ in the SOLIDWORKS API and while there is a difference between events and delegates (see Delegates vs. events | Microsoft Docs), we will use the terms interchangeably in this article. You can find a full list of the events available in the Sldworks interface and its quite useful to browse them to see which events are available.
A common naming schema is used where every delegate starts with ‘D’ followed by the context in which they apply, and end with a ‘_’ suffix. For example, ‘DAssemblyDocEvents_DeleteItemPreNotifyEventHandler’ fires whenever an item is about to be deleted in an assembly. There are currently 8 interfaces in which events are implemented but note that most of them are directly available from ISldWorks.
- ISldWorks – application events
- IPartDoc – part events
- IAssemblyDoc – assembly events
- IDrawingDoc – drawing events
- IModelView – modelview events (graphics related)
- IMouse – mouse events (mouse moved, button pressed)
- IMotionStudy – (implemented in swmotionstudy namespace)
- ISWPropertySheet – property sheet events
- ITaskpaneView – taskpane events
- IFeatMgrView – feature manage design tree events (very limited)
Implementation Example
This example assumes we already have the boilerplate for a default C# Solidworks addin. The goal is to force new drawing views to use ‘Projected’ dimensions so we need to catch a ‘View Created’ event somehow and change the dimension type. It is a good example because it contains the boilerplate for implementing handlers and goes a littler further by demonstrating how to ‘chain’ events to access ones in specific contexts.
First, add a new class for the event handler logic. All of the following functions are added to this class.
using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System; internal class EventHandlers { }
Next, declare all the event handlers you wish to implement as private static members. Note that you may need to ‘chain’ events to get the desired functionality. In this example, we need to handle the ActiveModelDocChanged event to catch the AddItemNotifyEvent event in drawings. Note the OnModelDocChanged and OnDrawingFeatureCreated parameters – these are the functions will get called when the events fire.
private static DSldWorksEvents_ActiveModelDocChangeNotifyEventHandler modelChanged = new DSldWorksEvents_ActiveModelDocChangeNotifyEventHandler(OnModelDocChanged); private static DDrawingDocEvents_AddItemNotifyEventHandler drawCreateFeature = new DDrawingDocEvents_AddItemNotifyEventHandler(OnDrawingFeatureCreated);
Add a function to attach application level event handlers. This needs to be called from your main ConnectToSW() function. Note that the modelChanged event we created in the first step is referenced here.
public static void AttachEventHandlers(SldWorks swApp) { swApp.ActiveModelDocChangeNotify += modelChanged; }
Add a function to detach application level event handlers. This needs to be called from your main DisconnectFromSW() function. Note that the modelChanged event is removed and another function is called to remove other event handlers.
public static void DetachEventHandlers(SldWorks swApp) { swApp.ActiveModelDocChangeNotify -= modelChanged; DetachDocEventHandlers(); }
Next, add functions for attaching and detaching document level events. Note that we are only implementing a drawing event in this example but the full structure is shown so you can see where to add part and assembly event handlers as well.
private static void AttachDocEventHandlers() { ModelDoc2 swModel = Main.swApp.ActiveDoc; if (swModel != null) { switch ((swDocumentTypes_e)swModel.GetType()) { case swDocumentTypes_e.swDocPART: break; case swDocumentTypes_e.swDocASSEMBLY: break; case swDocumentTypes_e.swDocDRAWING: (swModel as DrawingDoc).AddItemNotify += drawCreateFeature; break; } } } private static void DetachDocEventHandlers() { ModelDoc2 swModel = Main.swApp.ActiveDoc; if (swModel != null) { switch ((swDocumentTypes_e)swModel.GetType()) { case swDocumentTypes_e.swDocPART: break; case swDocumentTypes_e.swDocASSEMBLY: break; case swDocumentTypes_e.swDocDRAWING: (swModel as DrawingDoc).AddItemNotify -= drawCreateFeature; break; } } }
Now we need to implement the functions we specified earlier and handle the events we attached to. The OnModelDocChanged() function is pretty simple and just adds the document event handlers in this example. This will fire every time the active model is changed.
private static int OnModelDocChanged() { AttachDocEventHandlers(); return 0; }
Finally, the OnDrawingFeatureCreated() function can be implemented to add the functionality we are looking for. This event fires every time a new feature is added to a drawing so we handle it and get the last feature added, check if its a view, and set the view to use projected dimensions if it is.
private static int OnDrawingFeatureCreated(int featureType, string featureName) { try { if (featureType == (int)swNotifyEntityType_e.swNotifyDrawingView) { ModelDoc2 swModel = Main.swApp.ActiveDoc; Feature swFeat = swModel.Extension.GetLastFeatureAdded(); View swView = swFeat.GetSpecificFeature2(); swView.ProjectedDimensions = true; } } catch (Exception ex) { MessageBox.Show("Unhandled Exception. " + ex.StackTrace); } return 0; }
Cancelling Events
Sometimes it is desirable to ‘cancel’ events to prevent users from performing certain commands or to redirect them to different functionality. This is usually supported for ‘Pre’ events but there are no solid rules as far as I can tell. You may have noticed that the handler functions return an integer and they return 0 in the example above. Returning 1 instead of 0 tells SOLIDWORKS that the ‘Pre’ event has failed and it will not proceed any futher, thus ‘cancelling’ the event. However, this will not work for every event. Another option that works in some cases is to throw a COMException. This exception will get passed to SOLIDWORKS and it will end the thread processing the event in some cases.