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
bool
type variable. - Name of this variable =
result
- Value of this
result
variable is set byCreateLineMethod
method. - In above code, we use
await
keyword. This will wait for completion ofCreateLineMethod
method.
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
result
variable. - If value of
result
variable =true
- Then we will show an Information message.
- For showing message we use
this.eventAggregator
field. - This field get
InformationMessagesService
class and publish a message. - If value of
result
variable =false
- Then we will show an Error message.
- For showing message we use
this.eventAggregator
field. - This field get
ErrorMessagesService
class and publish a message. - In both cases message depend upon
messageToShow
variable. - Value of this
messageToShow
variable 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
swApp
variable 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
swApp
variable. - We are checking if
swApp
variable isnull
or not? - If value is
null
, then we will execute code inside thisif
condition.
messageToShow = "Failed to find Solidworks application.";
return false;
- Above code execute when value of
swApp
variable isnull
. - In above code, we are setting value of
messageToShow
variable to"Failed to find Solidworks application."
. - This variable will be use to show messages to user.
- After this we return
false
and 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 theswApp
object 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 totrue
means 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
defaultTemplate
variable. 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
defaultTemplate
variable. - We are checking if
defaultTemplate
variable isnull
or not? - If value is
null
, then we will execute code inside thisif
condition.
messageToShow = "Default part template is empty.";
return false;
- Above code execute when value of
defaultTemplate
variable isnull
. - In above code, we are setting value of
messageToShow
variable to"Default part template is empty."
. - This variable will be use to show messages to user.
- After this we return
false
and 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
swDoc
variable. 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_e
Member Description swDwgPaperA0size 11
swDwgPaperA1size 10
swDwgPaperA2size 9
swDwgPaperA3size 8
swDwgPaperA4size 6
swDwgPaperA4sizeVertical 7
swDwgPaperAsize 0
swDwgPaperAsizeVertical 1
swDwgPaperBsize 2
swDwgPaperCsize 3
swDwgPaperDsize 4
swDwgPaperEsize 5
swDwgPapersUserDefined 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 defaultTemplate
PaperSize 0
Width 0
Height 0
if (swDoc == null)
{
messageToShow = "Failed to get Solidworks document.";
return false;
}
- In above code, we are checking value of
swDoc
variable. - We are checking if
swDoc
variable isnull
or not? - If value is
null
, then we will execute code inside thisif
condition.
messageToShow = "Failed to get Solidworks document.";
return false;
- Above code execute when value of
swDoc
variable isnull
. - In above code, we are setting value of
messageToShow
variable to"Failed to get Solidworks document."
. - This variable will be use to show messages to user.
- After this we return
false
and 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
boolStatus
variable. 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_e
or 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_e
Member Description swSelectOptionDefault 0 or 0x0
swSelectOptionExtensive 1 or 0x1
-
Return Value :
true
if selected item is successfully selected,false
if not. -
In our code, I have used following values:
Parameter Name Value Used Name Right Plane
Type PLANE
X 0
Y 0
Z 0
Append false
Mark 0
Callout null
SelectOption (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
boolStatus
variable. - We are checking if
boolStatus
variable isfalse
or not? - If value is
false
, then we will execute code inside thisif
condition.
messageToShow = "Failed to select Right Plane.";
swApp.CloseAllDocuments(true);
swApp.ExitApp();
return false;
- Above code execute when value of
boolStatus
variable isfalse
. - In above code, we are setting value of
messageToShow
variable 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
true
as parameter.
- After closing all documents, we close Solidworks Application.
- For this we use
ExitApp()
method.- This
ExitApp()
method is part ofswApp
object. ExitApp()
method did not take any parameter.
- This
- After this we return
false
and 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
:true
to rebuild the part with any changes made to the sketch and exit sketch mode,false
to not
- Return Value:
None
- Reference: 🚀 InsertSketch method Solidworks API Help
UnitConversionHelper conversionHelper = container.Resolve<UnitConversionHelper>();
- In above line, we create a variable for
UnitConversionHelper
class.- Name of variable:
conversionHelper
. - Type of variable:
UnitConversionHelper
- Name of variable:
- We set the value of
conversionHelper
variable with help of DI container. - We ask DI container to resolve the initializing of
conversionHelper
variable.
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
conversionHelunitser
variable throughGetUnits()
method. - This method is part of
swDoc
variable. - 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
conversionHelper
variable. - 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, z1
variables 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 ofSketchManager
property. - This
SketchManager
property is part ofswDoc
variable. - 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 :
SketchSegment
Object if line created successfully. -
In our code, I have used following values:
Parameter Name Value Used X1 x1
Y1 y1
Z1 z1
X2 x2
Y2 y2
Z2 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
sketchSegment
variable. - We are checking if
sketchSegment
variable isnull
or not? - If value is
null
, then we will execute code inside thisif
condition.
messageToShow = "Failed to Create Sketch line.";
swApp.CloseAllDocuments(true);
swApp.ExitApp();
return false;
- Above code execute when value of
sketchSegment
variable isnull
. - In above code, we are setting value of
messageToShow
variable 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
true
as parameter.
- After closing all documents, we close Solidworks Application.
- For this we use
ExitApp()
method.- This
ExitApp()
method is part ofswApp
object. ExitApp()
method did not take any parameter.
- This
- After this we return
false
and 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 -
true
clears the entire existing selection list,false
clears only the items in the active selection list.
- All -
- We used
true
as parameter.
swDoc.ViewZoomtofit2();
- In above line, we zoom current view.
- We do this by
ViewZoomtofit2()
method. - This
ViewZoomtofit2()
method is part ofswDoc
variable. - 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
messageToShow
variable 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
PointViewModel
object (inputPoint
) and alengthConversionFactor
, and it converts theinputPoint
coordinates 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 typePointViewModel
that 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!!!