Experience in using the SolidWorks API for automated packaging design

In modern conditions, it is important for any enterprise to reduce the time required to design new products. One way to do this is through the automation of design processes. Among the products being designed, one can single out standard containers. With the help of this container (sets of boxes), for example, complexes of electronic equipment can be packed. The task of designing such sets of boxes in some cases can be quite formalized and can be monotonous work.

It should be noted that a number of scientists, developers and organizations (see for example [

1

, 2, 3]). However, there are no well-known tools designed to solve a highly specialized task: designing boxes of type VI according to GOST 5959-80 (see the figure above) based on the SolidWorks API. Therefore, the methods of such a solution are of interest.

The author of the article, working as a designer and having some skills in developing VBA applications, just faced the need to design sets of boxes. And this pushed him to the idea of ​​developing a program for this.

Initially, a VBA macro was written for design automation (you can see the development results in the corresponding publication [4]). However, outside the scope of the publication, there are some points that are rather not scientific, but of practical interest for developers using the SolidWorks API. Those who start programming using the API often have to spend a lot of time looking for methods for solving typical problems, and sometimes on English-language resources.

Note also that the written VBA macro was not without a number of shortcomings, such as manual updating of the parameter table, long execution time for rebuilding a 3D model, flashing images of the rebuilding model in front of the user, and some others. These shortcomings were not critical to the main functionality, but they increased the design time of the product and made the application less aesthetically pleasing.

This served as the basis for considering the following issues in the article.

  1. Development of an application that is devoid of the above disadvantages.
  2. API tools used to solve some common tasks.

The application mentioned above was written in the C ++ / CLI programming language (and I won’t be intimidated by these words). The choice of such a language for solving the problem was based on a number of reasons beyond the scope of this article. Alternatively, you can use, for example, the C # programming language. The names of objects, methods, and properties of the SolidWorks API for VBA, C #, and C ++ / CLI are the same, so you only need to know some of the syntax to port your code to another programming language.

To develop such an application, the author had to get an initial understanding of programming in the C ++ language.

The appearance of the application start form is shown in the figure.

A demonstration of the packaging design process using the program can be seen in the video.

The structural diagram of the software product given in the publication [4], has undergone some changes, mainly in terms of the architecture of the application. The methodology for constructing a 3D model, the data exchange scheme and the use of a number of SolidWorks tools remained the same. The modified structural diagram is shown in the figure.

It should be noted that the minimization of the editing time of assembly drawing templates after their rebuilding for a box with custom dimensions was achieved due to a special approach to the construction of sketches underlying the local sections in the drawing. Geometric objects of the sketches were snapped to the geometry of the box, dimensions were applied to the sketches, which were later hidden.

Now let’s move on to the description of the solution of some typical problems.

1. Gaining access to an object of type SldWorks ^

