SOLIDWORKS C# API - Create Line
Objective
I want to:
-
Create Line into Solidworks Part Document using Solidworks C# API
-
We will continue from previous article 🚀 Create Line UI - Part 2.
Demo Video
Please see below video on how to “Create Line 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.
Update Method - ExecuteCreateLineCommand
In this section, we update ExecuteCreateLineCommand method.
- First we replace below 👇🏻 code from ExecuteCreateLineCommand method.
await Task.Run(() =>
{
// Sleeping with 2 sec
Thread.Sleep(2000);
});
- Then we use below code.
bool result = await Task.Run(CreateLineMethod);
In above code, we are doing following.
- Create a
booltype variable. - Name of this variable =
result - Value of this
resultvariable is set byCreateLineMethodmethod. - In above code, we use
awaitkeyword. This will wait for completion ofCreateLineMethodmethod.
Since CreateLineMethod method did not exist hence we need to create a new method as shown below 👇🏻.
bool CreateLineMethod()
{
return true;
}
- In above code
CreateLineMethod()method return true as default value. - In
ExecuteCreateLineCommand()method, we will add following code.
if (result)
this.eventAggregator.GetEvent<InformationMessagesService>().Publish(messageToShow);
else
this.eventAggregator.GetEvent<ErrorMessagesService>().Publish(messageToShow);
- In above code, we are checking value of
resultvariable. - If value of
resultvariable =true - Then we will show an Information message.
- For showing message we use
this.eventAggregatorfield. - This field get
InformationMessagesServiceclass and publish a message. - If value of
resultvariable =false - Then we will show an Error message.
- For showing message we use
this.eventAggregatorfield. - This field get
ErrorMessagesServiceclass and publish a message. - In both cases message depend upon
messageToShowvariable. - Value of this
messageToShowvariable comes fromCreateLineMethod()method.
Update Method - CreateLineMethod
- Now we need to update
CreateLineMethod()method for Creating Line.
swApp = new SldWorks.SldWorks();
- In above code we are setting value of
swAppvariable to newSldWorks.SldWorks()type. - Reference: Please visit 🚀 online SOLIDWORKS API Help.
if (swApp == null)
{
messageToShow = "Failed to find Solidworks application.";
return false;
}
- In above code, we are checking value of
swAppvariable. - We are checking if
swAppvariable isnullor not? - If value is
null, then we will execute code inside thisifcondition.
messageToShow = "Failed to find Solidworks application.";
return false;
- Above code execute when value of
swAppvariable isnull. - In above code, we are setting value of
messageToShowvariable to"Failed to find Solidworks application.". - This variable will be use to show messages to user.
- After this we return
falseand exit theCreateLineMethod()method.
swApp.Visible = true;
In above line we are doing following:
- Purpose: This line makes sure the SOLIDWORKS is open and visible.
swApp: Refers to variable/object of an instance of SOLIDWORKS application.Visible: A property of theswAppobject that controls whether the SOLIDWORKS’s user interface (UI) is visible or hidden.true: A Boolean value indicating that the application should be visible. Setting it totruemeans the application window will be displayed.
string defaultTemplate = swApp.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplatePart);
- In above code we are creating a new variable.
- Name of variable:
defaultTemplate. - Type of variable:
string
- Name of variable:
- Sets the value of
defaultTemplatevariable. swApp: Refers to variable/object of an instance of SOLIDWORKS application.GetUserPreferenceStringValue(): A method that retrieves Gets system default user preference values.- This method
GetUserPreferenceStringValue()takes following parameters.- UserPreference: User preference as defined in
swUserPreferenceStringValue_e - Click here for more details of 🚀 swUserPreferenceStringValue_e
- UserPreference: User preference as defined in
-
In our code, I have used following values:
Parameter Name Value Used UserPreference (int)swUserPreferenceStringValue_e.swDefaultTemplatePart
if (string.IsNullOrEmpty(defaultTemplate))
{
messageToShow = "Default part template is empty.";
return false;
}
- In above code, we are checking value of
defaultTemplatevariable. - We are checking if
defaultTemplatevariable isnullor not? - If value is
null, then we will execute code inside thisifcondition.
messageToShow = "Default part template is empty.";
return false;
- Above code execute when value of
defaultTemplatevariable isnull. - In above code, we are setting value of
messageToShowvariable to"Default part template is empty.". - This variable will be use to show messages to user.
- After this we return
falseand exit theCreateLineMethod()method.
ModelDoc2 swDoc = swApp.NewDocument(defaultTemplate, 0, 0, 0);
- In above code we are creating a new variable.
- Name of variable:
swDoc. - Type of variable:
ModelDoc2
- Name of variable:
- Sets the value of
swDocvariable. swApp: Refers to variable/object of an instance of SOLIDWORKS application.NewDocument(): A method that creates a new document based on the specified template.- This method
NewDocument()takes following parameters.- TemplateName: Fully qualified path and name of the template to use for creating the new document
-
PaperSize: Size of paper as defined in
swDwgPaperSizes_eMember Description swDwgPaperA0size 11swDwgPaperA1size 10swDwgPaperA2size 9swDwgPaperA3size 8swDwgPaperA4size 6swDwgPaperA4sizeVertical 7swDwgPaperAsize 0swDwgPaperAsizeVertical 1swDwgPaperBsize 2swDwgPaperCsize 3swDwgPaperDsize 4swDwgPaperEsize 5swDwgPapersUserDefined 12 - Width: Width of paper; used only when PaperSize is
swDwgPapersUserDefined - Height: Height of paper; used only when PaperSize is
swDwgPapersUserDefined - Click here for more details of 🚀 NewDocument Method
-
In our code, I have used following values:
Parameter Name Value Used TemplateName defaultTemplatePaperSize 0Width 0Height 0
if (swDoc == null)
{
messageToShow = "Failed to get Solidworks document.";
return false;
}
- In above code, we are checking value of
swDocvariable. - We are checking if
swDocvariable isnullor not? - If value is
null, then we will execute code inside thisifcondition.
messageToShow = "Failed to get Solidworks document.";
return false;
- Above code execute when value of
swDocvariable isnull. - In above code, we are setting value of
messageToShowvariable to"Failed to get Solidworks document.". - This variable will be use to show messages to user.
- After this we return
falseand exit theCreateLineMethod()method.
bool boolStatus = swDoc.Extension.SelectByID2("Right Plane", "PLANE", 0, 0, 0, false, 0, null, (int)swSelectOption_e.swSelectOptionDefault);
- In above code we are creating a new variable.
- Name of variable:
boolStatus. - Type of variable:
bool
- Name of variable:
- Sets the value of
boolStatusvariable. swDoc.Extension: Refers to object allows access to the model.SelectByID2(): A method that Selects the specified entity.- This method
SelectByID2()takes following parameters.- Name: Name of object to select or an empty string
- Type: Type of object (uppercase) as defined in
swSelectType_eor an empty string- Click here for more details of 🚀 swSelectType_e
- X: X selection location or 0
- Y: Y selection location or 0
- Z: Z selection location or 0
-
Append: Please see below table for details:
If An, if entity is Then True Not already selected Entity is appended to the current selection list Already selected Entity is removed from the current selection list False Not already selected Current selection is cleared and then the entity is put on the list Already selected Current selection list remains the same - Mark: Value that you want to use as a mark; this value is used by other functions that require ordered selection.
- Callout: Pointer to the associated callout
-
SelectOption: Selection option as defined in
swSelectOption_eMember Description swSelectOptionDefault 0 or 0x0swSelectOptionExtensive 1 or 0x1
-
Return Value :
trueif selected item is successfully selected,falseif not. -
In our code, I have used following values:
Parameter Name Value Used Name Right PlaneType PLANEX 0Y 0Z 0Append falseMark 0Callout nullSelectOption (int)swSelectOption_e.swSelectOptionDefault
if (boolStatus == false)
{
messageToShow = "Failed to select Front Plane";
swApp.CloseAllDocuments(true);
swApp.ExitApp();
return false;
}
- In above code, we are checking value of
boolStatusvariable. - We are checking if
boolStatusvariable isfalseor not? - If value is
false, then we will execute code inside thisifcondition.
messageToShow = "Failed to select Right Plane.";
swApp.CloseAllDocuments(true);
swApp.ExitApp();
return false;
- Above code execute when value of
boolStatusvariable isfalse. - In above code, we are setting value of
messageToShowvariable to"Failed to select Right Plane.". - This variable will be use to show messages to user.
- After this, we close all documents in Solidworks application.
CloseAllDocuments(): For closing all documents, we useCloseAllDocuments()method.CloseAllDocuments()method takes following parameters:IncludeUnsaved:true= Close all documents, including dirty documentsfalse= Close all documents, excluding dirty documents
- In our code, we use
trueas parameter.
- After closing all documents, we close Solidworks Application.
- For this we use
ExitApp()method.- This
ExitApp()method is part ofswAppobject. ExitApp()method did not take any parameter.
- This
- After this we return
falseand exit theCreateLineMethod()method.
swDoc.SketchManager.InsertSketch(false);
- Now after selecting plane, we insert sketch into selected plane.
- For inserting sketch, we use:
InsertSketch()method: To Inserts a new sketch in the current part or assembly document.- Parameters:
UpdateEditRebuild:trueto rebuild the part with any changes made to the sketch and exit sketch mode,falseto not
- Return Value:
None
- Reference: 🚀 InsertSketch method Solidworks API Help
UnitConversionHelper conversionHelper = container.Resolve<UnitConversionHelper>();
- In above line, we create a variable for
UnitConversionHelperclass.- Name of variable:
conversionHelper. - Type of variable:
UnitConversionHelper
- Name of variable:
- We set the value of
conversionHelpervariable with help of DI container. - We ask DI container to resolve the initializing of
conversionHelpervariable.
var units = swDoc.GetUnits();
- In above line, we create a variable for storing Solidworks document units.
- Name of variable:
conversionHelunitser. - Type of variable:
var- Type will resolve while application is running.
- This is called Runtime resolution.
- Name of variable:
- We set the value of
conversionHelunitservariable throughGetUnits()method. - This method is part of
swDocvariable. - Reference: 🚀 GetUnits method Solidworks API Help
conversionHelper.UnitConversion((swLengthUnit_e)units[0]);
- In above line, we are calling
UnitConversion()method. - This method is part of
conversionHelpervariable. - For more details on
UnitConversion()method, please visit 🚀 SOLIDWORKS C# API - Fix Unit Issue article from this website.
double x1, y1, z1, x2, y2, z2;
- In above line, we create some variables.
- Type of variables:
double - Name of variables:
x1, y1, z1, x2, y2, z2
- Type of variables:
(x1, y1, z1) = ApplyUnitConversion(StartPointViewModel, conversionHelper.LengthConversionFactor);
- In above code, we are setting values of
x1, y1, z1variables usingApplyUnitConversion()method. - We pass 2 parameters to
ApplyUnitConversion()method.PointViewModel- For which point we want to apply unit conversions.LengthConversionFactor- Factor we want to apply to values of passing point.
- I will explain more about
ApplyUnitConversion()method later.
(x2, y2, z2) = ApplyUnitConversion(EndPointViewModel, conversionHelper.LengthConversionFactor);
- Same as previous line of code.
sketchSegment = swDoc.SketchManager.CreateLine(x1, y1, z1, x2, y2, z2);
- In above line of code, we are creating Sketch line.
- For this we are using
CreateLine()method. - This
CreateLine()method, creates a sketch line in the currently active 2D or 3D sketch. - This
CreateLine()method is part ofSketchManagerproperty. - This
SketchManagerproperty is part ofswDocvariable. - This
CreateLine()method takes following parameters.- X1 - X coordinate of the line start point
- Y1 - Y coordinate of the line start point
- Z1 - Z coordinate of the line start point
- X2 - X coordinate of the line end point
- Y2 - Y coordinate of the line end point
- Z2 - Z coordinate of the line end point
-
Return Value :
SketchSegmentObject if line created successfully. -
In our code, I have used following values:
Parameter Name Value Used X1 x1Y1 y1Z1 z1X2 x2Y2 y2Z2 z2
if (sketchSegment == null)
{
messageToShow = "Failed to Create Sketch line.";
swApp.CloseAllDocuments(true);
swApp.ExitApp();
return false;
}
- In above code, we are checking value of
sketchSegmentvariable. - We are checking if
sketchSegmentvariable isnullor not? - If value is
null, then we will execute code inside thisifcondition.
messageToShow = "Failed to Create Sketch line.";
swApp.CloseAllDocuments(true);
swApp.ExitApp();
return false;
- Above code execute when value of
sketchSegmentvariable isnull. - In above code, we are setting value of
messageToShowvariable to"Failed to Create Sketch line.". - This variable will be use to show messages to user.
- After this, we close all documents in Solidworks application.
CloseAllDocuments(): For closing all documents, we useCloseAllDocuments()method.CloseAllDocuments()method takes following parameters:IncludeUnsaved:true= Close all documents, including dirty documentsfalse= Close all documents, excluding dirty documents
- In our code, we use
trueas parameter.
- After closing all documents, we close Solidworks Application.
- For this we use
ExitApp()method.- This
ExitApp()method is part ofswAppobject. ExitApp()method did not take any parameter.
- This
- After this we return
falseand exit theCreateLineMethod()method.
swDoc.ClearSelection2(true);
- In above line, we clear all selection in Solidwork Sketch.
- We clear selection by
ClearSelection2()method. - This method
ClearSelection2()takes following parameter:- All -
trueclears the entire existing selection list,falseclears only the items in the active selection list.
- All -
- We used
trueas parameter.
swDoc.ViewZoomtofit2();
- In above line, we zoom current view.
- We do this by
ViewZoomtofit2()method. - This
ViewZoomtofit2()method is part ofswDocvariable. - This
ViewZoomtofit2()method, did not take any parameter and did not return any object.
messageToShow = "Sketch line successfully created.";
return true;
- In above code, we are setting value of
messageToShowvariable to"Sketch line successfully created.". - Then we return
true; indicating we have completed ourCreateLineMethod()method successfully.
Add Method - ApplyUnitConversion
Now we add ApplyUnitConversion method.
public (double, double, double) ApplyUnitConversion(PointViewModel inputPoint, double lengthConversionFactor)
{
double X, Y, Z;
X = inputPoint.XPoint * lengthConversionFactor;
Y = inputPoint.YPoint * lengthConversionFactor;
Z = inputPoint.ZPoint * lengthConversionFactor;
return (X, Y, Z);
}
- This method takes a
PointViewModelobject (inputPoint) and alengthConversionFactor, and it converts theinputPointcoordinates by multiplying each with the conversion factor. - Return Type: The method returns a tuple
(double, double, double)representing the converted X, Y, and Z coordinates. - Parameters:
inputPoint: An object of typePointViewModelthat has propertiesXPoint, YPoint, and ZPoint, representing the X, Y, and Z coordinates of a point.lengthConversionFactor: A double value used to convert the unit of measurement for each coordinate.
Final Result
Now, we have done everything needed to Create Line in Solidworks 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 Create Line in Solidworks SketchSketch 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!!!
