Rev # | Date | Description |
---|---|---|
1.0 | Dec 2023 | New document. |
Note
All SolidPractices are written as guidelines. It is a strong recommendation to use these documents only after properly evaluating your requirements. Distribution of this document is limited to Dassault Systèmes SolidWorks employees, VARs, and customers that are on active subscription. You may not post this document on blogs or any internal or external forums without prior written authorization from Dassault Systèmes SolidWorks Corporation.
This document was updated using DraftSight 2023 SP4. If you have questions or need assistance in understanding the content, please get in touch with your designated reseller.
Acknowledgments
This document was authored by CADSharp LLC and reviewed by Dassault Systèmes SolidWorks Corporation.
- Preface
The DraftSight API is a key feature of the software. It allows users with programming skills to automate tasks within DraftSight, much like the SOLIDWORKS API. This SolidPractices document provides a practical starting point for working with the DraftSight API and offers best practices to streamline development.
Your Feedback Requested
We would like to hear your feedback and suggestions for new topics. After reviewing this document, please take a few minutes to fill out a brief survey. Your feedback will help us create the content that directly addresses your challenges.
- Introduction
The DraftSight API is a powerful tool that enhances the capabilities of DraftSight, a popular 2D computer-aided design (CAD) software. This application programming interface (API) serves as the bridge between the DraftSight application and developers. It offers the means to automate tasks and create custom solutions, extending the software functionality to meet specific needs.
With the DraftSight API, users with programming expertise can tailor the software according to their requirements, making it a versatile tool for a wide range of industries and applications. Whether you are in engineering, architecture, manufacturing or any other field that relies on CAD, the DraftSight API provides the flexibility to streamline workflows and unlock the full potential of your CAD projects.
This introductory guide to the DraftSight API walks you through the fundamentals, helping you harness the power of automation and customization within DraftSight. The document explores key concepts, practical examples and best practices that allow you to make the most of this powerful feature. Whether you are a seasoned developer or new to the world of CAD customization, this resource serves as a valuable starting point for your journey with the DraftSight API.
- Usage Contexts and Supported Languages
One of the first things to do when developing with DraftSight is to decide on a programming language and application type. It is worth noting that many users first exposure to DraftSight customization or automation is with scripts or LISP. Both are suitable for simple use cases where you only need to automate a few commands or add some logic. However, these methods are limited and cannot take full advantage of the API, and are therefore outside the scope of this document. Instead, the following chart shows the primary supported languages and usage contexts. Complexity goes from left to right and top to bottom. Accordingly, VBA macros are the simplest and C++ native apps are the most complex. Prior experience with a particular language or platform affects this as well.
This chart applies to Windows. The MacOS and Linux only support C++ and JavaScript.
VBA | VB.NET/C# | JavaScript | C++ | |
---|---|---|---|---|
Macro | ✔ | ✔ | ✔ | ✔ |
Add-in | X | ✔ | X | ✔ |
Desktop App | X | ✔ | X | ✔ |
Web App | X | X | ✔ | X |
- Programming Languages
Microsoft® Visual Basic® for Applications (VBA) is beginner-friendly and offers an easy way to start programming with the DraftSight API. VBA only supports macros, which limit its usefulness. However, previous experience with the development of SOLIDWORKS macros or Microsoft Office® macros shorten the learning curve.
The two .NET framework languages, VB.NET and C#, are the most common programming languages used for DraftSight customization or automation. Between the two, C# is the recommendation because it is more capable. VB.NET is capable as well and is better suited for those with limited programming experience.
The DraftSight API also supports JavaScript, with some limitations. This is useful for developers who are more comfortable with web technologies or when a web application is preferable.
For advanced developers requiring low-level control, DraftSight offers a C++ API, in both standard and COM native contexts. This option is suitable for building complex extensions and integrations, enabling the implementation of highly specialized features or smooth interaction with other software systems.
- Application Types
Starting with the DraftSight API is made simple with macros, which you can conveniently create within the DraftSight application using the macro recorder. This is a good way to learn the API. However, macros do not always yield the most efficient results, particularly for larger or widely distributed projects. DraftSight supports various programming languages for macros, but VBA is the common choice. Unlike some other software, DraftSight lacks an integrated development environment (IDE). While you can edit VBA scripts in any text editor, the recommendation is to use the VBA IDE within SOLIDWORKS or Microsoft Office applications that support it, such as Word or Excel®. This offers benefits such as code completion, syntax highlighting and debugging tools.
Add-ins are plugins or extensions that enhance the capabilities of DraftSight. They are the most common use of the DraftSight API and are useful for adding new user interfaces, commands and custom event handlers. The simplest route is to develop these in a .NET language (VB.NET or C#), with C# being a recommendation. C++ is also supported for use cases that require low-level integration or performance.
You can also use the DraftSight API as a stand-alone application. This is useful when you need to control DraftSight outside the context of the program itself. A typical use case is the automation of batch tasks. For example, you might have hundreds or thousands of drawings for which you want to update the title block. It is possible to create a stand-alone application run DraftSight and process them automatically. You can also accomplish this in an add-in, however, the stand-alone application can help you better handle exceptions in DraftSight and perhaps run multiple instances to improve performance. You can develop stand-alone applications with VB.NET, C# and C++. C# is the authors’ recommendation.
While less common, web applications that interact with DraftSight provide remote access to CAD features through web browsers. The use cases for this are niche, but one example is sending data from a web application to DraftSight running on your desktop. The use of JavaScript is supported, so some developers might prefer to use this instead of developing a .NET stand-alone application or add-in.
- Key Takeaways
- Macros are great for learning and simple solutions that are not widely deployed.
- Add-ins are powerful extensions that make it possible to add new functionality into DraftSight.
- Standalone applications are ideal for automating batch processes and facilitating external control.
- Web applications provide another way to access the DraftSight API when preferred or required.
- API Documentation
You can access the DraftSight API documentation online at help.solidworks.com or locally from within the DraftSight application as shown in the following image. This is the best resource for learning and using the DraftSight API. If you are in a hurry, searching for your exact problem on the internet often yields results from the official forum and other websites. As with most software development challenges, the hard part is knowing what to ask.
When reading through the documentation, especially for the first time, start with the “Welcome” and “Getting Started” topics. These topics explain the technical details of the supported languages and application types, and provide actionable steps for getting started with the application and the language of your choice. Next, it is worth reading the “Release Notes” topic every time you upgrade to a newer version of DraftSight, to see what has changed in the API. Finally, the “Interop.dsAutomation Namespace” topic serves as a jumping off point for specific documentation on all the supported interfaces. The local documentation also contains more information about getting started, especially regarding macros, which have a dedicated topic.
To learn about an interface, start with the top-level topic (for example“ISketchManager”) and review each area. First, the syntax shows example declarations in all supported languages, along with an example in most cases. Next, many interfaces also have several in the Examples section. This is perhaps the most useful part of the documentation because it demonstrates how to access and use the interface in a practical example. Next, the Accessors section lists the methods for which you can access the interface. This is particularly useful for tracing the route that you need to take to get to the API you want to use, which often goes through a chain of accessors. Finally, the DraftSight API also includes an access diagram where you can see how the interface accessors link. There is sometimes a See Also section as well, that includes links to other topics or interfaces that may be of interest.
After reviewing the interface documentation, browse to the member topic (for example, ISketchManager Interface Members) where you can see the available properties and methods. Each property and method also have their own topics with the same headings as the interface. For methods, review the parameters to understand what you need to use them. In most cases, examples are available for each method.
Finally, another helpful resource is the example projects contained in the SDK, which are available in the APISDK folder of your DraftSight installation (C:\Program Files\Dassault Systemes\DraftSight\APISDK\samples is the default.) This contains example projects that demonstrate several use cases in a few of the supported languages. The recommendation is that you do not use these example projects as a primary resource or as a starting point for your own projects. If you do not have this folder, it is possible that your license does not include it. You might be able to download the folder separately. Contact your VAR to learn more.
In summary, the DraftSight API documentation is your primary development resource. You can access the documentation online or locally. The recommendation is to use the local documentation for good reasons, but it still comes down to user preference, and the online documentation is useful for comparing different versions of the API. Browse the API by clicking accessor links and reviewing the interface methods and properties.
- API Object Model
The DraftSight API object model consists of interfaces with properties and methods. The documentation contains the entire model. However, the following overview provides a better starting point by explaining the major interfaces, as well as the primary ways to add user interface (UI) functionality and handle events. The following image depicts a limited graphical representation of the object model, to help you understand how to access the major interfaces.
IApplication is the entry point to the DraftSight API. This means that every project starts with accessing or creating an instance of this object. It represents the DraftSight application itself and contains methods for controlling the application behavior and executing application-level events. The most common use case is accessing documents, using methods such as GetDocuments, GetActiveDocument, OpenDocument2 or NewDocument. Other common use cases include modifying application settings, adding UI elements and handling events.
IDocument is the next most used interface and represents a file in the context of DraftSight. As you might expect, it contains file-level properties and methods, such as setting scale and saving. It also contains accessors to many other interfaces that allow you to edit the document, such as GetLayerManager, GetModel, GetSheet and GetSelectionManager.
IModel and ISheet are both accessed from IDocument, and both are used to edit a particular file. IModel represents the model space and typically contains the main content, such as lines and other entities. ISheet represents the layout within the drawing and is used for managing blocks and views. Both interfaces have a GetSketchManager method that returns the sketch interface.
For most use cases, ISketchManager is the starting point for adding or editing geometry in a drawing. It contains many methods for inserting geometry, such as InsertPoint and InsertLine.
ISelectionManager is the interface used to access user selections and to select items programmatically. This is very useful because it is often necessary to obtain the user selection or select an object to use before calling another API.
- User Interface Components
The DraftSight API provides several methods for modifying the user interface inside the application. This is primarily accomplished in add-in projects, and the starting point is IWorkspace, which is accessible through several methods on IApplication. Using IWorkspace, you can add menus, ribbon panels, ribbon tabs and toolbars with the AddMenu, AddRibbonPanel, AddRibbonTab and AddToolbar methods respectively. Each of these methods return their interface, from which you can add individual commands and other user controls. Be sure to review all the documentation and example code for each interface before using them.
A common use case that allows even more UI flexibility is to add your own custom windows and run them with a command. For example, you can add a menu with IWorkspace:AddMenu, then a menu item with IMenuItem::InsertMenuItem, and launch in a separate window when you click that menu item.
- Events
Another powerful feature of the DraftSight API is event handlers. These handlers allow you to start custom functionality automatically based on typical user interaction events. For example, you could insert relevant data into a database every time a file saves. The “DraftSight Namespace” topic of the DraftSight API Help lists all the available events about halfway down, after the Interfaces section.
Event names have a context prefix and an event description suffix. For example, IApplicationEvents_FileNewNotify exists in the context of the application and fires when a new file is created. It is important to pay attention to whether the event occurs before or after the action. Sometimes, this appears in the name of the event in the form of Pre or Post (for example, IDocumentEvents_FileSavePreNotify and IDocumentEvents_FileSavePostNotify). Sometimes, the documentation mentions this, and sometimes you must test the event to see how it works when it runs. Testing is also a good way to determine the order in which multiple events fire for a specific set of user actions.
There are two main levels of events, application and document. Some events, such as creating a new file, occur at the application level. Other events, such as saving a file, happen at the document level. Several other events also exist in other contexts, LispFunctionEvents, SelectionManagerEvents and TrackerEvents.
A good example (“Fire Application and Document Events”) of implementing an event handler is provided in the documentation for VBA, VB.NET, and C#. However, here are the main steps that are necessary,
- Establish context (connect to or create an active session of DraftSight) to get an instance of IApplication.
- Create the function that you want to run when a specific event fires.
- Attach an event handler to IApplication and refer to the function created previously. This looks like the following line of code,
dsApp.FileOpenPostNotify += new _IApplicationEvents_FileOpenPostNotifyEventHandler(FileOpenPostNotify);
Where:
- dsApp is your IApplication object.
- _IApplicationEvents_FileOpenPreNotifyEventHandler is the event.
- FileOpenPostNotify is the function that you want to run.
- When your application exists, be sure to detach the event handler. The code is the same as in step 3, but uses -= instead of +=.
- Macro Development
As mentioned earlier, macros are a great way to learn the API and to create small automation projects quickly. The local documentation includes a topic specifically about macros and how to record them. DraftSight supports macros in several languages and contexts, however, a recommendation is to use VBA and using the integrated development environment (IDE) in SOLIDWORKS or an Office application such as Excel. This document uses that context. Be aware that DraftSight does not have an IDE, so you cannot load or run macros directly in DraftSight.
- Creating Your First Macro
- In the DraftSight Drafting and Annotation workspace, click Record in the Macro section of the Manage tab.
- Perform some actions that you want to automate. You can pause and resume recording if required.
- Click Stop in the same tab and section.
- A prompt appears from which you can choose the type of macro that you want to create.
- Choose VBA (.swb) and save the macro.
- Open this macro file in the SOLIDWORKS or Office VBA editor.
- In the VBA editor, click Tools > References and add a reference to dsAutomation.dll. This file exists in the bin folder of your DraftSight installation directory (C:\Program Files\Dassault Systemes\DraftSight\bin).
- From here you can edit, run and save the macro as required.
- Example Macro
This is a simple macro that draws three lines to create a triangle in the active document. For this to work, DraftSight must be open and a document must exist.
See how the IApplication object is obtained using GetObject and how various accessors are used to get to the ISketchManager interface, which is used to draw the lines.
Option Explicit
Sub main()
Dim dsApp As DraftSight.Application
Dim dsDoc As DraftSight.Document
Dim dsModel As DraftSight.Model
Dim dsSketchManager As DraftSight.SketchManager
'Connect to DraftSight
Set dsApp = GetObject(, "DraftSight.Application")
'Abort any command currently running in DraftSight to avoid nested commands
dsApp.AbortRunningCommand
'Get active document
Set dsDoc = dsApp.GetActiveDocument()
If Not dsDoc Is Nothing Then
'Get model space
Set dsModel = dsDoc.GetModel()
'Get Sketch Manager
Set dsSketchManager = dsModel.GetSketchManager()
'Draw lines
dsSketchManager.InsertLine 90, 170, 0, 240, 210, 0
dsSketchManager.InsertLine 240, 210, 0, 240, 140, 0
dsSketchManager.InsertLine 240, 140, 0, 90, 170, 0
Else
MsgBox "There are no open documents in DraftSight"
End If
End Sub
- Add-in Development
Add-ins are a more robust and integrated way to extend the DraftSight functionality. While you can write add-ins in several programming languages, the author recommends using C#. Here are a few reasons why C# DraftSight add-ins are the best choice for most projects.
- Seamless integration: Add-ins seamlessly integrate with the DraftSight interface, making them more user-friendly and accessible. They can create custom commands, toolbars and menus within the DraftSight environment and provide a smoother user experience.
- Complex functionality: Add-ins allow for the development of complex and sophisticated functionalities that might not be easily achievable using macros or stand-alone scripts. Add-ins can interact with the core DraftSight functionality, manipulate drawings and offer a wide range of features.
- Code reusability: Add-ins are reusable components that can be shared and distributed among DraftSight users. This reusability can save time and effort, especially in professional settings where multiple users benefit from the same custom functionality.
- Version compatibility: Add-ins are generally more reliable across different DraftSight versions, reducing the need for frequent updates or modifications after the software updates.
- Error handling: Add-ins typically provide better error handling and debugging capabilities. This makes it easier to identify and resolve issues in the code.
- Creating Your First Add-in
Creating an add-in involves creating a project and writing code in a fully IDE such as Microsoft Visual Studio®. Here are the steps to create a basic C# add-in in Visual Studio. Adding commands and other UI elements is beyond the scope of this document. However, the included project template (and the examples in the API SDK) contain the necessary code.
- If you have not done so already, download and install the latest Visual Studio Community Edition (free) from the Microsoft website. This requires the .NET desktop development features as a minimum.
- Run Visual Studio and create a new .NET Framework (4.8) Class Library project.
- The application creates the Class1.cs file by default. Rename the file and the contained class to something more relevant such as Main or DSAddin.
- Add references to DraftSight.Interop.dsAddin and DraftSight.Interop.dsAutomation. Both files exist in the APISDK folder of your DraftSight installation. (C:\Program Files\Dassault Systemes\DraftSight\APISDK\tlb)
- Decorate your main class with a new GUID and a COMVisible flag.
- Implement the DsAddin interface on your main class. This requires the ConnectToDraftSight and DisconnectFromDraftSight functions.
- At a minimum, you must keep track of the IApplication object and your add-in GUID, so add two private class properties for these objects. Ensure that the initializer for your main class sets the GUID property, and the ConnectToDraftSight function should set the IApplication property. At this point, you have the skeleton for a DraftSight add-in.
- Call the functionality that you want to add from ConnectToDraftSight. Typically, this involves adding a UI or events by creating and calling the CreateUI or AttachEvents functions. Remember to create the RemoveUI and DetachEvents functions as well and call them from DisconnectFromDraftSight.
- IMPORTANT. To get your add-in working in DraftSight, you must create an XML file. See the documentation about the addinConfigs folder and the project-specific XML files.
- To debug your add-in, set Visual Studio to run DraftSight when debugging.
- When creating an installer or deploying in another manner, remember to distribute the XML file.
- Add-in Boilerplate
using System.Runtime.InteropServices;
using DraftSight.Interop.dsAddin;
using DraftSight.Interop.dsAutomation;
namespace DSAddin
{
[Guid("4260FEED-4BD2-40FC-917E-F42D7AF1A20A"), ComVisible(true)]
public class Main : DsAddin
{
private Application dsApp = null;
private string addinGUID = "";
public Main()
{
addinGUID = this.GetType().GUID.ToString();
}
public bool ConnectToDraftSight(object DsApp, int Cookie)
{
dsApp = DsApp as Application;
if (dsApp == null) { return false; }
CreateUI();
return true;
}
public bool DisconnectFromDraftSight()
{
RemoveUI();
dsApp.RemoveUserInterface(addinGUID);
dsApp = null;
return true;
}
private void CreateUI() { }
private void RemoveUI() { }
}
}
- Stand-Alone Development
A stand-alone is an application that runs on its own. In the context of this document, that means it controls or interacts with DraftSight from an external setting. This is advantageous when you need to process large amounts of data or files in DraftSight because you can handle application crashes and other events effectively. The development process varies greatly depending on which operating system and programming language you are developing for. Essentially, you must get or create an instance of IApplication and use it to implement your use case.
- Creating your First Standalone Application
A .NET desktop application is the most common type of stand-alone application. The following steps describe how to create a WPF (.Net Framework 4.8) application. The exact steps differ depending on your choice of application.
- If you have not done so already, download and install the latest Visual Studio Community Edition (free) from the Microsoft website. This requires the .NET desktop development features as a minimum.
- Run Visual Studio and create a new WPF App (.NET Framework).
- Add a reference to DraftSight.Interop.dsAutomation, which exists in the APISDK folder of your DraftSight installation (C:\Program Files\Dassault Systemes\DraftSight\APISDK\tlb\DraftSight.Interop.dsAutomation.dll).
- Create the user interface (not required for some projects, such as console applications).
- In your main class constructor (or wherever is appropriate,) get or create an instance of IApplication. Here are a few of the many ways to do this on a Windows computer:
- System.Activator.CreateInstance(“DraftSight.Application”) returns an IApplication object if DraftSight is installed correctly on the computer. Optionally, you may append the version (year) you want at the end of the string.
- Obtain the DraftSight.exe path by interrogating the file system or using other means and create a System.Diagnostics.ProcessStartInfo object. Then, call System.Diagnostics.Process.Start (info object). From there, you can obtain the IApplication object with the process ID, although this is not trivial. If you have not done this before, search the internet for information about how to obtain a COM object from the process ID.
- If you want to use an instance of DraftSight that is already running, create a System.Guid object and define it as the System.Type.GetTypeFromProgID(“DraftSight.Application”) GUID. You can then pass that GUID into the GetActiveObject method provided in the oleaut32.dll library to retrieve an IApplication object.
- Use IApplication to implement the use case you want.
- Common Use Case Examples
The following list describes some prominent use cases for the DraftSight API. These examples showcase the versatility of the API and illustrate why it is a powerful tool. In certain scenarios, developing extensive add-in applications with the API can be a cost-effective alternative to acquiring new software, effectively extending the capabilities in DraftSight. You can accomplish this internally, or with the assistance of an external service provider.
- Automation
- Create scripts to automate tasks like batch printing, dimensioning or block insertion.
- Generate standard views or layouts automatically.
- Customization
- Add custom tool palettes, commands and menus to tailor DraftSight to specific workflows.
- Create custom drafting tools or commands for specialized needs.
- Integration
- Link DraftSight with ERP systems, databases or product lifecycle management (PLM) software.
- Import and export drawing data to and from other applications.
- Design Validation
- Develop plugins to perform quality checks, such as ensuring proper layer usage, scale or dimensioning standards.
- Implement rules to validate compliance with industry-specific regulations.
- Data Extraction
- Extract attributes, text or geometric data from drawings for use in reports or analysis.
- Export drawing data to formats like CSV, XML or databases.
- Template and Symbol Libraries
- Build and manage libraries of standard templates, blocks or symbols.
- Enable easy access to frequently used elements in drawings.
- Collaboration
- Develop tools for version control and change tracking to facilitate collaboration among team members.
- Create markup and annotation tools for reviewing and commenting on drawings.
- CAD Standards Enforcement
- Implement checks and rules to ensure that drawings adhere to company or industry-specific CAD standards.
- Correct and update drawings automatically to meet compliance requirements.
- Specialized Industry Solutions
- Build industry-specific applications, such as architectural design tools, structural analysis integrations or manufacturing process simulations.
- Reporting and Documentation
- Generate bills of materials (BOM), parts lists or cost estimates based on the drawing data.
- Automatically create documentation such as project reports, assembly instructions or datasheets.
- In Conclusion
Developing with the DraftSight API offers extensive customization and enhancement options for users in diverse fields, ranging from architecture and engineering to manufacturing and beyond. It allows users to optimize their drafting and design processes to meet specific needs and standards.
We hope that you find this document informational and useful and request that you leave a brief feedback about the topics that you want us to cover in the next revision of this document. Click here for a complete list of SolidPractices documents available from DS SOLIDWORKS Corp.