SOLIDWORKS C# API - Create Line

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.

Create Line into Solidworks Part Document

Important

Please note that there are no explanations in the video.
Explanation of each step and why we write the code this way is provided 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 for 2 seconds
    Thread.Sleep(2000);
});
  • Then we use below code.
bool result = await Task.Run(CreateLineMethod);

In above code, we are doing following.

  1. Create a bool type variable.
  2. Name of this variable = result
  3. Value of this result variable is set by CreateLineMethod method.
  4. In above code, we use await keyword. This will wait for completion of CreateLineMethod 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 from CreateLineMethod() 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 new SldWorks.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 is null or not?
  • If value is null, then we will execute code inside this if condition.
messageToShow = "Failed to find SolidWorks application.";
return false;
  • Above code execute when value of swApp variable is null .
  • 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 the CreateLineMethod() 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 the swApp 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 to true means the application window will be displayed.

SOLIDWORKS C# API - Delete Selected Sketch

I want to:

  • Delete Selected Sketch into Solidworks Part Document using Solidworks C# API

  • We will continue from previous article πŸš€ Delete Selected Sketch UI.

Demo Video

Please see below video on how to β€œDelete Selected Sketch into Solidworks Part Document” using Solidworks C# API from WPF Application.

(Add your video caption here)

Important

Please note that there are no explanations in the video.
Explanation of each step and why we write the code this way is provided in this post.



Update Method - ExecuteDeleteCommand

In this section, we update ExecuteDeleteCommand method.

  • First we replace below πŸ‘‡πŸ» code from ExecuteDeleteCommand method.
await Task.Run(() =>
{
    // Sleeping for 2 seconds
    Thread.Sleep(2000);
});
  • Then we use below code.
bool result = await Task.Run(DeleteSketch);

In above code, we are doing following.

  1. Create a bool type variable.
  2. Name of this variable = result
  3. Value of this result variable is set by DeleteSketch method.
  4. In above code, we use await keyword. This will wait for completion of DeleteSketch method.

Since DeleteSketch method did not exist hence we need to create a new method as shown below πŸ‘‡πŸ».

bool DeleteSketch()
{
    return true;
}
  • In above code DeleteSketch() method return true as default value.
  • In ExecuteDeleteCommand() 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 from DeleteSketch() method.

Update Method - DeleteSketch

  • Now we need to update DeleteSketch() method for deleting selected Sketch.
swApp = new SldWorks.SldWorks();
  • In above code we are setting value of swApp variable to new SldWorks.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 is null or not?
  • If value is null, then we will execute code inside this if condition.
messageToShow = "Failed to find SolidWorks application.";
return false;
  • Above code execute when value of swApp variable is null .
  • 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 the ChangeSketchName() method.
swDoc = swApp.ActiveDoc;
  • In above code we are setting value of swDoc variable to new swApp.ActiveDoc property.
  • This ActiveDoc property is part of swApp variable.
  • If there is NO document active then this ActiveDoc property return null.
  • Reference: Please visit πŸš€ online SOLIDWORKS API Help .
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 is null or not?
  • If value is null, then we will execute code inside this if condition.
messageToShow = "Failed to get SolidWorks document.";
return false;
  • Above code execute when value of swDoc variable is null .
  • 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 the ChangeSketchName() method.
bool result = swDoc.Extension.DeleteSelection2(
    (int)swDeleteSelectionOptions_e.swDelete_Children
);
  • In above code, we delete selected Sketch.
  • For changing the name, we use DeleteSelection2() method.
  • DeleteSelection2() method is part of Extension property.
  • Extension property is part of swDoc variable.
  • DeleteSelection2() method takes following parameters.
    • DeleteOptions: Options as defined in swDeleteSelectionOptions_e.
swDeleteSelectionOptions_e Members
MemberDescription
swDelete_Absorbed 2
swDelete_Advanced 4
swDelete_Children 1
  • Return Value : true if selected item is deleted, false if not.

  • In our code, I have used following values:

DeleteSelection2 Parameters
Parameter NameValue Used
DeleteOptions swDeleteSelectionOptions_e.swDelete_Children
  • We store return value of DeleteSelection2() method in result variable.
  • result variable Type : bool
