SOLIDWORKS C# API - Insert Solidworks Sketch
Objective
I want to:
-
Insert Sketch into Solidworks Part Document using Solidworks C# API
-
We will continue from previous article 🚀 Insert Solidworks Sketch UI.
-
Extend article by adding Solidworks C# API to previous code.
Demo Video
Please see below video on how to “Insert Sketch into Solidworks Part Document” using Solidworks C# API from WPF Application.
Please note that there are no explanation in the video.
Explanation of each step and why we write code this way is given in this post.
Add [Solidworks References]
-
For opening Solidworks we need to add some references into our project.
-
Please see below 👇🏻 image for how to add Solidworks reference.
- Please see below 👇🏻 image from 🚀 Browse Solidworks Document article for how to add reference files.
Update ViewModel
In this section, we update MainWindowViewModel for inserting Sketch.
Check Plane Selected
Before proceeding, we need to confirm, if any Plane is selected.
-
Function needs to update:
ExecuteInsertSketchCommand()
-
Please see below 👇🏻 image for reference.
- Please see below 👇🏻 code sample for reference.
if(string.IsNullOrEmpty(SelectedPlane))
{
this.eventAggregator.GetEvent<ErrorMessagesService>().Publish("No Plane selected in application. Please select a Plane.");
return;
}
- In above code, we are checking, if any Plane is selected.
- Condition:
string.IsNullOrEmpty(SelectedPlane)
- We check if value of
SelectedPlane
variable isnull
orempty
byIsNullOrEmpty()
method. - When this condition is
true
, then we PublishErrorMessagesService
event. - This
ErrorMessagesService
, then display message to user. - Message to show: “No Plane selected in application. Please select a Plane.”
- After showing message we exit the function.
- We check if value of
Add New Function
-
Now we add a new function which we use for Inserting Sketch.
-
Please see below 👇🏻 image for reference.
- Please see below 👇🏻 code sample for reference.
bool insertSketch = await Task.Run(InsertSketch);
-
In above line, we are are doing following.
- Creating a new variable.
- Type of new variable:
bool
- Name of variable:
insertSketch
- Value of this variable is get by
InsertSketch()
method. - We are also waiting for this
InsertSketch()
method to complete in different backgroud Thread.
private bool InsertSketch()
{
throw new NotImplementedException();
}
- In above line of code, we create a new
InsertSketch()
method. - This method currently throw
NotImplementedException()
exception.
Get Default Part Template
- In
InsertSketch()
method, we get Default Part Template.
SldWorks.SldWorks swApp = new SldWorks.SldWorks();
- Purpose: In above line, we create variable for Solidworks application.
- Variable Name:
swApp
- Type:
SldWorks.SldWorks
string defaultTemplate = swApp.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplatePart);
- Purpose: In above line, we create variable for default part template.
- Variable Name:
defaultTemplate
- Type:
string
- Value: We get this value by
GetUserPreferenceStringValue()
method.- This method is part of
swApp
variable. GetUserPreferenceStringValue()
method takeInteger
as parameter.- We pass
swUserPreferenceStringValue_e.swDefaultTemplatePart
enumerable as parameter. - Since
GetUserPreferenceStringValue()
method, takesInteger
as parameter, we castswUserPreferenceStringValue_e.swDefaultTemplatePart
to(int)
. - Final Parameter:
(int)swUserPreferenceStringValue_e.swDefaultTemplatePart
- This method is part of
if (string.IsNullOrEmpty(defaultTemplate))
{
this.eventAggregator.GetEvent<ErrorMessagesService>().Publish("Default part template is empty.");
return false;
}
-
In above code, we check if “Default Part template” is null or empty.
-
Condition:
string.IsNullOrEmpty(defaultTemplate)
- We check if value of
defaultTemplate
variable isnull
orempty
byIsNullOrEmpty()
method. - When this condition is
true
, then we PublishErrorMessagesService
event. - This
ErrorMessagesService
, then display message to user. - Message to show: “Default part template is empty.”
- After showing message we exit the function and return
false
.
- We check if value of
Get Solidworks Document
- Now we create Solidworks Document object.
ModelDoc2 swDoc = swApp.NewDocument(defaultTemplate, 0, 0, 0);
- Purpose: In above line, we create variable for Solidworks Document object.
- Variable Name:
swDoc
- Type:
ModelDoc2
if (swDoc == null)
{
this.eventAggregator.GetEvent<ErrorMessagesService>().Publish("Failed to create new Part document.");
return false;
}
-
In above code, we check if “Solidworks Document object” is null.
-
Condition:
swDoc == null
- We check if value of
defaultTemplate
variable isnull
. - When this condition is
true
, then we PublishErrorMessagesService
event. - This
ErrorMessagesService
, then display message to user. - Message to show: “Failed to create new Part document.”
- After showing message we exit the function and return
false
.
- We check if value of
Select Plane
-
Now we select Plane in Solidworks document.
-
We get selected plane name from drop down.
bool boolStatus = swDoc.Extension.SelectByID2(SelectedPlane, "PLANE", 0, 0, 0, false, 0, null, (int)swSelectOption_e.swSelectOptionDefault);
- Purpose: In above line, we create variable for checking plane is selected or not.
- Variable Name:
boolStatus
- Type:
bool
- Value: We get this value by
SelectByID2()
method.- This method is part of
swDoc.Extension
variable. SelectByID2()
method takes following as parameter.- Name: Name of object to select or an empty string.
- Type: Type of object (uppercase) as defined in
swSelectType_e
or an empty string.For full list of
swSelectType_e
object types, please visit 🚀 Solidworks SelectByID2 API Help - X: X selection location or 0.
- Y: Y selection location or 0.
- Z: Z selection location or 0.
- Append: please visit 🚀 Solidworks SelectByID2 API Help
- Mark: Value that you want to use as a mark.
- Callout: Pointer to the associated
callout
. - SelectOption: Selection option as defined in
swSelectOption_e
in below table.
Member Description swSelectOptionDefault
0 swSelectOptionExtensive
1 -
Return Value:
True
if item was successfully selected,False
if not. -
In our code, I have used following values:
Parameter Name Value Used Name SelectedPlane
Type PLANE
X 0
Y 0
Z 0
Append false
Mark 0
Callout null
SelectOption (int)swSelectOption_e.swSelectOptionDefault
- This method is part of
if (boolStatus == false)
{
this.eventAggregator.GetEvent<ErrorMessagesService>().Publish($"Failed to select [{SelectedPlane}].");
swApp.CloseAllDocuments(true);
swApp.ExitApp();
return false;
}
- In above code, we check if plane is selected or not.
- Condition:
boolStatus == false
- We check if value of
boolStatus
variable isfalse
.
- We check if value of
this.eventAggregator.GetEvent<ErrorMessagesService>().Publish($"Failed to select [{SelectedPlane}].");
- When this condition is
true
, then we PublishErrorMessagesService
event. - This
ErrorMessagesService
, then display message to user. - Message to show: “Failed to select [{SelectedPlane}].”
swApp.CloseAllDocuments(true);
- After showing message, we close all open document in Solidworks.
- We close all documents including all dirty documents.
- We close all documents by
CloseAllDocuments()
method. - This method is part of
swApp
variable.CloseAllDocuments()
method takes following as parameter.- IncludeUnsaved: As define in below table.
Member Description True
Close all documents, including dirty documents. False
Close all documents, excluding dirty documents. - Return Value:
True
if item was successfully execute,False
if not.
- Reference: 🚀 Solidworks CloseAllDocuments Method API Help
swApp.ExitApp();
- After closing all document in Solidworks application, we exit Solidworks application.
- We do this by calling
ExitApp()
method. - This
ExitApp()
method is partswApp
variable. - This
ExitApp()
method did not take any parameter.
return false;
- After closing Solidworks application, we exit the function and return
false
.
Insert Sketch
- Now, we add Solidworks Sketch segment into selected plane.
swDoc.Visible = true;
- In above code, we make Solidworks visible.
- We make Solidworks visible by setting value of
Visible
property. - This
Visible
property is part ofswDoc
variable. - We set the value of
Visible
property totrue
.
swDoc.SketchManager.InsertSketch(false);
- In above code, we insert Solidwork Sketch into selected plane.
- We insert plane by
InsertSketch()
method. - This
InsertSketch()
method is part ofswDoc.SketchManager
object. - This
InsertSketch()
method takes following parameter:- UpdateEditRebuild: True to rebuild the part with any changes made to the sketch and exit sketch mode, False to not.
- Return Value: This
InsertSketch()
method did not return any value. - Reference: 🚀 Solidworks InsertSketch Method API Help
return true;
-
After inserting sketch we return
true
and exitInsertSketch()
function in our application. -
In
ExecuteInsertSketchCommand()
method we add below lines.
if (insertSketch == false)
return;
- In above code, we check if Sketch is inserted successfully.
- Condition:
insertSketch == false
- We check if value of
insertSketch
variable isfalse
. - In above condition is true, then we exit function from here.
- This also means we got some error while inserting Solidworks Sketch into document.
- We check if value of
this.eventAggregator.GetEvent<InformationMessagesService>().Publish("Sketch inserted successfully.");
- After this we Publish
InformationMessagesService
event. - This
InformationMessagesService
, then display message to user. - Message to show: “Sketch inserted successfully.”
FINAL RESULT
Now, we have done everything needed to Insert Solidwork Sketch into Solidworks Document through our application.
Please see below image for final result of our work.
This is it !!!
I hope my efforts will helpful to someone!
If you found anything to add or update, please let me know on my e-mail.
Hope this post helps you to Insert Solidworks Sketch from WPF PRISM Application.
If you like the post then please share it with your friends also.
Do let me know by you like this post or not!
Till then, Happy learning!!!