This assumes that a developer in Visual Studio 2019 has created an empty CLR project and started work on a Windows Form application (see, for example [5]). It is also assumed that the developer has a basic understanding of programming in C ++ (or, for example, in C # or VB, if you go the other way).

In addition to the source code file that launches the start form, a header file and a main source code file have been added. The last two files specify the SolidWorks namespaces after the #include preprocessor directives:

using namespace SolidWorks::Interop::sldworks;
using namespace SolidWorks::Interop::swcommands;
using namespace SolidWorks::Interop::swconst;

In the Visual Studio 2019 Solution Explorer window, in the References section, you need to add links to the SolidWorks dll files for working with the API (see figure).

These files are located in the folder C: Program Files SolidWorks Corp SolidWorks api redist

One way to access an object of type SldWorks ^ is to use the following code:

SldWorks^ swApp = nullptr; //Объект типа SldWorks^
        
//Массив запущенных процессов SolidWorks
array<Process^>^ localByName = Process::GetProcessesByName("SLDWORKS");
		

//Проверяем, запущен ли хоть один процесс SW
if (localByName->Length > 0)
{
MessageBoxA(0, "Запущено одно или несколько приложений SolidWorks. Закройте их и повторите попытку.", "Ошибка!", MB_ICONSTOP | MB_OK);
     return -1;
}
swApp = (SldWorks^) Activator::CreateInstance(Type::GetTypeFromProgID("SldWorks.Application.21"));

Note that in our case, for the application to work correctly, it is necessary to launch a specific version of SolidWorks, for which additional checks are performed. The SldWorks.Application.21 argument means that SolidWorks 2013 must be started. The numbers at the end of the argument increase by one as the year of the software version increases by one.

2. The task of copying the template files of the 3D-model of the box assembly

As mentioned in the post [4], each configuration of the box structure is associated with its own set of template files. It is necessary to copy the template files so that the original files remain unchanged, and the assembly drawing of the designed box refers to the model copied to the folder specified by the user. The solution to this problem is illustrated by the code fragment presented below.

//Предполагается здесь и в других примерах кода, что уже получен доступ к приложению //SolidWorks (переменная swApp типа SldWorks^), что показанно в фрагменте кода к задаче 1 

IModelDoc2^ swModel;
int longstatus;
bool boolstatus;

//Открываем файл 3D-модели ящика и чертеж в папке с шаблонами
swApp->OpenDoc6(gcnew System::String(str_Drawing_input_path.c_str()), 3, 0, "", swErrors, swWarnings);
//str_Drawing_input_path – путь хранения шаблона чертежа, тип переменной string
swApp->OpenDoc6(gcnew System::String(str_Box_input_path.c_str()), 2, 0, "", swErrors, swWarnings);
//str_Box_input_path – путь хранения шаблона 3D-модели сборки, тип переменной string
swApp->ActivateDoc2("Ящик", false, longstatus);
swModel = (IModelDoc2^)swApp->ActiveDoc;

//Сохраняем сборку в папку, указанную пользователем. Ссылки на модель в чертеже при этом меняются
longstatus = swModel->SaveAs3(gcnew System::String(str_Box_output_path.c_str()), 0, 1);
//str_Box_output_path – путь для сохранения файла сборки в папку пользователя, тип переменной string
swModel = (IModelDoc2^)swApp->ActiveDoc;
swApp->ActivateDoc2("Ящик - Лист1", false, longstatus);
swModel = (IModelDoc2^)swApp->ActiveDoc;
		
//Сохраняем шаблон чертежа
boolstatus = swModel->Save3(1, swErrors, swWarnings);

//Закрываем шаблон чертежа
swApp->CloseDoc("Ящик - Лист1");

//Копируем шаблон чертежа в папку пользователя
File::Copy(gcnew System::String(str_Drawing_input_path.c_str()), gcnew System::String(str_Drawing_output_path.c_str()), true);
//str_Drawing_output_path - путь для сохранения файла сборки в папку пользователя, тип переменной string
		
//Открываем шаблон чертежа
swModel = swApp->OpenDoc6(gcnew System::String(str_Drawing_input_path.c_str()), 3, 0, "", swErrors, swWarnings);

//Сохраняем сборку в предыдущее место. Ссылки на модель в чертеже опять меняются
swApp->ActivateDoc2(gcnew System::String(Box_parametres.str_Box_designation.c_str()) + " - Ящик.SLDASM", false, longstatus);
swModel = (IModelDoc2^)swApp->ActiveDoc;
longstatus = swModel->SaveAs3(gcnew System::String(str_Box_input_path.c_str()), 0, 1);
		
//Закроем шаблон файла сборки ящика
swApp->CloseDoc("Ящик.SLDASM");
swModel = (IModelDoc2^)swApp->ActiveDoc;
swApp->ActivateDoc2("Ящик - Лист1", false, longstatus);
swModel = (IModelDoc2^)swApp->ActiveDoc;
		
//Снова сохраняем шаблон чертежа
boolstatus = swModel->Save3(1, swErrors, swWarnings);
		
//Закрываем шаблон чертежа
swApp->CloseDoc("Ящик - Лист1");

3. The task of writing to the file of the 3D model of the assembly of custom properties

The solution to this problem is illustrated by the program code of the corresponding function:

	//Функция добавления свойств к файлу модели
int SetActiveConfigProperty(IModelDoc2^ Model, string PropertyName, string PropertyValue, int PropertyType)
{
		ConfigurationManager^ swConfMgr;               
		ModelDocExtension^ swModelDocExt;
		CustomPropertyManager^ swCustProp;
		System::String^ ConfigName;
		System::String^ resolvedPropertyValue;
		int int_Result_code;
		
		swConfMgr = Model->ConfigurationManager;
		ConfigName = swConfMgr->ActiveConfiguration->Name;

		swModelDocExt = Model->Extension;
		swCustProp = swModelDocExt->CustomPropertyManager[ConfigName];
		
		//Для корректной работы удаляем свойство, если оно существует
		int_Result_code = swCustProp->Delete(gcnew System::String(PropertyName.c_str()));
		//Проверяем тип добавляемого свойства: 1 - текст, 2 - число
		if (PropertyType == 1)
			int_Result_code = swCustProp->Add2(gcnew System::String(PropertyName.c_str()), 30, gcnew System::String(PropertyValue.c_str()));
		else if (PropertyType == 2)
			int_Result_code = swCustProp->Add2(gcnew System::String(PropertyName.c_str()), 5, gcnew System::String(PropertyValue.c_str()));
		
		return int_Result_code;
}

4. The task of automatic rebuilding of the parameter table without the participation of the designer

The custom properties are saved in the assembly 3D model file and must be updated in the design table. The solution to this problem in a macro intended for other purposes is discussed on the resource [6]… Here is a piece of code responsible for this functionality:

DesignTable^ DesTbl;
bool bool_Result;
ModelDoc2^ swDoc;

//Получаем доступ к таблице параметров
swDoc = (ModelDoc2^)swApp->ActiveDoc;
DesTbl = (DesignTable^)swDoc->GetDesignTable();
bool_Result = DesTbl->Attach();

//Обновляем таблицу параметров и отключаемся от нее
bool_Result = DesTbl->UpdateTable(2, true);
DesTbl->Detach();

5. Tasks of accelerating the work of a macro

These tasks can be accomplished by using a number of API methods [7]… In our work, we used two of them: hiding the application from the user and disabling screen regeneration. The screen regeneration was disabled not at all stages, but only at the stage of automatic updating of the parameter table. Therefore, the problem being solved illustrates not a quantitative, but a qualitative gain in speed. Please note that to disable the visibility of an application, you need to change not one application property, but three [8]:

Frame^ pFrame;

swApp->UserControl = false;
swApp->Visible = false;
pFrame = (Frame^)swApp->Frame();
pFrame->KeepInvisible = true;

A snippet of code that disables screen regeneration:

IModelDoc2^ swModel;
ModelView^ modView;

swModel = (IModelDoc2^)swApp->ActiveDoc;
modView = (ModelView^)swModel->ActiveView;
modView->EnableGraphicsUpdate = false;

Time measurements have shown that interacting with the SolidWorks API with a VBA macro (taking into account a manual update of the design table) and a C ++ / CLI application when designing the same box takes approximately 160 and 65 seconds, respectively. This confirms the expected reduction in macro run time. A similar picture is observed when comparing two versions of C ++ / CLI applications.

In conclusion, we note that the article examined the API tools that were used to solve a number of typical tasks of interacting with SolidWorks. The improved application allows you to get a set of design documentation for a box in about 5-7 minutes compared to 10-15 minutes for a VBA macro (excluding the saving of documentation in the PDM / PLM system).

Bibliographic list

  1. Engineering company Glosis [Электронный ресурс] .– URL: glosys.ru/index.php/projects/item/161-sistema-avtomatizirovannogo-proektirovaniya-yaschichnoy-taryi.html .– (date of access 12.01.2022).
  2. Polyanskov Yu. V., Pavlov P. Yu., Blumenstein A. A., Meshikhin A. A. Computer-aided design of containers for transportation of panels of a civil aircraft // Bulletin of the Samara Scientific Center of the Russian Academy of Sciences. –2019 .– v. 21 .– No. 4.
  3. Yastrebov D. V., Zguralskaya E. N., Egorychev D. V. Computer-aided design of containers for transportation of units and panels of aviation products // Bulletin of the Samara Scientific Center of the Russian Academy of Sciences .– 2021 .– v. 23 .– №1.
  4. Serkov, E.A., Automation of design of containers for complexes of radio-electronic equipment, Izv. universities. Instrument making .– 2020 .– v. 63 .– No. 6 .– p. 548-554.
  5. YouTube. Create a C ++ / Visual studio 2019 / Windows Form windowed application. [Электронный ресурс] .– URL: www.youtube.com/watch?v=QbMVxkzTi54 .– (date of access 09.11.2021).
  6. SolidWorks. Forums. [Электронный ресурс] .– Access mode: for authorization. users. – URL: forum.solidworks.com/thread/114067 .– (date of access 07.11.2021).
  7. CAD booster. SolidWorks automation. How to improve SOLIDWORKS macro speed 10x [Электронный ресурс] .– URL: cadbooster.com/improve-solidworks-macro-speed-10x/#disable-updating-feature-tree .– (date of access 07.11.2021).
  8. SolidWorks. Forums. [Электронный ресурс] .– Access mode: for authorization. users. – URL: forum.solidworks.com/thread/106420 .– (date of access 07.11.2021).

Similar Posts

One Comment

  1. LOVED the free offer, such a nice surprise! I started my free trial recently and can only say I will 100% invest in it once the trial is over. I love all the flexibility CMS IntelliCAD offers, and the tools are super easy to work with. They have been in the market since the 1990s, so no wonder why the software is so good.

Leave a Reply

Your email address will not be published. Required fields are marked *