if (result == false)
{
    messageToShow = "Failed to delete selected sketch.";
    return false;
}
  • We check value of result variable and successfully delete Selected Sketch or not.
  • In above code, we are checking value of result variable and successfully deleted Sketch or not.
  • We are checking if result variable is true or false?
  • If value is false, then we will execute code inside this if condition.
messageToShow = "Failed to delete selected sketch.";
return false;
  • Above code execute when value of result variable is false .
  • In above code, we are setting value of messageToShow variable to "Failed to delete selected sketch.".
  • This variable will be use to show messages to user.
  • After this we return false and exit the DeleteSketch() method.
messageToShow = "Selected Sketch is deleted.";
return true;
  • Above code execute when value of result variable is true and did not execute code inside if condition.
  • In above code, we are setting value of messageToShow variable to "Selected Sketch is deleted.".
  • This variable will be use to show messages to user.
  • After this we return true and exit the DeleteSketch() method.

FINAL RESULT

For Demo, we already had a sketch we want to delete with our program.

Please see below πŸ‘‡πŸ» image for reference.

Feature Sketch We Want To Delete
Figure: Feature Sketch We Want To Delete

Now, we have done everything needed to Delete Solidworks Sketch into Solidworks Document through our application.

Please see below image for final result of our work.

Delete Sketch Result
Figure: Delete Sketch Result

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 Delete Selected 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!!!

  • In above code we are creating a new variable.
    • Name of variable: defaultTemplate.
    • Type of variable: string
  • 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
  • In our code, I have used following values:
User Preference Parameters
Parameter NameValue 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 is null or not?
  • If value is null, then we will execute code inside this if condition.
messageToShow = "Default part template is empty.";
return false;
  • Above code execute when value of defaultTemplate variable is null .
  • 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 the CreateLineMethod() 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
  • 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
Drawing Paper Size Members
MemberDescription
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:
New Document Parameters
Parameter NameValue 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 is null or not?
  • If value is null, then we will execute code inside this if condition.
messageToShow = "Failed to get Solidworks document.";
return false;
  • Above code execute when value of swDoc variable is null .
  • 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 the CreateLineMethod() 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
  • 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
    • 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:
SelectByID2 Append Behavior
IfAn, if entity isThen
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
Select Option Members
MemberDescription
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:

SelectByID2 Parameters
Parameter NameValue 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 is false or not?
  • If value is false, then we will execute code inside this if condition.
messageToShow = "Failed to select Right Plane.";
swApp.CloseAllDocuments(true);
swApp.ExitApp();
return false;
  • Above code execute when value of boolStatus variable is false .
  • 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 use CloseAllDocuments() method.
    • CloseAllDocuments() method takes following parameters:
      • IncludeUnsaved:
        • true = Close all documents, including dirty documents
        • false = 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 of swApp object.
    • ExitApp() method did not take any parameter.
  • After this we return false and exit the CreateLineMethod() 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
  • 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.
  • We set the value of conversionHelunitser variable through GetUnits() 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
(x1, y1, z1) = ApplyUnitConversion(StartPointViewModel, conversionHelper.LengthConversionFactor);
  • In above code, we are setting values of x1, y1, z1 variables using ApplyUnitConversion() 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 of SketchManager property.
  • This SketchManager property is part of swDoc 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:
CreateLine Parameters
Parameter NameValue 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 is null or not?
  • If value is null, then we will execute code inside this if condition.
messageToShow = "Failed to Create Sketch line.";
swApp.CloseAllDocuments(true);
swApp.ExitApp();
return false;
  • Above code execute when value of sketchSegment variable is null .
  • 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 use CloseAllDocuments() method.
    • CloseAllDocuments() method takes following parameters:
      • IncludeUnsaved:
        • true = Close all documents, including dirty documents
        • false = 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 of swApp object.
    • ExitApp() method did not take any parameter.
  • After this we return false and exit the CreateLineMethod() 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.
  • 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 of swDoc 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 our CreateLineMethod() 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 a lengthConversionFactor, and it converts the inputPoint 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 type PointViewModel that has properties XPoint, 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.

Create Line Result
Figure: Sketch Line Creation Result

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!!!