Solidworks learning notes - link Solidworks
on this basis
Allows access to functions that perform drawing operations.
attribute
Name | Description | remarks |
ActiveDrawingView | Gets the currently active drawing view. | Gets the currently active sheet view. |
AutomaticViewUpdate | Gets or sets whether the drawing views in this drawing are automatically updated if the underlying model in that drawing view changes. | Gets or sets whether the drawing view in the drawing is automatically updated when the underlying model in the drawing view changes. |
BackgroundProcessingOption | Gets or sets the background processing option for this drawing. | Gets or sets the spooling options for this drawing. |
HiddenViewsVisible | Shows or hides all of the hidden drawing views. | Shows or hides all hidden sheet views. |
IActiveDrawingView | Gets the currently active drawing view. | Gets the currently active sheet view. |
Sheet | Gets the specified sheet. | Gets the specified worksheet. |
System.int BackgroundProcessingOption {get; set;}
This example shows how to fire notifications when background processing events occur. //---------------------------------------------------------------------------- // Preconditions: // 1. Create a VSTA C# macro. // a. Copy and paste SolidWorksMacro.cs code in the macro. // b. Create a form, Form1, that contains the following // controls: // * CheckBox1 with caption Enable background processing and open // drawing. // * button1 with caption Close after background processing end event // fires". // c. Copy and paste Form1.cs code in your form's code window. // d. Modify the path in Form1.cs to open a huge drawing document that // contains many parts. // 2. Press F5 to start and close the debugger. // 3. Click Build > Build macro_name to build a DLL for the macro. // 4. Save and close the macro. // // Postconditions: // 1. Open the Windows Task manager, click the Processes tab, and click the CPU column // header to sort the processes in descending order. // 2. In SOLIDWORKS, click Tools > Macro > Run. // a. Locate your macro's \SwMacro\bin\Debug folder. // b. Select macro_name.dll. // c. Click Open to open the form. // 3. Select the Enable background processing and open drawing checkbox on the form. // 4. Displays a checkmark in the check box. // 5. Click OK to close the Background processing enabled message box. // 6. Opens the specified drawing. // 7. Fires the background processing start events. // 8. Click OK to close the Background processing start event fired message box. // 9. In the Windows Task Manager, observe that several sldbgproc.exe processes are // occupying most of the CPU. // 10. Click OK to close the Background processing stop event fired message box. // 11. Click Close after background processing end event fired button on the form. // 12. Unloads Form1. //---------------------------------------------------------------------------------- //SolidWorksMacro.cs using SolidWorks.Interop.sldworks; using System.Runtime.InteropServices; using System; using System.Windows.Forms; namespace BackgroundProcessingEventsCSharp.csproj { public partial class SolidWorksMacro { public SldWorks swApp; public void Main() { //Create and show an instance of the form Form1 myForm = new Form1(); myForm.Show(); } } } //Form1 using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Windows.Forms; using System.Diagnostics; using System.Collections; using System.Runtime.InteropServices; using System; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; namespace BackgroundProcessingEventsCSharp.csproj { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public SldWorks swApp; public bool checkBoxClicked; private void checkBox1_CheckedChanged(object sender, EventArgs e) { try { swApp = (SldWorks)System.Runtime.InteropServices.Marshal.GetActiveObject("SldWorks.Application"); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } ModelDoc2 swModelDoc = default(ModelDoc2); DrawingDoc swDrawingDoc = default(DrawingDoc); string filePath = null; filePath = "path_and_filename_of_huge_drawing"; DocumentSpecification docSpecification = default(DocumentSpecification); // Set up events AttachEventHandlers(); // Enable background processing swApp.EnableBackgroundProcessing = true; MessageBox.Show("Background processing enabled"); // Open huge drawing docSpecification = (DocumentSpecification)swApp.GetOpenDocSpec(filePath); docSpecification.Silent = true; swModelDoc = (ModelDoc2)swApp.OpenDoc7(docSpecification); swDrawingDoc = (DrawingDoc)swModelDoc; // Set document background processing to application setting swDrawingDoc.BackgroundProcessingOption = (int)swBackgroundProcessOption_e.swBackgroundProcessing_DeferToApplication; } public void AttachEventHandlers() { AttachSWEvents(); } public void AttachSWEvents() { swApp.BackgroundProcessingStartNotify += this.mySwApp_BackgroundProcessingStartNotify; swApp.BackgroundProcessingEndNotify += this.mySwApp_BackgroundProcessingEndNotify; } private int mySwApp_BackgroundProcessingStartNotify(string filename) { MessageBox.Show("Background processing start event fired"); return 1; } private int mySwApp_BackgroundProcessingEndNotify(string filename) { MessageBox.Show("Background processing end event fired"); swApp.EnableBackgroundProcessing = false; return 1; } public void CheckBox1_Click(object sender, System.EventArgs e) { checkBoxClicked = true; } private void button1_Click(object sender, EventArgs e) { this.Close(); } } }
Sheet Sheet( System.string Name) {get;}
This example shows how to get each sheet in a multi-sheet drawing document regardless whether the sheet is loaded. //---------------------------------------------------------------------- // Preconditions: // 1. Click File > Open. // 2. Open public_documents\samples\tutorial\advdrawings\foodprocessor.sldrw. // 3. Click Select sheets to open > Selected > Sheet1* (load) > OK >Open. // 4. Open the Immediate window. // // Postconditions: // 1. Loads Sheet1 only. // 2. Mouse over Sheet2, Sheet3, and Sheet4 tabs and examine the // Immediate window. // // NOTE: Because this drawing is used elsewhere, do not save changes. //--------------------------------------------------------------------- using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System; using System.Diagnostics; namespace SheetDrawingDocCSharp.csproj { partial class SolidWorksMacro { public void Main() { ModelDoc2 swModel = default(ModelDoc2); DrawingDoc swDraw = default(DrawingDoc); string[] vSheetName = null; int i = 0; bool bRet = false; string sheetName; swModel = (ModelDoc2)swApp.ActiveDoc; swDraw = (DrawingDoc)swModel; // Get the sheets in the drawing document vSheetName = (string[])swDraw.GetSheetNames(); // Traverse the sheets and determine whether // they're loaded for (i = 0; i < vSheetName.Length; i++) { sheetName = (string)vSheetName[i]; bRet = swDraw.ActivateSheet(sheetName); Sheet swSheet = default(Sheet); swSheet = (Sheet)swDraw.get_Sheet(vSheetName[i]); if ((swSheet.IsLoaded())) { Debug.Print(vSheetName[i] + " is loaded."); } else { Debug.Print(vSheetName[i] + " is not loaded."); } } } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
method
Name | Description | remarks |
ActivateSheet | Activates the specified drawing sheet. | Activates the specified sheet. |
ActivateView | Activates the specified drawing view. | Activates the specified sheet view. |
AddChamferDim | Adds a chamfer dimension. | Add Chamfer dimensions. |
AddHoleCallout2 | Adds a hole callout at the specified position to the hole whose edge is selected. | Adds a hole callout at the specified location to the hole whose edge is selected. |
AddLineStyle | Adds a line style to the current drawing. | Adds a linetype to the current drawing. |
AlignHorz | Uses the selected edge to align the current drawing view. | Aligns the current drawing view with the selected edges. |
AlignOrdinate | Aligns the ordinate dimension. | Align ordinate dimensions. |
AlignVert | Uses the selected edge to align the current drawing view. | Aligns the current drawing view with the selected edges. |
AttachAnnotation | Attaches an existing annotation to a drawing sheet or view. | Attach an existing note to a drawing sheet or view. |
AttachDimensions | Attaches unattached dimensions. | Attach dimensions not attached. |
AutoBalloon5 | Automatically inserts BOM balloons in selected drawing views. | Automatically inserts BOM balloons in the selected drawing view. |
AutoDimension | Automatically dimensions the selected drawing view. | Automatically dimension selected drawing views. |
BreakView | Breaks the drawing view along the existing break lines. | Breaks a drawing view along an existing break line. |
ChangeComponentLayer | Puts the selected components on the specified layer. | Places the selected component on the specified layer. |
ChangeOrdDir | Changes the ordinate direction. | Change the ordinate direction. |
ChangeRefConfigurationOfFlatPatternView | Changes the referenced configuration of the flat-pattern view. | Change the reference configuration for plan mode views. |
Create1stAngleViews2 | Creates standard three orthographic views (first angle projection) for the specified model. | Creates three standard orthographic views (first angle projection) for the specified model. |
Create3rdAngleViews2 | Creates standard three orthographic views (third angle projection) for the specified model. | Creates three standard orthographic views (third angle projection) for the specified model. |
CreateAngDim4 | Creates a non-associative angular dimension. | Creates a non associative angular dimension. |
CreateAutoBalloonOptions | Creates an object that stores auto balloon options. | Create an object that stores automatic balloon options. |
CreateAuxiliaryViewAt2 | Creates an auxiliary view based on a selected edge in a drawing view. | Creates a secondary view based on the selected edges in the drawing view. |
CreateBreakOutSection | Creates a broken-out section in a drawing document. | Creates a broken section in a drawing document. |
CreateConstructionGeometry | Sets the selected sketch segments to be construction geometry instead of sketch geometry. | Sets the selected sketch segment as construction geometry instead of sketch geometry. |
CreateDetailViewAt4 | Creates a detail view in a drawing document. | Create a detail view in a drawing document. |
CreateDiamDim4 | Creates a non-associative diameter dimension. | Creates a non associative diameter dimension. |
CreateDrawViewFromModelView3 | Creates a drawing view on the current drawing sheet using the specified model view. | Creates a drawing view on the current drawing sheet using the specified model view. |
CreateFlatPatternViewFromModelView3 | Creates a flat-pattern view from a model view. | Create a plan pattern view from a model view. |
CreateLayer2 | Creates a layer for this document. | Create a layer for this document. |
CreateLinearDim4 | Creates a non-associative linear dimension. | Creates a non associative linear dimension. |
CreateOrdinateDim4 | Creates a non-associative ordinate dimension. | Creates a non associative ordinate dimension. |
CreateRelativeView | Creates a relative drawing view. | Create a relative drafting view. |
CreateSectionView | Creates a section view in the drawing using the selected section line. | Creates a section view in the drawing using the selected section line. |
CreateSectionViewAt5 | Creates the specified section view. | Creates the specified section view. |
CreateText2 | Creates a note containing the specified text at a given location. | Creates a comment containing the specified text at the given location. |
CreateUnfoldedViewAt3 | Creates an unfolded drawing view from the selected drawing view and places it in the drawing at the specified location. | Creates an expanded sheet view from the selected sheet view and places it in a specified location on the sheet. |
CreateViewport3 | Creates a an empty view in a drawing. | Create an empty view in the drawing. |
DeleteAllCosmeticThreads | Deletes all cosmetic threads, which do not have callouts, in a drawing of an assembly only. | Delete all unmarked decorative threads only in the drawing of the assembly. |
DeleteLineStyle | Deletes the specified line style from the current drawing. | Removes the specified linetype from the current drawing. |
Dimensions | Adds dimensions to the drawing from model. | Add dimensions from the model to the drawing. |
DragModelDimension | Copies or moves dimensions to a different drawing view. | Copy or move dimensions to different drawing views. |
DrawingViewRotate | Rotates the selected drawing view. | Rotates the selected drawing view. |
DropDrawingViewFromPalette2 | Moves the specified drawing view from the View Palette to the current drawing sheet. | Moves the specified drawing view from the view palette to the current drawing sheet. |
EditCenterMarkProperties | Edits center mark properties. | Edit center tag properties. |
EditOrdinate | Edits an ordinate dimension. | Edit ordinate dimensions. |
EditSelectedGtol | Gets the selected GTol to edit. | Gets the selected GTol to edit. |
EditSheet | Puts the current drawing sheet in edit mode. | Puts the current drawing in edit mode. |
EditSketch | Allows editing of a sketch in the selected drawing view or sheet. | Allows you to edit sketches in selected sheet views or sheets. |
EditTemplate | Puts the template of the current drawing sheet in edit mode. | Puts the template of the current drawing in edit mode. |
EndDrawing | Provides faster creation of entities in a drawing when used with IDrawingDoc::StartDrawing. | When used with IDrawingDoc::StartDrawing, you can create entities in your drawing faster. |
FeatureByName | Gets the specified feature in the drawing. | Gets the specified feature in the drawing. |
FlipSectionLine | Flips the cut direction of the selected section line. | Flips the cutting direction of the selected section line. |
GenerateViewPaletteViews | Adds the specified document's predefined drawing views to the View Palette. | Adds a predefined drawing view of the specified document to the view palette. |
GetCurrentSheet | Gets the currently active drawing sheet. | Gets the currently active drawing. |
GetDrawingPaletteViewNames | Gets the names of drawing views in the View Palette for the active drawing sheet. | Gets the name of the sheet view in the view palette of the active sheet. |
GetEditSheet | Gets whether the current drawing is in edit sheet mode or edit template mode. | Gets whether the current drawing is in edit sheet mode or edit template mode. |
GetFirstView | Gets the first drawing view on the current sheet. | Gets the first drafting view on the current sheet. |
GetInsertionPoint | Gets the current insertion (pick) point in a drawing. | Gets the current insertion (pick) point in the drawing. |
GetLineFontCount2 | Gets the a number line fonts supported by this drawing. | Gets the number line font supported by this drawing. |
GetLineFontId | Gets the associated line font ID. | Gets the associated line font ID. |
GetLineFontInfo2 | Gets the detailed information about the specified line font. | Gets the details of the specified line font. |
GetLineFontName2 | Gets the name of the specified line font. | Gets the name of the specified line font. |
GetLineStyles | Gets all of the line styles used in the current document. | Gets all line styles used in the current document. |
GetPenCount | Gets the number of pens currently defined in SOLIDWORKS. | Gets the number of transactions currently defined in SOLIDWORKS. |
GetPenInfo | Gets information about the pens used in SOLIDWORKS. | Get information about pens used in SOLIDWORKS. |
GetSheetCount | Gets the number of drawing sheets in this drawing. | Gets the number of drawing pages in this drawing. |
GetSheetNames | Gets a list of the names of the drawing sheets in this drawing. | Gets a list of sheet names in this sheet. |
GetViewCount | Gets all of the number of all of views, including the number of sheets, in this drawing document. | Gets the total number of all views in this drawing document, including the number of sheets. |
GetViews | Gets the all of the views, including the sheets, in this drawing document. | Gets all views in this drawing document, including sheets. |
HideEdge | Hides selected visible edges in a drawing document. | Hides the selected visible edges in the drawing document. |
HideShowDimensions | Sets whether to display suppressed dimensions as dimmed and hide them. | Sets whether suppressed dimensions are grayed out and hidden. |
HideShowDrawingViews | Sets whether to hide or show hidden drawing views. | Sets whether to hide or show hidden drawing views. |
IAddChamferDim | Adds a chamfer dimension. | Add Chamfer dimensions. |
IAddHoleCallout2 | Adds a hole callout at the specified position to the hole whose edge is selected. | Adds a hole callout at the specified location to the hole whose edge is selected. |
ICreateAngDim4 | Creates a non-associative angular dimension. | Creates a non associative angular dimension. |
ICreateAuxiliaryViewAt2 | Creates an auxiliary view based on a selected edge in a drawing view. | Creates a secondary view based on the selected edges in the drawing view. |
ICreateDiamDim4 | Creates a non-associative diameter dimension. | Creates a non associative diameter dimension. |
ICreateLinearDim4 | Creates a non-associative linear dimension. | Creates a non associative linear dimension. |
ICreateOrdinateDim4 | Creates a non-associative ordinate dimension. | Creates a non associative ordinate dimension. |
ICreateSectionViewAt5 | Creates a section view from the section line up to the specified distance at the specified distance. | Creates a section view at a specified distance from the section line. |
ICreateText2 | Creates a note containing the specified text at a given location. | Creates a comment containing the specified text at the given location. |
IEditSelectedGtol | Gets the selected GTol to edit. | Gets the selected GTol to edit. |
IFeatureByName | Gets the specified feature in the drawing. | Gets the specified feature in the drawing. |
IGetCurrentSheet | Gets the currently active drawing sheet. | Gets the currently active drawing. |
IGetFirstView | Gets the first drawing view on the current sheet. | Gets the first drafting view on the current sheet. |
IGetInsertionPoint | Gets the current insertion (pick) point in a drawing. | Gets the current insertion (pick) point in the drawing. |
IGetPenInfo | Gets information about the pens used in SOLIDWORKS. | Get information about pens used in SOLIDWORKS. |
IGetSheetNames | Gets a list of the names of the drawing sheets in this drawing. | Gets a list of sheet names in this sheet. |
IInsertDowelSymbol | Inserts a dowel pin symbol on the currently selected edge or edges. | Inserts a dowel symbol on the currently selected edge or edges. |
IInsertMultiJogLeader3 | Inserts a multi-jog leader. | Insert a multi break leader. |
IInsertRevisionCloud | Inserts a revision cloud annotation with the specified shape into a view or sheet. | Inserts a revision cloud annotation with a specified shape into a view or sheet. |
INewGtol | Creates a new GTol. | Create a new geometric tolerance. |
InsertAngularRunningDim | Inserts an angular running dimension into this drawing. | Insert an angular running dimension in this drawing. |
InsertBaseDim | Inserts the base model dimensions into this drawing. | Insert the base model dimensions into this drawing. |
InsertBreakHorizontal | Inserts a horizontal break in the drawing view. | Inserts a horizontal break in a drawing view. |
InsertBreakVertical | Inserts a vertical break in this drawing. | Insert a vertical break in this drawing. |
InsertCenterLine2 | Inserts a centerline on the selected entities. | Inserts a centerline on the selected body. |
InsertCenterMark3 | Inserts a center mark in a drawing document. | Inserts a center mark in a drawing document. |
InsertCircularNotePattern | Inserts a circular note pattern using the selected note. | Insert circular note mode using the selected notes. |
InsertDowelSymbol | Inserts a dowel pin symbol on the currently selected edge or edges in this drawing. | Inserts a dowel symbol on the currently selected edge or edges in this drawing. |
InsertGroup | Inserts the currently selected items into a group (or view). | Inserts the currently selected item into a group (or view). |
InsertHorizontalOrdinate | Inserts a horizontal ordinate dimension into this drawing. | Insert a horizontal dimension in this drawing. |
InsertLinearNotePattern | Inserts a linear note pattern using the selected note. | Inserts a linear note mode using the selected note. |
InsertModelAnnotations3 | Inserts model annotations into this drawing document in the currently selected drawing view. | Inserts model notes into this drawing document in the currently selected drawing view. |
InsertModelDimensions | Inserts model dimensions into the selected drawing view according to the option specified. | Inserts the model dimensions into the selected drawing view according to the specified options. |
InsertModelInPredefinedView | Inserts the model into the predefined drawing views in the active drawing sheet. | Inserts the model into a predefined sheet view in the active sheet. |
InsertMultiJogLeader3 | Inserts a multi-jog leader. | Insert a multi break leader. |
InsertNewNote2 | Creates a new note in this drawing. | Create a new note in this drawing. |
InsertOrdinate | Inserts an ordinate dimension into this drawing. | Insert ordinate dimensions in this drawing. |
InsertRefDim | Inserts reference dimensions in this drawing. | Insert reference dimensions in this drawing. |
InsertRevisionCloud | Inserts a revision cloud annotation with the specified shape into a view or sheet. | Inserts a revision cloud annotation with a specified shape into a view or sheet. |
InsertRevisionSymbol | Inserts a revision symbol note in this drawing. | Insert a revision symbol note in this drawing. |
InsertTableAnnotation2 | Inserts a table annotation in this drawing. | Insert a table note in this drawing. |
InsertThreadCallout | Inserts a thread callout into this drawing. | Insert a thread dimension in this drawing. |
InsertVerticalOrdinate | Inserts a vertical ordinate dimension in this drawing. | Inserts a vertical ordinate dimension in this drawing. |
InsertWeldSymbol | Creates a weld symbol located at the last edge selection. | Creates a welding symbol at the last edge selection. |
IReorderSheets | Reorders the drawing sheets per their positions in the input array. | Reorder the sheets according to their position in the input array. |
IsolateChangedDimensions | Isolates changed dimensions. | Isolate changed dimensions. |
LoadLineStyles | Loads the specified line styles into the current drawing. | Loads the specified linetype into the current drawing. |
MakeSectionLine | Makes a section line from a set of connected sketch lines. | Make a section line from a set of connected sketch lines. |
ModifySurfaceFinishSymbol | Modifies the selected surface finish symbol. | Modifies the selected surface texture symbol. |
NewGtol | Creates a new GTol object and returns the pointer to that object. | Create a new GTol object and return a pointer to it. |
NewNote | Creates a new note at the selected location. | Creates a new note at the selected location. |
NewSheet4 | Creates a new drawing sheet in this drawing document. | Create a new drawing sheet in this drawing document. |
OnComponentProperties | Displays the Component Properties dialog for the selected view. | Displays the component properties dialog box for the selected view. |
PasteSheet | Copies and pastes a drawing sheet to the specified location of the drawing document, optionally renaming whenever duplicate names occur. | Copy and paste the drawing to the specified location of the drawing document, and you can choose to rename it when duplicate names appear. |
ReorderSheets | Reorders the drawing sheets per their positions in the input array. | Reorder the sheets according to their position in the input array. |
ReplaceViewModel | Replaces the specified instances of a model in the specified drawing views. | Replaces the specified instance of the model in the specified drawing view. |
ResolveOutOfDateLightWeightComponents | Resolves out-of-date lightweight components in the selected drawing view or drawing sheet. | Resolve obsolete lightened components in the selected drawing view or drawing sheet. |
RestoreRotation | Restores rotation for the selected drawing view. | Restores the rotation of the selected drawing view. |
SaveLineStyles | Exports to a file the specified line styles in the current drawing. | Exports the linetypes specified in the current drawing to a file. |
SetCurrentLayer | Sets the current layer used by this document. | Sets the current layer used by this document. |
SetLineColor | Sets the line color for a selected edge or sketch entity. | Sets the line color of the selected edge line or sketch entity. |
SetLineStyle | Sets the style or font for the line for a selected edge or sketch entity. | Sets the style or font of the line for the selected edge line or sketch entity. |
SetLineWidth | Sets the line thickness for a selected edge or sketch entity to a SOLIDWORKS-supplied weight (width). | Sets the lineweight of the selected edge line or sketch entity to the thickness (width) provided by SOLIDWORKS. |
SetLineWidthCustom | Sets the line thickness to the specified custom width for a selected edge or sketch entity. | Sets the line thickness to the specified custom width of the selected edge line or sketch entity. |
SetSheetsSelected | Sets the specified drawing sheets whose setups to modify. | Sets the specified sheet whose settings you want to change. |
SetupSheet6 | Sets up the specified drawing sheet. | Sets the specified sheet. |
SheetNext | Moves to the next sheet in the drawing. | Move to the next sheet in the drawing. |
SheetPrevious | Returns to the previous sheet in a drawing. | Returns to the previous sheet in the drawing. |
ShowEdge | Shows the selected hidden edges in a drawing document. | Displays the selected hidden edges in the drawing document. |
SketchDim | Inserts a sketch dimension in this drawing. | Insert sketch dimensions in this drawing. |
StartDrawing | Provides faster creation of entities within a drawing. | Provides faster creation of solids in drawings. |
SuppressView | Hides the selected drawing view. | Hides the selected drawing view. |
TranslateDrawing | Translates the entire drawing. | Translate the entire drawing. |
UnBreakView | Removes a break in the selected drawing view. | Deletes breaks in the selected drawing view. |
UnsuppressView | Hides the selected drawing view. | Hides the selected drawing view. |
ViewDisplayHidden | Sets the current display mode to Hidden Lines Removed. | Set the current display mode to hidden line deleted. |
ViewDisplayHiddengreyed | Sets the current display mode to Hidden Lines Visible. | Sets the current display mode to visible hidden lines. |
ViewDisplayShaded | Sets the current display mode to Shaded. | Sets the current display mode to shadow. |
ViewDisplayWireframe | Sets the current display mode to Wireframe. | Sets the current display mode to wireframe. |
ViewFullPage | Fits the drawing to the full page. | Fit the drawing to the whole page. |
ViewHlrQuality | Toggles the Hidden Lines Removed mode for the drawing view. | Toggles hidden line removal mode in drafting view. |
ViewModelEdges | Toggles the mode for viewing model edges when in shaded mode. | Toggles the mode of viewing model edges in shaded mode. |
ViewTangentEdges | Toggles display of tangent edges in the selected drawing view. | Toggles the display of tangent edges in the selected drawing view. |
System.bool ActivateSheet( System.string Name)
This example shows how to copy and paste drawing sheets. //---------------------------------------------------------- // Preconditions: // 1. Open a drawing document containing one sheet // named Sheet1. // 2. Open the Immediate window. // // Postconditions: // 1. Activates Sheet1. // 2. Copy and pastes Sheet1 as Sheet1(2) and activates Sheet1(2). // 3. Copy and pastes Sheet1 as Sheet1(3) and activates Sheet1(3). // 4. Examine the FeatureManager design tree and Immediate window. //---------------------------------------------------------- using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; using System; using System.Diagnostics; namespace Macro1CSharp.csproj { public partial class SolidWorksMacro { public void Main() { DrawingDoc Part = default(DrawingDoc); ModelDoc2 swModel = default(ModelDoc2); bool boolstatus = false; swModel = (ModelDoc2)swApp.ActiveDoc; Part = (DrawingDoc)swModel; if ((Part == null)) { Debug.Print(" Please open a drawing document. "); return; } Sheet currentsheet = default(Sheet); currentsheet = (Sheet)Part.GetCurrentSheet(); Part.ActivateSheet(currentsheet.GetName()); Debug.Print("Active sheet: " + currentsheet.GetName()); boolstatus = swModel.Extension.SelectByID2("Sheet1", "SHEET", 0.09205356547875, 0.10872368523, 0, false, 0, null, 0); swModel.EditCopy(); boolstatus = Part.PasteSheet((int)swInsertOptions_e.swInsertOption_BeforeSelectedSheet, (int)swRenameOptions_e.swRenameOption_No); currentsheet = (Sheet)Part.GetCurrentSheet(); Part.ActivateSheet(currentsheet.GetName()); Debug.Print("Active sheet: " + currentsheet.GetName()); boolstatus = swModel.Extension.SelectByID2("Sheet1", "SHEET", 0.09205356547875, 0.10872368523, 0, false, 0, null, 0); swModel.EditCopy(); boolstatus = Part.PasteSheet((int)swInsertOptions_e.swInsertOption_AfterSelectedSheet, (int)swRenameOptions_e.swRenameOption_No); currentsheet = (Sheet)Part.GetCurrentSheet(); Part.ActivateSheet(currentsheet.GetName()); Debug.Print("Active sheet: " + currentsheet.GetName()); } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
This example shows how to determine which sheets in a drawing are loaded. //---------------------------------------------- // Preconditions: // 1. Click File > Open. // 2. Browse to public_documents\samples\tutorial\advdrawings. // 3. Select foodprocessor.slddrw. // 4. Click Select sheets to open > Selected > Sheet1* (Load) > OK > Open. // 5. Open the Immediate window. // // Postconditions: // 1. Loads Sheet1 only. // 2. Mouse over the Sheet2, Sheet3, and Sheet4 tabs and // examine the Immediate window to verify step 1. // // NOTE: Because this drawing is used elsewhere, do not save // changes. //---------------------------------------------- using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System; using System.Diagnostics; namespace IsLoadedSheetCSharp.csproj { partial class SolidWorksMacro { public void Main() { ModelDoc2 swModel = default(ModelDoc2); DrawingDoc swDraw = default(DrawingDoc); object[] vSheetName = null; int i = 0; bool bRet = false; string sheetName; swModel = (ModelDoc2)swApp.ActiveDoc; swDraw = (DrawingDoc)swModel; // Get the sheets in the drawing document vSheetName = (object[])swDraw.GetSheetNames(); // Traverse the sheets and determine whether // they're loaded for (i = 0; i < vSheetName.Length; i++) { sheetName = (string)vSheetName[i]; bRet = swDraw.ActivateSheet(sheetName); Sheet swSheet = default(Sheet); swSheet = (Sheet)swDraw.GetCurrentSheet(); if ((swSheet.IsLoaded())) { Debug.Print(vSheetName[i] + " is loaded."); } else { Debug.Print(vSheetName[i] + " is not loaded."); } } } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
System.bool ActivateView( System.string ViewName)
This example demonstrates firing Undo pre- and post-notification events in a drawing document. //--------------------------------------------------------------------------- // Preconditions: Open public_documents\samples\tutorial\AutoCAD\7550-021.slddrw. // // Postconditions: // 1. Selects and deletes the note in Drawing View1. // 2. Undoes the deleted note. // 3. Fires pre-notification event indicating that an undo action is about to // occur and fires post-notification event indicating that an undo // action occurred. // 4. Click OK to close each message box. // // NOTE: Because the drawing is used elsewhere, do not save changes. //--------------------------------------------------------------------------- using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System; using System.Collections; using System.Windows.Forms; namespace UndoPostNotifyDrawingCSharp.csproj { partial class SolidWorksMacro { public DrawingDoc swDrawing; public void Main() { ModelDoc2 swModel = default(ModelDoc2); ModelDocExtension swModelDocExt = default(ModelDocExtension); bool boolstatus = false; Hashtable openDrawing = default(Hashtable); swModel = (ModelDoc2)swApp.ActiveDoc; swModelDocExt = (ModelDocExtension)swModel.Extension; // Event notification swDrawing = (DrawingDoc)swModel; openDrawing = new Hashtable(); AttachEventHandlers(); // Activate the drawing view that contains // the note you want to delete boolstatus = swDrawing.ActivateView("Drawing View3"); boolstatus = swModelDocExt.SelectByID2("DetailItem77@Drawing View3", "NOTE", 0.3058741216774, 0.1870419466786, 0, false, 0, null, 0); // Delete the selected note swModel.EditDelete(); // Undo deletion of note swModel.EditUndo2(1); // Post-notification is fired // Rebuild the drawing swModel.ForceRebuild3(true); } public void AttachEventHandlers() { AttachSWEvents(); } public void AttachSWEvents() { swDrawing.UndoPostNotify += this.swDrawing_UndoPostNotify; swDrawing.UndoPreNotify += this.swDrawing_UndoPreNotify; } private int swDrawing_UndoPostNotify() { // Display message after Undo // NOTE: Because the message box may be displayed // behind an opened window, you might not see it. // If so, then check the Taskbar. MessageBox.Show("An undo post-notification event has been fired."); return 1; } private int b() { // Display message after Undo // NOTE: Because the message box may be displayed // behind an opened window, you might not see it. // If so, then check the Taskbar. MessageBox.Show("An Undo pre-notification event has been fired."); return 1; } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
//This example shows how to automatically insert a model's dimensions marked for drawings //into a drawing. //--------------------------------------------------------------------------- // Preconditions: // 1. Assembly document to open exists. // 2. Run the macro. // // Postconditions: // 1. A new drawing document is opened. // 2. A drawing view of the assembly document is created. // 3. The dimensions in the assembly document that are marked for drawings, // including any duplicate dimensions, appear in the drawing view. // 4. The dimensions in the drawing, which are annotations, // are selected and marked. //--------------------------------------------------------------------------- using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; using System; namespace SelectAnnotationsCSharp.csproj { public partial class SolidWorksMacro { public void Main() { ModelDoc2 swModel; ModelDocExtension swModelDocExt; DrawingDoc swDrawing; SelectionMgr swSelmgr; View swView; object[] annotations; object selAnnot; Annotation swAnnotation; SelectData swSelData; int mark; string retval; bool status; retval = swApp.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplateDrawing); swModel = (ModelDoc2)swApp.NewDocument(retval, 0, 0, 0); swDrawing = (DrawingDoc)swModel; swModelDocExt = (ModelDocExtension)swModel.Extension; swSelmgr = (SelectionMgr)swModel.SelectionManager; // Create drawing from assembly swView = (View)swDrawing.CreateDrawViewFromModelView3("C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\wrench.sldasm", "*Front", 0.1314541543147, 0.1407887187817, 0); // Select and activate the view status = swModelDocExt.SelectByID2("Drawing View1", "DRAWINGVIEW", 0, 0, 0, false, 0, null, 0); status = swDrawing.ActivateView("Drawing View1"); swModel.ClearSelection2(true); // Insert the annotations marked for the drawing annotations = (object[])swDrawing.InsertModelAnnotations3((int)swImportModelItemsSource_e.swImportModelItemsFromEntireModel, (int)swInsertAnnotation_e.swInsertDimensionsMarkedForDrawing, true, false, false, false); // Select and mark each annotation swSelData = swSelmgr.CreateSelectData(); mark = 0; foreach (object annot in annotations) { selAnnot = annot; swAnnotation = (Annotation)selAnnot; status = swAnnotation.Select3(true, swSelData); swSelData.Mark = mark; mark = mark + 1; } } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
System.bool AttachAnnotation( System.int Option)
//This example shows how to attach an existing annotation to a drawing view. //---------------------------------------------------------------------------- // Preconditions: Open public_documents\samples\tutorial\api\replaceview.slddrw. // // Postconditions: // 1. Inserts a note annotation n the drawing. // 2. Selects the annotation. // 3. Appends a face in a drawing view to the selection list. // 4. Attaches the annotation to the selected face. // 5. Examine the drawing. // 6. Close the drawing without saving it. // --------------------------------------------------------------------------- using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; using System; namespace AttachAnnotation_CSharp.csproj { partial class SolidWorksMacro { ModelDoc2 part; DrawingDoc draw; Note aNote; Annotation anAnnot; SelectData selectData = null; int ret; bool boolstatus; public void Main() { part = (ModelDoc2)swApp.ActiveDoc; draw = (DrawingDoc)part; boolstatus = draw.ActivateSheet("Sheet1"); aNote = (Note)draw.CreateText2("This is a note.", 0.21, 0.12, 0, 0.005, 0); anAnnot = (Annotation)aNote.GetAnnotation(); ret = anAnnot.SetLeader3(swLeaderStyle_e.swBENT, swLeaderSide_e.swLS_SMART, true, false, false, false); anAnnot.Select3(false, selectData); boolstatus = draw.ActivateView("Drawing View1"); boolstatus = part.Extension.SelectByID2("", "FACE", 0.0783563575357558, 0.17448024010205, -499.965138294658, true, 0, null, 0); draw.AttachAnnotation(swAttachAnnotationOption_e.swAttachAnnotationOption_View); } public SldWorks swApp; } }
System.object AutoBalloon5( AutoBalloonOptions BalloonOptions)
//This example shows how to automatically add BOM balloons to a drawing view. //------------------------------------------------------------------------------ // Preconditions: Open a drawing with a bill of materials (BOM) table. // // Postconditions: BOM balloons are added to the view. //------------------------------------------------------------------------------ using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; namespace AutoBalloon_CSharp.csproj { partial class SolidWorksMacro { ModelDoc2 Part; DrawingDoc Draw; object vNotes; AutoBalloonOptions autoballoonParams; bool boolstatus; public void Main() { Part = (ModelDoc2)swApp.ActiveDoc; Draw = (DrawingDoc)Part; boolstatus = Draw.ActivateView("Drawing View1"); boolstatus = Part.Extension.SelectByID2("Drawing View1", "DRAWINGVIEW", 0, 0, 0, false, 0, null, 0); autoballoonParams = Draw.CreateAutoBalloonOptions(); autoballoonParams.Layout = (int)swBalloonLayoutType_e.swDetailingBalloonLayout_Square; autoballoonParams.ReverseDirection = false; autoballoonParams.IgnoreMultiple = true; autoballoonParams.InsertMagneticLine = true; autoballoonParams.LeaderAttachmentToFaces = true; autoballoonParams.Style = (int)swBalloonStyle_e.swBS_Circular; autoballoonParams.Size = (int)swBalloonFit_e.swBF_5Chars; autoballoonParams.UpperTextContent = (int)swBalloonTextContent_e.swBalloonTextItemNumber; autoballoonParams.Layername = "-None-"; autoballoonParams.ItemNumberStart = 1; autoballoonParams.ItemNumberIncrement = 1; autoballoonParams.ItemOrder = (int)swBalloonItemNumbersOrder_e.swBalloonItemNumbers_DoNotChangeItemNumbers; autoballoonParams.EditBalloons = true; autoballoonParams.EditBalloonOption = (int)swEditBalloonOption_e.swEditBalloonOption_Resequence; vNotes = Draw.AutoBalloon5(autoballoonParams); } public SldWorks swApp; } }
System.int AutoDimension(
System.int EntitiesToDimension,
System.int HorizontalScheme,
System.int HorizontalPlacement,
System.int VerticalScheme,
System.int VerticalPlacement)
//This example shows how to autodimension a selected drawing view. //----------------------------------------------------------------- // Preconditions: Verify that the specified drawing document to // open exists. // // Postconditions: // 1. Opens the specified drawing document. // 2. Activates Drawing View1. // 3. Selects a vertex. // 4. Autodimensions the drawing view based on the // selected vertex. // 5. Examine the drawing. // // NOTE: Because the drawing is used elsewhere, do not save changes. //------------------------------------------------------------------ using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; using System; namespace AutodimensionCSharp.csproj { public partial class SolidWorksMacro { public void Main() { ModelDoc2 swModel = default(ModelDoc2); DrawingDoc swDrawing = default(DrawingDoc); ModelDocExtension swModelDocExt = default(ModelDocExtension); bool status = false; string fileName = null; int errors = 0; int warnings = 0; int selmark = 0; int ret = 0; // Open drawing document of part fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\advdrawings\\foodprocessor.slddrw"; swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocDRAWING, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); swDrawing = (DrawingDoc)swModel; status = swDrawing.ActivateView("Drawing View1"); swModelDocExt = (ModelDocExtension)swModel.Extension; // Select drawing view status = swModelDocExt.SelectByID2("Drawing View1", "DRAWINGVIEW", 0, 0, 0, false, 0, null, 0); // Horizontal and vertical datum, or a vertex datum, baselines for // dimension creation // These are optional; if not selected, autodimension uses default datums, // the leftmost and bottommost edges selmark = (int)swAutodimMark_e.swAutodimMarkHorizontalDatum; selmark = (int)swAutodimMark_e.swAutodimMarkVerticalDatum; selmark = (int)swAutodimMark_e.swAutodimMarkOriginDatum; // Select a vertex status = swModelDocExt.SelectByID2("", "VERTEX", 0.20215546544586, 0.2496899375, 0.00479999999998881, true, selmark, null, 0); // Autodimensions the drawing view based on the selected vertex ret = swDrawing.AutoDimension((int)swAutodimEntities_e.swAutodimEntitiesBasedOnPreselect, (int)swAutodimScheme_e.swAutodimSchemeBaseline, (int)swAutodimHorizontalPlacement_e.swAutodimHorizontalPlacementAbove, (int)swAutodimScheme_e.swAutodimSchemeBaseline, (int)swAutodimVerticalPlacement_e.swAutodimVerticalPlacementRight); } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
void BreakView()
//This example shows how to create and remove a broken view. //---------------------------------------------------------------------------- // Preconditions: // 1. Verify that the specified file to open exists. // 2. Open the Immediate window. // // Postconditions: // 1. Opens the specified drawing and selects Drawing View1. // 2. Examine the drawing, then press F5. // 3. Inserts break lines in Drawing View1. // 4. Examine the drawing, then press F5. // 5. Modifies the positions of the break lines and breaks the view. // 6. Examine the drawing, then press F5. // 7. Removes the break from Drawing View1. // 8. Examine the drawing and the Immediate window. // // NOTE: Because this drawing document is used elsewhere, // do not save changes. //---------------------------------------------------------------------------- using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; using System; using System.Diagnostics; namespace BreakViewDrawingDocCSharp.csproj { public partial class SolidWorksMacro { public void Main() { ModelDoc2 swModel; DrawingDoc swDrawingDoc; ModelDocExtension swModelDocExt; SelectionMgr swSelectionManager; SelectData swSelectData; View swView; BreakLine swBreakLine; string fileName; bool status; int errors = 0; int warnings = 0; fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\box.slddrw"; swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocDRAWING, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); swModel = (ModelDoc2)swApp.ActiveDoc; swDrawingDoc = (DrawingDoc)swModel; swModelDocExt = (ModelDocExtension)swModel.Extension; // Activate and select the view to break status = swDrawingDoc.ActivateView("Drawing View1"); status = swModelDocExt.SelectByID2("Drawing View1", "DRAWINGVIEW", 0, 0, 0, false, 0, null, 0); swSelectionManager = (SelectionMgr)swModel.SelectionManager; swSelectData = (SelectData)swSelectionManager.CreateSelectData(); swView = (View)swSelectionManager.GetSelectedObject6(1, -1); System.Diagnostics.Debugger.Break(); // Examine the drawing; press F5 // Insert the break lines swBreakLine = (BreakLine)swView.InsertBreak(0, -0.0291950859897372, 0.0198236302285804, 1); System.Diagnostics.Debugger.Break(); // Break lines inserted; press F5 // Reset position of break lines status = swBreakLine.SetPosition(-0.03, 0.05); swModel.EditRebuild3 Debug.Print("Break line: "); Debug.Print(" Selected: " + swBreakLine.Select(true, null)); Debug.Print(" Style: " + swBreakLine.Style); Debug.Print(" Orientation: " + swBreakLine.Orientation); Debug.Print(" Position: " + swBreakLine.GetPosition(0)); swDrawingDoc.BreakView(); System.Diagnostics.Debugger.Break(); // Positions of the break lines are modified, and view is broken // Press F5 status = swModelDocExt.SelectByID2("Drawing View1", "DRAWINGVIEW", 0, 0, 0, false, 0, null, 0); swDrawingDoc.UnBreakView(); // Break is removed } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
void ChangeComponentLayer(
System.string Layername,
System.bool AllViews)
This example shows how to create a layer for the part in the selected drawing view. '---------------------------------------------------------------------------- ' Preconditions: ' 1. Open a drawing of a part. ' 2. Select a drawing view in the FeatureManager design tree. ' 3. Open the Immediate window. ' ' Postconditions: ' 1. Creates a layer for the part in the selected drawing view. ' 2. Click the Layer Properties tool on the Line Format toolbar to verify ' that the newly created layer is selected in the Layers dialog box. ' 3. Examine the Immediate window. '---------------------------------------------------------------------------- Option Explicit Private Sub ChangeComponentLayer _ ( _ swApp As SldWorks.SldWorks, _ swDraw As SldWorks.DrawingDoc, _ sLayerName As String _ ) Dim bRet As Boolean ' Form a valid layer name sLayerName = Replace(sLayerName, "/", "_") sLayerName = Replace(sLayerName, "@", "_") bRet = swDraw.CreateLayer2( _ sLayerName, _ "Layer for part in " & sLayerName, _ 0, swLineCONTINUOUS, swLW_NORMAL, True, True) ' Change in all drawing views swDraw.ChangeComponentLayer sLayerName, True End Sub Sub main() Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2 Dim swDraw As SldWorks.DrawingDoc Dim swSelMgr As SldWorks.SelectionMgr Dim swView As SldWorks.View Dim swDrawModel As SldWorks.ModelDoc2 Dim swDrawPart As SldWorks.PartDoc Dim vBody As Variant Dim swBody As SldWorks.Body2 Dim swFace As SldWorks.Face2 Dim swEnt As SldWorks.Entity Dim nErrors As Long Dim nWarnings As Long Dim bRet As Boolean Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc Set swDraw = swModel Set swSelMgr = swModel.SelectionManager Set swView = swSelMgr.GetSelectedObject6(1, -1) Set swDrawModel = swApp.OpenDoc6(swView.GetReferencedModelName, swDocPART, swOpenDocOptions_Silent, "", nErrors, nWarnings) Set swDrawPart = swDrawModel Debug.Print "File = " & swModel.GetPathName Debug.Print " View = " & swView.Name Debug.Print " View Model = " & swView.GetReferencedModelName vBody = swDrawPart.GetBodies2(swSolidBody, True) Set swBody = vBody(0) Set swFace = swBody.GetFirstFace Set swEnt = swFace bRet = swView.SelectEntity(swEnt, False) ChangeComponentLayer swApp, swDraw, swView.Name End Sub
System.object CreateDetailViewAt4(
System.double X,
System.double Y,
System.double Z,
System.int Style,
System.double Scale1,
System.double Scale2,
System.string LabelIn,
System.int Showtype,
System.bool FullOutline,
System.bool JaggedOutline,
System.bool NoOutline,
System.int ShapeIntensity)
//This example shows how to create a detail circle and a detail view. //--------------------------------------------------------------------------- // Preconditions: // 1. Verify that the drawing to open exists. // 2. Open the Immediate window. // // Postconditions: // 1. Opens the specified drawing. // 2. Activates Drawing View4. // 3. Creates a detail circle and a detail view using the visible // corner of Drawing View4. // 4. Activates the detail view. // 5. Gets and sets some properties of the detail circle and detail view. // 6. Examine the drawing document and Immediate window. // // NOTE: Because the drawing is used elsewhere, do not save changes. //------------------------------------------------------------------------------ using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; using System; using System.Diagnostics; namespace Macro1CSharp.csproj { partial class SolidWorksMacro { public void Main() { ModelDoc2 swModel = default(ModelDoc2); DrawingDoc swDrawing = default(DrawingDoc); SketchManager swSketchManager = default(SketchManager); SketchSegment swSketchSegment = default(SketchSegment); View swView = default(View); DetailCircle swDetailCircle = default(DetailCircle); SelectionMgr swSelMgr = default(SelectionMgr); SelectData swSelData = default(SelectData); string fileName = null; bool status = false; int errors = 0; int warnings = 0; // Open drawing fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\replaceview.slddrw"; swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocDRAWING, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); swDrawing = (DrawingDoc)swModel; swSelMgr = (SelectionMgr)swModel.SelectionManager; swSelData = (SelectData)swSelMgr.CreateSelectData(); swApp.ActivateDoc3("replaceview - Sheet1", false, (int)swRebuildOnActivation_e.swDontRebuildActiveDoc, ref errors); // Activate Drawing View4 and create detail circle and detail view status = swDrawing.ActivateView("Drawing View4"); swSketchManager = (SketchManager)swModel.SketchManager; swSketchSegment = (SketchSegment)swSketchManager.CreateCircle(0.007581, 0.053509, 0.0, 0.013533, 0.016475, 0.0); swView = (View)swDrawing.CreateDetailViewAt4(0.22305342706156, 0.0762140266484527, 0, (int)swDetViewStyle_e.swDetViewSTANDARD, 1, 1, "A", (int)swDetCircleShowType_e.swDetCircleCIRCLE, true, true, false, 5); swModel.ClearSelection2(true); // Activate detail view status = swDrawing.ActivateView("Drawing View5"); // Get and set some properties of detail circle and detail view swDetailCircle = (DetailCircle)swView.GetDetail(); Debug.Print("Detail circle:"); Debug.Print(" Selected: " + swDetailCircle.Select(true, null)); Debug.Print(" Label: " + swDetailCircle.GetLabel()); Double xpos; Double ypos; swDetailCircle.GetLabelPosition(out xpos, out ypos); Debug.Print(" Label X position: " + xpos); Debug.Print(" Label Y position: " + ypos); Debug.Print(" Type of circle: " + swDetailCircle.GetDisplay()); Debug.Print(" Name: " + swDetailCircle.GetName()); Debug.Print(" Style: " + swDetailCircle.GetStyle()); Debug.Print(" Default document text formatting? " + swDetailCircle.GetUseDocTextFormat()); if (swDetailCircle.NoOutline == false) { Debug.Print(" No outline? False"); if (swDetailCircle.JaggedOutline == true) { swDetailCircle.ShapeIntensity = 2; Debug.Print(" Jagged outline and shape intensity? True and 2"); } } } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
System.bool CreateBreakOutSection(
System.double Depth)
//This example shows how to create a broken-out section in a drawing view. //---------------------------------------------------------------------------- // Preconditions: // 1. Open a drawing. // 2. Select Drawing View1. // // Postconditions: A broken-out section is created in Drawing View1 // using the specified closed spline. // --------------------------------------------------------------------------- using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; namespace CreateBreakOutSection_CSharp.csproj { partial class SolidWorksMacro { ModelDoc2 Part; object pointArray; double[] points = new double[12]; SketchSegment skSegment; SelectData selectData = null; DrawingDoc dDoc; public void Main() { Part = (ModelDoc2)swApp.ActiveDoc; points[0] = -0.0544316967839374; points[1] = 0.0413619530906299; points[2] = 0; points[3] = 0.0530556603589196; points[4] = 0.0413619530906299; points[5] = 0; points[6] = 0.00783232107320536; points[7] = 0.00720299635749822; points[8] = 0; points[9] = -0.0544316967839374; points[10] = 0.0413619530906299; points[11] = 0; pointArray = points; skSegment = Part.SketchManager.CreateSpline((pointArray)); skSegment.Select4(true, selectData); dDoc = (DrawingDoc)Part; dDoc.CreateBreakOutSection(0.00254); Part.ClearSelection2(true); } public SldWorks swApp; } }
View CreateRelativeView(
System.string ModelName,
System.double XPos,
System.double YPos,
System.int ViewDirFront,
System.int ViewDirRight)
//This example shows how to create a relative drawing view. // ****************************************************************************** // Preconditions: // 1. Open public_documents\samples\tutorial\api\maingrip.sldprt. // 2. Select File > Make Drawing from Part. // 3. Run the macro. // // Postconditions: // 1. Iterates through the drawing views // in the View Palette and drops // *Current drawing view in the drawing. // 2. Activates the part. // 3. Selects two faces for the relative drawing view. // 4. Activates the drawing. // 5. Creates and inserts a relative drawing // view using the selected faces. // // NOTE: Because the part document is used elsewhere, do not // save any changes when closing it. // ****************************************************************************** using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; using System; namespace CreateRelativeViewCSharp.csproj { partial class SolidWorksMacro { ModelDoc2 swModel; DrawingDoc swDrawing; View swView; ModelDocExtension swModelDocExt; string fileName; bool status; int errors; int warnings; int numViews; object[] viewNames; string viewName; string viewPaletteName; int i; public void Main() { swDrawing = (DrawingDoc)swApp.ActiveDoc; // Get number of views on View Palette numViews = 0; viewNames = (object[])swDrawing.GetDrawingPaletteViewNames(); // Iterate through views on View Palette // When view name equals *Current, drop // that view in drawing if (!((viewNames == null))) { numViews = (viewNames.GetUpperBound(0) - viewNames.GetLowerBound(0)); for (i = 0; i <= numViews; i++) { viewPaletteName = (string)viewNames[i]; if ((viewPaletteName == "*Current")) { swView = (View)swDrawing.DropDrawingViewFromPalette2(viewPaletteName, 0.0, 0.0, 0.0); } } } // Activate the part document and // select two faces for the relative drawing view swApp.ActivateDoc3("maingrip.sldprt", false, (int)swRebuildOnActivation_e.swUserDecision, ref errors); swModel = (ModelDoc2)swApp.ActiveDoc; swModelDocExt = (ModelDocExtension)swModel.Extension; swModel.ClearSelection2(true); status = swModelDocExt.SelectByID2("", "FACE", 0.0466263268498324, 0.00558799999987514, -0.00617351393179888, false, 1, null, 0); status = swModelDocExt.SelectByID2("", "FACE", 0.0504738910727269, 0.00167315253537481, -0.00496149996774875, true, 2, null, 0); // Activate the drawing document // Create and insert the relative drawing view using // the selected faces // Activate the relative drawing view swApp.ActivateDoc3("maingrip - Sheet1", false, (int)swRebuildOnActivation_e.swUserDecision, ref errors); swDrawing = (DrawingDoc)swApp.ActiveDoc; fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\maingrip.sldprt"; swView = (View)swDrawing.CreateRelativeView(fileName, 0.203608914116486, 0.493530187561698, (int)swRelativeViewCreationDirection_e.swRelativeViewCreationDirection_FRONT, (int)swRelativeViewCreationDirection_e.swRelativeViewCreationDirection_RIGHT); status = swDrawing.ActivateView("Drawing View2"); } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
View CreateSectionViewAt5(
System.double X,
System.double Y,
System.double Z,
System.string SectionLabel,
System.int Options,
System.object ExcludedComponents,
System.double SectionDepth)
//This example creates a section view and sets and gets some of the section view's data. //-------------------------------------------------------------------------- // Preconditions: // 1. Open public_documents\samples\tutorial\driveworksxpress\mobile gantry.slddrw // 2. Open the Immediate window. // // Postconditions: // 1. Creates a section view of Drawing View4. // 2. Sets and gets some section view settings. // 3. Examine the drawing and the Immediate window. // // NOTE: Because this drawing is used elsewhere, do not save changes. //-------------------------------------------------------------------------- using System; using System.Diagnostics; using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; namespace CreateSectionView_CSharp.csproj { partial class SolidWorksMacro { ModelDoc2 swModel; DrawingDoc swDrawing; SketchManager swSketchMgr; SketchSegment swSketchSegment; object excludedComponents; View swView; DrSection swSectionView; bool boolstatus; public void Main() { swModel = (ModelDoc2)swApp.ActiveDoc; swDrawing = (DrawingDoc)swModel; // Activate the view for which you want to create a section view boolstatus = swDrawing.ActivateView("Drawing View4"); swModel.ClearSelection2(true); // Create section-view line swSketchMgr = swModel.SketchManager; swSketchSegment = swSketchMgr.CreateLine(-1.383705, 2.078706, 0.0, 2.747162, 0.0441, 0.0); // Create the section view at the specified coordinates // and up to the specified distance from the section-view line excludedComponents = null; swView = swDrawing.CreateSectionViewAt5(0.1604082711061, 0.2048687170364, 0, "D", 32, (excludedComponents), 0.00835); Debug.Print("View data: "); Debug.Print(" Emphasize outlines of section views? " + swView.EmphasizeOutline); swSectionView = (DrSection)swView.GetSection(); // Set some section-view settings swSectionView.SetAutoHatch(true); swSectionView.SetLabel2("ABCD"); swSectionView.SetDisplayOnlySurfaceCut(false); swSectionView.SetPartialSection(false); swSectionView.SetReversedCutDirection(false); swSectionView.SetScaleWithModelChanges(true); swSectionView.CutSurfaceBodies = true; swSectionView.DisplaySurfaceBodies = true; swSectionView.ExcludeSliceSectionBodies = false; // Get some section-view settings Debug.Print("Section view data: "); Debug.Print(" Label: " + swSectionView.GetLabel()); Debug.Print(" Name of section line: " + swSectionView.GetName()); Debug.Print(" Depth: " + swSectionView.SectionDepth * 1000.0 + " mm"); Debug.Print(" Cut direction reversed from default direction? " + swSectionView.GetReversedCutDirection()); Debug.Print(" Partial section cut? " + swSectionView.GetPartialSection()); Debug.Print(" Display only the surface cut by the section line? " + swSectionView.GetDisplayOnlySurfaceCut()); Debug.Print(" Display surface bodies? " + swSectionView.DisplaySurfaceBodies); Debug.Print(" Exclude slice section bodies? " + swSectionView.ExcludeSliceSectionBodies); swSectionView.SetDisplayOnlySpeedPakBodies(true); Debug.Print(" Display only SpeedPak bodies? " + swSectionView.GetDisplayOnlySpeedPakBodies()); Debug.Print(" Scale with model changes? " + swSectionView.GetScaleWithModelChanges()); Debug.Print(" Auto-hatch enabled? " + swSectionView.GetAutoHatch()); Debug.Print(" Hide cut surface bodies? " + swSectionView.CutSurfaceBodies); swModel.EditRebuild3(); } public SldWorks swApp; } }
View CreateUnfoldedViewAt3(
System.double X,
System.double Y,
System.double Z,
System.bool NotAligned)
//This example shows how to create an unfolded view from an existing view. //---------------------------------------------------------------------------- // Preconditions: Open: // public_documents\samples\tutorial\advdrawings\foodprocessor.slddrw // // Postconditions: A new unfolded view is created from Drawing View1. // // NOTE: Because the model is used elsewhere, // do not save changes when closing it. // --------------------------------------------------------------------------- using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; namespace InsertUnfoldedView_CSharp.csproj { partial class SolidWorksMacro { ModelDoc2 Part; DrawingDoc ddoc; View myView; bool boolstatus; public void Main() { Part = (ModelDoc2)swApp.ActiveDoc; ddoc = (DrawingDoc)Part; boolstatus = Part.Extension.SelectByID2("Drawing View1", "DRAWINGVIEW", 0, 0, 0, false, 0, null, 0); myView = ddoc.CreateUnfoldedViewAt3(0.379074752406062, 0.276482735105582, 0, false); } public SldWorks swApp; } }
System.bool DrawingViewRotate(
System.double NewAngle)
This example shows how to rotate the selected drawing view 45º. //--------------------------------------------------------------- // Preconditions: Verify that the specified file to open exists. // // Postconditions: Rotates the selected drawing view 45º. //---------------------------------------- ---------------------- using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System; namespace DrawingViewRotateCSharp.csproj { partial class SolidWorksMacro { public void Main() { ModelDoc2 swModel = default(ModelDoc2); ModelDocExtension swModelDocExt = default(ModelDocExtension); DrawingDoc swDrawing = default(DrawingDoc); bool status = false; int errors = 0; int warnings = 0; swModel = (ModelDoc2)swApp.OpenDoc6("C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\driveworksxpress\\mobile gantry.slddrw", (int)swDocumentTypes_e.swDocDRAWING, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); swModelDocExt = (ModelDocExtension)swModel.Extension; swModel.ViewZoomtofit2(); swDrawing = (DrawingDoc)swModel; status = swDrawing.ActivateView("Drawing View4"); status = swModelDocExt.SelectByID2("Drawing View4", "DRAWINGVIEW", 0.1122300799499, 0.1471819585104, 0, false, 0, null, 0); //Convert degrees to radians, the default system unit // 1 radian = 180º/p = 57.295779513º or approximately 57.3º status = swDrawing.DrawingViewRotate(45 / 57.3); } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
View DropDrawingViewFromPalette2(
System.string PaletteViewName,
System.double X,
System.double Y,
System.double Z)
//This example shows how to get the number of lines in a flat-pattern drawing view's //boundary-box sketch. //---------------------------------------------------------- // Preconditions: // 1. Open public_documents\samples\tutorial\api\SMGussetAPI.SLDPRT. // 2. Create a new drawing document. // 3. Select SMGussetAPI.SLDPRT in the View // Palette's dropdown list box. // 4. Open the Immediate window. // // Postconditions: // 1. Examine the Immediate window and the drawing. // 2. If necessary, drag the drawing onto the drawing sheet // and zoom in on the drawing view. // // NOTE: Because the part is used elsewhere, do not save // changes. //--------------------------------------------------------- using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System; using System.Diagnostics; namespace GetSMBoundaryBoxDisplayDataViewCSharp.csproj { partial class SolidWorksMacro { public void Main() { ModelDoc2 swModel; DrawingDoc swDrawing; View swView; Sheet swSheet; DisplayData swDisplayData; double[] sheetProperties = null; double sheetScale = 0; swDwgPaperSizes_e paperSize; double width = 0; double height = 0; long numViews = 0; object[] viewNames = null; string viewPaletteName = ""; string drawingViewName = ""; int i = 0; bool status = false; swModel = (ModelDoc2)swApp.ActiveDoc; swDrawing = (DrawingDoc)swModel; // Get current sheet swSheet = (Sheet)swDrawing.GetCurrentSheet(); sheetProperties = (double[])swSheet.GetProperties(); sheetScale = (double)sheetProperties[2] / sheetProperties[3]; paperSize = (swDwgPaperSizes_e)swSheet.GetSize(ref width, ref height); // Get number of views on View Palette numViews = 0; viewNames = (object[])swDrawing.GetDrawingPaletteViewNames(); // Iterate through views on View Palette // When view name equals "Flat pattern", drop // that view in drawing if (!((viewNames == null))) { numViews = viewNames.GetUpperBound(0) - viewNames.GetLowerBound(0); for (i = 0; i <= numViews; i++) { viewPaletteName = (string)viewNames[i]; if ((viewPaletteName == "Flat pattern")) { Debug.Print("Dropping View Palette view named: " + viewPaletteName); swView = (View)swDrawing.DropDrawingViewFromPalette2(viewPaletteName, 0.0, 0.0, 0.0); drawingViewName = swView.GetName2(); Debug.Print("Dropped View Palette view into drawing view named: " + drawingViewName); } } } // Activate view and get number of lines in // its boundary box sketch status = swDrawing.ActivateView(drawingViewName); swView = (View)swDrawing.ActiveDrawingView; swDisplayData = (DisplayData)swView.GetSMBoundaryBoxDisplayData(); Debug.Print("Number of lines in boundary box of flat-pattern drawing view: " + swDisplayData.GetLineCount()); } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
void EditSheet()
This example shows how to place a note behind a drawing sheet. //---------------------------------------------------------- // Preconditions: // 1. Verify that the specified drawing file to open exists. // 2. Open the Immediate window. // // Postconditions: // 1. Places the selected note, 2012-sm in the drawing template, // behind the drawing sheet. // 2. To verify: // a. Examine the Immediate window. // b. Right-click the drawing and click // Edit Sheet Format. // c. Right-click 2012-sm and examine the // the short-cut menu to verify that Display // Note Behind Sheet is selected. // d. Exit drawing sheet edit mode. // // NOTE: Because this drawing is used elsewhere, do not // save changes. //----------------------------------------------------------- using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; using System; using System.Diagnostics; namespace NoteBehindSheetCSharp.csproj { partial class SolidWorksMacro { public void Main() { ModelDoc2 swModel = default(ModelDoc2); ModelDocExtension swModelDocExt = default(ModelDocExtension); DrawingDoc swDrawing = default(DrawingDoc); SelectionMgr swSelectionMgr = default(SelectionMgr); Note swNote = default(Note); string fileName = null; bool status = false; int errors = 0; int warnings = 0; // Open drawing fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\2012-sm.slddrw"; swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocDRAWING, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); swDrawing = (DrawingDoc)swModel; // Put drawing template and sheet in edit mode swModelDocExt = (ModelDocExtension)swModel.Extension; status = swModelDocExt.SelectByID2("Sheet1", "SHEET", 0.0399580396732789, 0.20594194865811, 0, false, 0, null, 0); swDrawing.EditTemplate(); swDrawing.EditSheet(); swModel.ClearSelection2(true); // Select note to place behind the sheet status = swModelDocExt.SelectByID2("DetailItem3@Sheet Format1", "NOTE", 0.155548914819136, 0.017885845974329, 0, false, 0, null, 0); swSelectionMgr = (SelectionMgr)swModel.SelectionManager; swNote = (Note)swSelectionMgr.GetSelectedObject6(1, -1); swNote.BehindSheet = true; Debug.Print("Was the selected note placed behind the sheet? " + status); } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
System.object FeatureByName( System.string Name)
//This example shows how to get and set the table anchor of a hole table in a drawing. //----------------------------------------------------------------- // Preconditions: Verify that the specified drawing to open exists. // // Postconditions: // 1. Opens the drawing. // 2. At System.Diagnostics.Debugger.Break(), examine the position // of the hole table in the drawing. // 3. Click the Continue button in the SOLIDWORKS Visual Studio Tools for // Applications IDE. // 4. Sets the position of the hole table's anchor // to the specified location. // 5. Examine the hole table in the drawing. // // NOTE: If prompted, do not save changes when closing the drawing. //------------------------------------------------------------------ using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System; using System.Diagnostics; namespace TableAnchorPositionCSharp.csproj { partial class SolidWorksMacro { public void Main() { string filename = null; filename = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\SimpleHole.slddrw"; ModelDoc2 model = default(ModelDoc2); int errors = 0; int warnings = 0; model = (ModelDoc2)swApp.OpenDoc6(filename, (int)swDocumentTypes_e.swDocDRAWING, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); if (model == null) return; System.Diagnostics.Debugger.Break(); TableAnnotation swTable = default(TableAnnotation); // If document is a drawing, then continue switch (model.GetType()) { case (int)swDocumentTypes_e.swDocDRAWING: DrawingDoc drw = default(DrawingDoc); drw = (DrawingDoc)model; // Get the current sheet Sheet drwSheet = default(Sheet); drwSheet = (Sheet)drw.GetCurrentSheet(); // Select the Sheet2 feature ModelDocExtension modeldocext = default(ModelDocExtension); bool status = false; modeldocext = (ModelDocExtension)model.Extension; status = modeldocext.SelectByID2("Sheet2", "SHEET", 0, 0, 0, false, 0, null, 0); // Get the views on Sheet2 object[] views = null; views = (object[])drwSheet.GetViews(); foreach (object vView in views) { View drwView = default(View); drwView = (View)vView; Feature viewFeature = default(Feature); viewFeature = (Feature)drw.FeatureByName(drwView.Name); // Traverse the features in the view Feature subFeature = default(Feature); subFeature = (Feature)viewFeature.GetFirstSubFeature(); // If the feature is HoleTableFeat, then get the table annotations while (!(subFeature == null)) { if (subFeature.GetTypeName2() == "HoleTableFeat") { HoleTable swHoleTable = default(HoleTable); swHoleTable = (HoleTable)subFeature.GetSpecificFeature2(); object[] holeTables = null; holeTables = (object[])swHoleTable.GetTableAnnotations(); // If the annotation is a hole table, then continue if ((holeTables != null)) { foreach (object table in holeTables) { swTable = (TableAnnotation)table; // If the hole table is anchored, then continue if (swTable.Type == (int)swTableAnnotationType_e.swTableAnnotation_HoleChart) { if (swTable.Anchored != false) { TableAnchor holeTableAnchor = default(TableAnchor); holeTableAnchor = (TableAnchor)drwView.Sheet.get_TableAnchor((int)swTableAnnotationType_e.swTableAnnotation_HoleChart); // Get the position of the table anchor double[] anchorPosition = null; anchorPosition = (double[])holeTableAnchor.Position; // Determine type of table anchor swBOMConfigurationAnchorType_e newCorner = default(swBOMConfigurationAnchorType_e); string corner = null; switch (swTable.AnchorType) { case (int)swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_BottomLeft: corner = " Bottom-left "; newCorner = swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_TopRight; break; case (int)swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_BottomRight: corner = " Bottom-right "; newCorner = swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_TopLeft; break; case (int)swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_TopLeft: corner = " Top-left "; newCorner = swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_BottomRight; break; case (int)swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_TopRight: corner = " Top-right "; newCorner = swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_BottomLeft; break; } swTable.AnchorType = (int)newCorner; // Set the new position of the table anchor double[] dNewPosition = new double[2]; dNewPosition[0] = 0.0; dNewPosition[1] = 0.0; holeTableAnchor.Position = dNewPosition; } } } } } subFeature = (Feature)subFeature.GetNextSubFeature(); } } break; case (int)swDocumentTypes_e.swDocASSEMBLY: case (int)swDocumentTypes_e.swDocPART: break; } } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
System.bool GenerateViewPaletteViews( System.string FileName)
//This example shows how to get and set whether to hide cutting line shoulders in a //section view. //-------------------------------------------------------------------------- // Preconditions: // 1. Verify that the part and templates exist. // 2. Open the Immediate window. // // Postconditions: // 1. Opens the part. // 2. Creates a drawing of the part. // 3. Creates a section view. // 4. Gets and sets whether to hide cutting line shoulders in the section // view. // 5. Examine the Immediate window. // // NOTE: Because the part is used elsewhere, do not save it or the drawing. //-------------------------------------------------------------------------- using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; using System; using System.Diagnostics; namespace Macro1CSharp.csproj { public partial class SolidWorksMacro { public void Main() { ModelDoc2 swModel = default(ModelDoc2); DrawingDoc swDrawing = default(DrawingDoc); Sheet swSheet = default(Sheet); View swView = default(View); ModelDocExtension swModelDocExt = default(ModelDocExtension); SketchSegment swSketchSegment = default(SketchSegment); SketchManager swSketchMgr = default(SketchManager); DrSection swSectionView = default(DrSection); bool status = false; int errors = 0; int warnings = 0; string fileName = null; double swSheetWidth = 0; double swSheetHeight = 0; string drawingTemplate = null; string sheetTemplate = null; //Open part fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\cam roller.sldprt"; swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); //Create drawing of part swSheetWidth = 1.189; swSheetHeight = 0.841; drawingTemplate = "C:\\ProgramData\\SolidWorks\\SOLIDWORKS 2017\\templates\\Drawing.drwdot"; swDrawing = (DrawingDoc)swApp.NewDocument(drawingTemplate, (int)swDwgPaperSizes_e.swDwgPapersUserDefined, swSheetWidth, swSheetHeight); swSheet = (Sheet)swDrawing.GetCurrentSheet(); swSheet.SetProperties2((int)swDwgPaperSizes_e.swDwgPapersUserDefined, (int)swDwgTemplates_e.swDwgTemplateCustom, 1, 2, false, swSheetWidth, swSheetHeight, true); sheetTemplate = "C:\\ProgramData\\SolidWorks\\SOLIDWORKS 2017\\lang\\english\\sheetformat\\a0 - iso.slddrt"; swSheet.SetTemplateName(sheetTemplate); swSheet.ReloadTemplate(true); status = swDrawing.GenerateViewPaletteViews(fileName); swView = (View)swDrawing.DropDrawingViewFromPalette2("*Left", 0.580930433566434, 0.431525272727273, 0); //Create section view swDrawing = (DrawingDoc)swApp.ActiveDoc; status = swDrawing.ActivateView("Drawing View1"); swModel.ClearSelection2(true); swModel = (ModelDoc2)swDrawing; swSketchMgr = (SketchManager)swModel.SketchManager; swSketchSegment = (SketchSegment)swSketchMgr.CreateLine(0.0, 0.0, 0.0, 0.012168, 0.021283, 0.0); swSketchSegment = (SketchSegment)swSketchMgr.CreateLine(0.0, 0.0, 0.0, 0.024347, -0.010966, 0.0); swModelDocExt = (ModelDocExtension)swModel.Extension; status = swModelDocExt.SelectByID2("Line1", "SKETCHSEGMENT", 0.690604633175108, 0.625483883858213, 0, false, 0, null, 0); status = swModelDocExt.SelectByID2("Line2", "SKETCHSEGMENT", 0.747211061353527, 0.357889859742052, 0, true, 0, null, 0); swView = (View)swDrawing.CreateSectionViewAt5(0.676815388637685, 0.116110180826413, 0, "A", (int)swCreateSectionViewAtOptions_e.swCreateSectionView_OffsetSection, null, 0); status = swDrawing.ActivateView("Drawing View2"); swModel.ClearSelection2(true); //Get section view and get and set whether to hide cutting line shoulders swSectionView = (DrSection)swView.GetSection(); if (swSectionView.CuttingLineShoulders) { Debug.Print("Hide cutting line shoulders = True"); Debug.Print("Setting hide cutting line shoulders to False"); swSectionView.CuttingLineShoulders = false; Debug.Print(" Hide cutting line shoulders = " + swSectionView.CuttingLineShoulders); } else { Debug.Print("Hide cutting line shoulders = False"); Debug.Print("Setting hide cutting line shoulders to True"); swSectionView.CuttingLineShoulders = true; Debug.Print(" Hide cutting line shoulders = " + swSectionView.CuttingLineShoulders); } } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
System.object GetCurrentSheet()
This example shows how to create a title block in a drawing, if one does not already exist, and how to get the notes from an existing title block in a drawing. //-------------------------------------------------------- // Preconditions: Drawing document is open. // // Postconditions: If the drawing contains a title block, then // the notes of that block are printed // to the Immediate window. If not, // a title block is created. //------------------------------------------------------- using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace ExampleCS.csproj { public partial class SolidWorksMacro { ModelDoc2 swModel; ModelDocExtension swExt; SelectionMgr swSelMgr; View swView; DrawingDoc swDraw; public void Main() { swModel = swApp.ActiveDoc as ModelDoc2; swExt = swModel.Extension; swSelMgr = swModel.SelectionManager as SelectionMgr; swDraw = swModel as DrawingDoc; Sheet swSheet; swSheet = swDraw.GetCurrentSheet() as Sheet; TitleBlock swTitleBlock; swTitleBlock = swSheet.TitleBlock; object[] vNotes; int i; // Create title block if one doesn't exist if (swTitleBlock == null) { swView = swDraw.GetFirstView() as View; vNotes = (object[])swView.GetNotes(); // Add first two notes to the title block DispatchWrapper[] notesArray = new DispatchWrapper[2]; notesArray[0] = new DispatchWrapper(vNotes[0]); notesArray[1] = new DispatchWrapper(vNotes[1]); swTitleBlock = swSheet.InsertTitleBlock(notesArray); } vNotes = (object[])swTitleBlock.GetNotes(); for (i = 0; i < vNotes.Length; i++) { Note swNote; swNote = (Note)vNotes[i]; Debug.Print("Name: " + swNote.GetName()); Debug.Print("Value: " + swNote.GetText()); } } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
System.object GetFirstView()
//This example shows how to get the drawing view's bounding box, position, and position //lock status. //--------------------------------------------------------- // Preconditions: // 1. Verify that the drawing document to open exists. // 2. Open the Immediate window. // // Postconditions: // 1. Opens the specified drawing document. // 2. Gets each drawing view's: // * origin's x and y positions relative // to the drawing sheet origin // * bounding box // * position lock status // 3. Examine the Immediate window. // // NOTE: Because the drawing is used elsewhere, do not save // changes. //---------------------------------------------------------- using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; using System; using System.Diagnostics; namespace Macro1.csproj { public partial class SolidWorksMacro { public void Main() { DrawingDoc swDraw = default(DrawingDoc); View swView = default(View); double[] outline = null; double[] pos = null; string fileName = null; int errors = 0; int warnings = 0; fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\replaceview.slddrw"; swDraw = (DrawingDoc)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocDRAWING, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); swView = (View)swDraw.GetFirstView(); while ((swView != null)) { outline = (double[])swView.GetOutline(); pos = (double[])swView.Position; Debug.Print("View = " + swView.Name); Debug.Print(" X and Y positions = (" + pos[0] * 1000.0 + ", " + pos[1] * 1000.0 + ") mm"); Debug.Print(" X and Y bounding box minimums = (" + outline[0] * 1000.0 + ", " + outline[1] * 1000.0 + ") mm"); Debug.Print(" X and Y bounding box maximums = (" + outline[2] * 1000.0 + ", " + outline[3] * 1000.0 + ") mm"); Debug.Print(" Position locked?" + swView.PositionLocked); swView = (View)swView.GetNextView(); } } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
System.object GetSheetNames()
//This example shows how to modify and reload a sheet format template. //------------------------------------------------------------ // Preconditions: // 1. Make a copy of: // C:\ProgramData\SolidWorks\SOLIDWORKS version\lang\english\sheetformat\a0 - iso.slddrt. // 2. Create a new blank drawing using standard sheet size AO (ISO). // 3. Add another blank sheet to the drawing, for a total of two sheets. // 4. Open the Immediate window. // // Postconditions: // 1. Modifies the sheet format template to include a new // note. // 2. Examine Sheet1, Sheet2, and the Immediate window. // 3. Delete: // C:\ProgramData\SolidWorks\SOLIDWORKS version\lang\english\sheetformat\a0 - iso.slddrt. // 4. Rename the copy that you made in Preconditions step 1 to: // C:\ProgramData\SolidWorks\SOLIDWORKS version\lang\english\sheetformat\a0 - iso.slddrt. //------------------------------------------------------------ using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; using System; using System.Diagnostics; namespace Macro1CSharp.csproj { public partial class SolidWorksMacro { const bool TEST_APPLY_CHANGES_TO_ALL = true; private string GetReloadResult(swReloadTemplateResult_e result) { string functionReturnValue = null; switch (result) { case (swReloadTemplateResult_e)swReloadTemplateResult_e.swReloadTemplate_Success: functionReturnValue = "Success"; break; case (swReloadTemplateResult_e)swReloadTemplateResult_e.swReloadTemplate_UnknownError: functionReturnValue = "FAIL - Unknown Error"; break; case (swReloadTemplateResult_e)swReloadTemplateResult_e.swReloadTemplate_FileNotFound: functionReturnValue = "FAIL - File Not Found"; break; case (swReloadTemplateResult_e)swReloadTemplateResult_e.swReloadTemplate_CustomSheet: functionReturnValue = "FAIL - Custom Sheet"; break; case (swReloadTemplateResult_e)swReloadTemplateResult_e.swReloadTemplate_ViewOnly: functionReturnValue = "FAIL - View Only"; break; default: functionReturnValue = "FAIL - <unrecognized error code - " + result + ">"; break; } return functionReturnValue; } public void Main() { ModelDoc2 swModel = default(ModelDoc2); swModel = (ModelDoc2)swApp.ActiveDoc; if (swModel == null) { Debug.Print("Create a new empty drawing and add a second sheet to the drawing."); return; } if (swModel.GetType() != (int)swDocumentTypes_e.swDocDRAWING) return; DrawingDoc swDrwng = default(DrawingDoc); swDrwng = (DrawingDoc)swModel; //Get the current sheet Sheet activeSheet = default(Sheet); activeSheet = (Sheet)swDrwng.GetCurrentSheet(); Debug.Print("Active sheet name: " + activeSheet.GetName()); //Get the sheet format template string templateName = null; templateName = activeSheet.GetTemplateName(); Debug.Print("Sheet format template name to modify: " + templateName); swDrwng.EditTemplate(); //Add a new note to the sheet format template Note swNote = default(Note); swNote = (Note)swModel.InsertNote("A New Note"); Annotation swAnno = default(Annotation); swAnno = (Annotation)swNote.GetAnnotation(); swAnno.SetPosition2(0, 0.2, 0); TextFormat txtFormat = default(TextFormat); txtFormat = (TextFormat)swAnno.GetTextFormat(0); txtFormat.BackWards = (txtFormat.BackWards == false); txtFormat.Bold = true; txtFormat.CharHeightInPts = 10 * txtFormat.CharHeightInPts; swAnno.SetTextFormat(0, false, txtFormat); swDrwng.EditSheet(); //At this point, the active sheet's format has changed if (TEST_APPLY_CHANGES_TO_ALL) { //Save sheet format back to original sheet format template activeSheet.SaveFormat(templateName); //Reload all other sheets from the updated sheet format template object[] vSheetNames = null; vSheetNames = (object[])swDrwng.GetSheetNames(); foreach (string vName in vSheetNames) { if (vName != (string)activeSheet.GetName()) { Debug.Print("Other sheet name: " + vName); Sheet otherSheet = default(Sheet); otherSheet = (Sheet)swDrwng.get_Sheet(vName); if (otherSheet.GetTemplateName() == templateName) { swReloadTemplateResult_e reloadResult = default(swReloadTemplateResult_e); //Keep modifications and and reload all other elements //from original sheet format template reloadResult = (swReloadTemplateResult_e)otherSheet.ReloadTemplate(true); //Discard modifications and reload all elements from //original sheet format template //reloadResult = otherSheet.ReloadTemplate(False) Debug.Print("Reload sheet format for <" + otherSheet.GetName() + ">: " + GetReloadResult(reloadResult)); } } } swDrwng.ActivateSheet(activeSheet.GetName()); } else { //Discard the changes and reload the original sheet format template swReloadTemplateResult_e reloadResult = default(swReloadTemplateResult_e); reloadResult = (swReloadTemplateResult_e)activeSheet.ReloadTemplate(false); Debug.Print("Done - " + GetReloadResult(reloadResult)); } } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
System.int GetViewCount()
This example shows how to get all of the views and notes in a drawing document. '-------------------------------------------- ' Preconditions: Drawing document is open and at least ' one view has some notes. ' ' Postconditions: None ' ' NOTE: IDrawingDoc::GetViews returns both sheets and views. '---------------------------------------------- Option Explicit Dim swApp As SldWorks.SldWorks Dim swModel As SldWorks.ModelDoc2 Dim swDrawDoc As SldWorks.DrawingDoc Dim swView As SldWorks.View Dim swNote As SldWorks.Note Dim sheetCount As Long Dim viewCount As Long Dim noteCount As Long Dim i As Long Sub main() Set swApp = Application.SldWorks Set swModel = swApp.ActiveDoc Set swDrawDoc = swModel Dim viewCount As Long viewCount = swDrawDoc.GetViewCount Dim ss As Variant ss = swDrawDoc.GetViews For sheetCount = LBound(ss) To UBound(ss) Dim vv As Variant vv = ss(sheetCount) For viewCount = LBound(vv) To UBound(vv) Debug.Print (vv(viewCount).GetName2()) Dim vNotes As Variant noteCount = vv(viewCount).GetNoteCount If noteCount > 0 Then vNotes = vv(viewCount).GetNotes For i = 0 To noteCount - 1 Debug.Print " Note text: " & vNotes(i).GetText Next End If Next viewCount Next sheetCount End Sub
void HideEdge()
//This example shows how to hide and then show all of the edges in the root component in //a drawing view. //--------------------------------------------------------------------------- // Preconditions: // 1. Verify that the specified drawing document to open exists. // 2. Open the Immediate window. // // Postconditions: // 1. Opens the specified drawing document. // 2. Hides and then shows all edges in the root component in // Drawing View1. // 3. Examine the drawing and Immediate window. //---------------------------------------------------------------------------- using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; namespace HideShowEdges_CSharp.csproj { partial class SolidWorksMacro { ModelDoc2 swModel; DrawingDoc swDraw; DocumentSpecification swDocSpecification; Sheet swSheet; View swView; DrawingComponent swDrawingComponent; Component2 swComponent; Entity swEntity; object[] vEdges; bool bRet; int i; public void Main() { // Specify the drawing to open swDocSpecification = (DocumentSpecification)swApp.GetOpenDocSpec("C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\advdrawings\\foodprocessor.SLDDRW"); swModel = (ModelDoc2)swApp.ActiveDoc; if (swModel == null) { swModel = swApp.OpenDoc7(swDocSpecification); } swModel = (ModelDoc2)swApp.ActiveDoc; swDraw = (DrawingDoc)swModel; // Get the current sheet swSheet = (Sheet)swDraw.GetCurrentSheet(); Debug.Print(swSheet.GetName()); // Select Drawing View1 bRet = swModel.Extension.SelectByID2("Drawing View1", "DRAWINGVIEW", 0.0, 0.0, 0.0, true, 0, null, (int)swSelectOption_e.swSelectOptionDefault); swView = (View)((SelectionMgr)swModel.SelectionManager).GetSelectedObject6(1, -1); // Print the drawing view name and get the component in the drawing view Debug.Print(swView.GetName2()); swDrawingComponent = swView.RootDrawingComponent; swComponent = swDrawingComponent.Component; // Get the component's visible entities in the drawing view int eCount = 0; eCount = swView.GetVisibleEntityCount2(swComponent, (int)swViewEntityType_e.swViewEntityType_Edge); vEdges = (object[])swView.GetVisibleEntities2(swComponent, (int)swViewEntityType_e.swViewEntityType_Edge); Debug.Print("Number of edges found: " + eCount); // Hide all of the visible edges in the drawing view for (i = 0; i <= eCount - 1; i++) { swEntity = (Entity)vEdges[i]; swEntity.Select4(true, null); swDraw.HideEdge(); } // Clear all selections swModel.ClearSelection2(true); // Show all hidden edges swView.HiddenEdges = vEdges; } public SldWorks swApp; } }
void HideShowDrawingViews()
//This example shows how to set the display mode of a drawing view. //---------------------------------------------------------------------------- // Preconditions: // 1. Open a drawing document. // 2. Select a view. // 3. Inspect the graphics area and press F5 six times. // // Postconditions: The display mode, hide/show, and suppression // settings for the document are modified as specified. //---------------------------------------------------------------------------- using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; namespace DisplayHiddenLinesinDrawing_CSharp.csproj { partial class SolidWorksMacro { public void Main() { ModelDoc2 swModel = default(ModelDoc2); DrawingDoc swDraw = default(DrawingDoc); swModel = (ModelDoc2)swApp.ActiveDoc; swDraw = (DrawingDoc)swModel; swDraw.ViewDisplayHidden(); System.Diagnostics.Debugger.Break(); swDraw.ViewDisplayHiddengreyed(); System.Diagnostics.Debugger.Break(); swDraw.ViewDisplayWireframe(); System.Diagnostics.Debugger.Break(); swDraw.ViewDisplayShaded(); System.Diagnostics.Debugger.Break(); // Suppress view swDraw.SuppressView(); System.Diagnostics.Debugger.Break(); // Display an X where the view was suppressed swDraw.HideShowDrawingViews(); System.Diagnostics.Debugger.Break(); // Unsuppress view swDraw.UnsuppressView(); } public SldWorks swApp; } }
Centerline InsertCenterLine2()
//This example shows how to get all of the centerlines in all of the drawing views in a //drawing. //------------------------------------ // Preconditions: // 1. Verify that the drawing document to open exists. // 2. Open the Immediate window. // // Postconditions: // 1. Opens the specified drawing. // 2. Inserts a centerline annotation. // 3. Prints the path and file name of the drawing document // to the Immediate window. // 4. Iterates the sheet and drawing view, prints their names, and // prints the name of the centerline annotation to // the Immediate window. // 5. Examine the Immediate window. // // NOTE: Because this drawing document is used elsewhere, // do not save any changes. //------------------------------------ using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; using System; using System.Diagnostics; namespace CenterLinesCSharp.csproj { public partial class SolidWorksMacro { public void Main() { ModelDoc2 swModel = default(ModelDoc2); ModelDocExtension swModelDocExt = default(ModelDocExtension); DrawingDoc swDrawing = default(DrawingDoc); View swView = default(View); Centerline swCenterLine = default(Centerline); Annotation swAnnotation = default(Annotation); bool status = false; int errors = 0; int warnings = 0; string fileName = null; fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\cylinder20.SLDDRW"; swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocDRAWING, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); swDrawing = (DrawingDoc)swModel; swModelDocExt = (ModelDocExtension)swModel.Extension; status = swDrawing.ActivateView("Drawing View1"); status = swModelDocExt.SelectByID2("cylinder20-9@Drawing View1", "COMPONENT", 0, 0, 0, false, 0, null, 0); status = swModelDocExt.SelectByID2("", "FACE", 0.513454307125032, 0.454946591641617, 250.013794595267, false, 0, null, 0); swCenterLine = (Centerline)swDrawing.InsertCenterLine2(); swModel.ClearSelection2(true); swView = (View)swDrawing.GetFirstView(); Debug.Print("File = " + swModel.GetPathName()); while ((swView != null)) { Debug.Print(" View = " + swView.GetName2()); swCenterLine = (Centerline)swView.GetFirstCenterLine(); while ((swCenterLine != null)) { swAnnotation = (Annotation)swCenterLine.GetAnnotation(); Debug.Print(" Name = " + swAnnotation.GetName()); swCenterLine = swCenterLine.GetNext(); } swView = (View)swView.GetNextView(); } } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
System.bool InsertCircularNotePattern(
System.double ArcRadius,
System.double ArcAngle,
System.int PatternNum,
System.double PatternSpacing,
System.bool PatternRotate,
System.string DeleteInstances)
This example shows how to insert linear and circular note patterns in a drawing. //--------------------------------------------------------- // // Preconditions: Verify that the specified drawing document // to open exists. // // Postconditions: // 1. Inserts a note in the drawing and selects the note. // 2. Inserts a linear note pattern (2 instances, including // the original note) in the drawing. // 3. Inserts a circular note pattern (4 instances, including // the original note) in the drawing. // // NOTE: Because the model is used elsewhere, do not save // changes. //---------------------------------------------------------- using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System; namespace InsertLinearCircularNotePatternsCSharp.csproj { partial class SolidWorksMacro { public void Main() { ModelDoc2 swModel = default(ModelDoc2); DrawingDoc swDrawingDoc = default(DrawingDoc); Note swNote = default(Note); bool status = false; int errors = 0; int warnings = 0; // Open drawing document, activate sheet, and make it the active document swModel = (ModelDoc2)swApp.OpenDoc6("C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\advdrawings\\foodprocessor.slddrw", 3, 0, "", ref errors, ref warnings); swApp.ActivateDoc2("foodprocessor - Sheet1", false, ref errors); swDrawingDoc = (DrawingDoc)swApp.ActiveDoc; // Insert a note swNote = (Note)swModel.InsertNote("Test inserting linear and circular note patterns"); // Select the just-inserted note status = swModel.Extension.SelectByID2("DetailItem174@Sheet1", "NOTE", 0.2558797881203, 0.3700526, 0, false, 0, null, 0); // Create a linear note pattern using the selected note status = swDrawingDoc.InsertLinearNotePattern(2, 1, 0.01, 0.01, 0.7853981633975, 1.570796326795, ""); // Create a circular pattern using the selected note status = swDrawingDoc.InsertCircularNotePattern(0.075, 4.03202193189, -4, 1.570796326795, true, ""); } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
System.object InsertRevisionCloud( System.int CloudShape)
//This example shows how to insert revision clouds into a drawing and access revision //cloud data. //---------------------------------------------------------------------------- // Preconditions: Open public_documents\samples\tutorial\api\resetsketchvisibility.slddrw. // // Postconditions: // 1. Inserts an elliptical revision cloud in the drawing. // 2. Examine the Immediate window. // // NOTE: Because the drawing is used elsewhere, do not save changes. // --------------------------------------------------------------------------- using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; namespace InsertRevisionCloud_CSharp.csproj { partial class SolidWorksMacro { DrawingDoc Part; RevisionCloud RevCloud; Annotation RevCloudAnno; bool boolstatus; public void Main() { Part = (DrawingDoc)swApp.ActiveDoc; boolstatus = Part.ActivateView("Drawing View1"); // Create a revision cloud with an elliptical shape RevCloud = (RevisionCloud)Part.InsertRevisionCloud(1); if ((RevCloud != null)) { RevCloudAnno = (Annotation)RevCloud.GetAnnotation(); if ((RevCloudAnno != null)) { // Position the center of the elliptical revision cloud boolstatus = RevCloudAnno.SetPosition(0.270847371964905, 0.553263328912467, 0); RevCloud.ArcRadius = 0.00508; // Create a path point on the corner of an ellipse-inscribed rectangle boolstatus = RevCloud.SetPathPointAtIndex(-1, 0.378419710263212, 0.511051398694144, 0); // Close the revision cloud path boolstatus = RevCloud.Finalize(); } } } public SldWorks swApp; } }
TableAnnotation InsertTableAnnotation2(
System.bool UseAnchorPoint,
System.double X,
System.double Y,
System.int AnchorType,
System.string TableTemplate,
System.int Rows,
System.int Columns)
This example shows how to get a general table feature and some of its table annotation data. //----------------------------------------------------------------- // Preconditions: // 1. Verify that the specified drawing document to open exists. // 2. Open the Immediate window. // // Postconditions: // 1. Opens the specified drawing document. // 2. Inserts a table annotation. // 3. Gets the general table feature. // 4. Prints the name of the general table feature and // some of its annotation table data the Immediate window. // 5. Examine the Immediate window. // // NOTE: Because the drawing document is used elsewhere, do not // save changes. //----------------------------------------------------------------- using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; using System; using System.Diagnostics; namespace GeneralTableFeatureCSharp.csproj { public partial class SolidWorksMacro { public void Main() { ModelDoc2 swModel = default(ModelDoc2); DrawingDoc swDrawing = default(DrawingDoc); bool status = false; int errors = 0; int warnings = 0; string fileName = null; TableAnnotation swTableAnnotation = default(TableAnnotation); GeneralTableFeature swGeneralTableFeature = default(GeneralTableFeature); SelectionMgr swSelectionMgr = default(SelectionMgr); ModelDocExtension swModelDocExt = default(ModelDocExtension); Feature swFeature = default(Feature); int nbrTableAnnotations = 0; object[] tableAnnotations = null; int i = 0; bool anchorAttached = false; int anchorType = 0; int nbrColumns = 0; int nbrRows = 0; //Open drawing document fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\assem20.slddrw"; swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocDRAWING, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); //Insert table annotation swDrawing = (DrawingDoc)swModel; swTableAnnotation = (TableAnnotation)swDrawing.InsertTableAnnotation2(false, 0.0275123456559767, 0.132124518483965, 1, "", 2, 2); if ((swTableAnnotation != null)) { swTableAnnotation.BorderLineWeight = 0; swTableAnnotation.GridLineWeight = 0; } //Select and get general table feature swModelDocExt = (ModelDocExtension)swModel.Extension; status = swModelDocExt.SelectByID2("General Table1", "GENERALTABLEFEAT", 0, 0, 0, false, 0, null, 0); swSelectionMgr = (SelectionMgr)swModel.SelectionManager; swGeneralTableFeature = (GeneralTableFeature)swSelectionMgr.GetSelectedObject6(1, -1); swFeature = (Feature)swGeneralTableFeature.GetFeature(); Debug.Print("General table feature name: " + swFeature.Name); //Get general table feature's annotation data nbrTableAnnotations = swGeneralTableFeature.GetTableAnnotationCount(); Debug.Print("Number of annotations = " + nbrTableAnnotations); tableAnnotations = (object[])swGeneralTableFeature.GetTableAnnotations(); for (i = 0; i <= (nbrTableAnnotations - 1); i++) { swTableAnnotation = (TableAnnotation)tableAnnotations[i]; anchorAttached = swTableAnnotation.Anchored; Debug.Print("Table anchored = " + anchorAttached); anchorType = swTableAnnotation.AnchorType; Debug.Print("Anchor type = " + anchorType); nbrColumns = swTableAnnotation.ColumnCount; Debug.Print("Number of columns = " + nbrColumns); nbrRows = swTableAnnotation.RowCount; Debug.Print("Number of rows = " + nbrRows); } } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
void IsolateChangedDimensions()
This example shows how to isolate a changed dimension. //------------------------------------------------------ // Preconditions: The specified drawing and part // documents exist. // // Postconditions: // 1. Opens the drawing document. // 2. Sets the system option to display // changed dimensions in the color selected // for Tools > Options > System Options > // Colors > Color scheme settings > // Drawings, Changed dimensions. // 3. Saves and closes the drawing document. // 4. Opens the part document of the drawing document. // 5. Changes a dimension. // 6. Saves and closes the part document. // 7. Opens the previously saved drawing document. // 8. Examine the drawing document to verify that // the changed dimension is displayed in the // changed-dimension color. Place your cursor over // the dimension to see its previous value. //------------------------------------------------------- using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System; namespace IsolateChangedDimensionsDrawingDocCSharp.csproj { partial class SolidWorksMacro { public void Main() { ModelDoc2 swModel = default(ModelDoc2); ModelDocExtension swModelDocExt = default(ModelDocExtension); DrawingDoc swDrawing = default(DrawingDoc); string fileName = null; string saveFileName = null; int errors = 0; int warnings = 0; bool status = false; // Open drawing document fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\box.slddrw"; swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocDRAWING, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); // Isolate changed dimensions // Equivalent to selecting Tools > Options > System Options > Colors > // Use specified color for changed drawing dimensions on open swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swUseChangedDimensions, true); swDrawing = (DrawingDoc)swModel; swDrawing.IsolateChangedDimensions(); // Save drawing document to another name saveFileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\box_changed.slddrw"; swModelDocExt = (ModelDocExtension)swModel.Extension; status = swModelDocExt.SaveAs(saveFileName, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings); swApp.CloseDoc(saveFileName); // Open the part document referenced by the drawing document, // change a dimension, and save the document fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\box.sldprt"; swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); swModelDocExt = (ModelDocExtension)swModel.Extension; status = swModelDocExt.SelectByID2("Sketch1", "SKETCH", 0, 0, 0, true, 0, null, 0); status = swModelDocExt.SelectByID2("D2@Sketch1@box.SLDPRT", "DIMENSION", -0.03613329319351, -0.02215939491444, 0.02938582119709, true, 0, null, 0); Dimension swDimension = default(Dimension); swDimension = (Dimension)swModel.Parameter("D2@Sketch1"); swDimension.SystemValue = 0.185; swModel.ClearSelection2(true); status = swModel.EditRebuild3(); status = swModel.Save3((int)swSaveAsOptions_e.swSaveAsOptions_Silent, ref errors, ref warnings); swApp.CloseDoc(fileName); // Open the previously saved drawing document // and place your cursor on the changed dimension, // which displays in the color specified for // changed dimensions, to see its previous value swModel = (ModelDoc2)swApp.OpenDoc6(saveFileName, (int)swDocumentTypes_e.swDocDRAWING, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
System.bool NewSheet4(
System.string Name,
System.int PaperSize,
System.int TemplateIn,
System.double Scale1,
System.double Scale2,
System.bool FirstAngle,
System.string TemplateName,
System.double Width,
System.double Height,
System.string PropertyViewName,
System.double ZoneLeftMargin,
System.double ZoneRightMargin,
System.double ZoneTopMargin,
System.double ZoneBottomMargin,
System.int ZoneRow,
System.int ZoneCol)
This example shows how to create a drawing sheet with zones, modify the zones in the drawing sheet, and insert a revision table. //----------------------------------------------------------------------------- // Preconditions: // 1. Verify that the specified model document and templates exist. // 2. Open an Immediate window. // // Postconditions: // 1. Creates a new sheet named Test with four zones. // 2. Inspect the graphics area. // 3. Press F5. // 4. Modifies Test to contain nine zones. // 5. Creates Revision Table1. // 6. Adds a revision row to the table. // 7. Inspect the FeatureManager design tree, the graphics area, and the // Immediate window. // // NOTE: Because the model is used elsewhere, do not save changes to it. //--------------------------------------------------------------------------- using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; namespace InsertRevisionTable_CSharp.csproj { partial class SolidWorksMacro { DrawingDoc swDraw; Sheet currentsheet; ModelDoc2 swModel; RevisionTableAnnotation revTableAnno; bool boolstatus; int longstatus; int longwarnings; public void Main() { swModel = swApp.OpenDoc6("C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\assem20.slddrw", 3, 0, "", ref longstatus, ref longwarnings); swApp.ActivateDoc2("assem20 - Sheet1", false, ref longstatus); swModel = (ModelDoc2)swApp.ActiveDoc; swDraw = (DrawingDoc)swModel; boolstatus = swModel.Extension.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swShowZoneLines, 0, true); boolstatus = swModel.Extension.SetUserPreferenceInteger((int)swUserPreferenceIntegerValue_e.swRevisionTableMultipleSheetStyle, 0, (int)swRevisionTableMultipleSheetStyle_e.swRevisionTable_Independent); if ((swDraw == null)) { Debug.Print(" Please open a drawing document. "); } currentsheet = (Sheet)swDraw.GetCurrentSheet(); swDraw.ActivateSheet(currentsheet.GetName()); // Create sheet, Test, with 4 zones boolstatus = swDraw.NewSheet4("Test", (int)swDwgPaperSizes_e.swDwgPaperAsize, (int)swDwgTemplates_e.swDwgTemplateAsize, 1, 1, true, "", 0, 0, "", 0.5, 0.5, 0.5, 0.5, 2, 2); System.Diagnostics.Debugger.Break(); boolstatus = swModel.Extension.SelectByID2("Sheet Format2", "SHEET", 0, 0, 0, false, 0, null, 0); swDraw.EditTemplate(); swModel.EditSketch(); swModel.ClearSelection2(true); boolstatus = swModel.Extension.SelectByID2("Sheet Format2", "SHEET", 0.0812585524728589, 0.139959974668275, 0, false, 0, null, 0); // Modify Test to have 9 zones boolstatus = swDraw.SetupSheet6("Test", (int)swDwgPaperSizes_e.swDwgPapersUserDefined, (int)swDwgTemplates_e.swDwgTemplateCustom, 1, 1, true, "C:\\Program Files\\SOLIDWORKS Corp\\SOLIDWORKS\\lang\\english\\sheetformat\\a - landscape.slddrt", 0.2794, 0.2159, "Default", false, 0.5, 0.5, 0.5, 0.5, 3, 3); swDraw.EditSheet(); swModel.EditSketch(); swModel.ForceRebuild3(true); currentsheet = (Sheet)swDraw.GetCurrentSheet(); swDraw.ActivateSheet(currentsheet.GetName()); // Insert a revision table and add a revision row revTableAnno = currentsheet.InsertRevisionTable2(true, 0.0, 0.0, (int)swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_TopLeft, "C:\\Program Files\\SOLIDWORKS Corp\\SOLIDWORKS\\lang\\English\\standard revision block.sldrevtbt", (int)swRevisionTableSymbolShape_e.swRevisionTable_CircleSymbol, true); Debug.Print("Revision table annotation"); Debug.Print(" New revision: " + revTableAnno.AddRevision("A")); Debug.Print(" Current revision: " + revTableAnno.CurrentRevision); RevisionTableFeature revTableFeat = default(RevisionTableFeature); revTableFeat = revTableAnno.RevisionTableFeature; Debug.Print("Revision table feature"); Debug.Print(" Number of revision table annotations: " + revTableFeat.GetTableAnnotationCount()); Feature feat = default(Feature); feat = (Feature)revTableFeat.GetFeature(); Debug.Print("Feature: " + feat.Name); } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
System.bool ReplaceViewModel(
System.string NewModelPathName,
System.object Views,
System.object Instances)
This example shows how to replace a model in drawing views. //--------------------------------------------------------------------------- // Preconditions: // 1. Open public_documents\samples\tutorial\api\assem20.slddrw. // 2. Verify that the specified replacement model exists. // // Postconditions: Replaces the specified component in Drawing View1 // with the specified model. // // NOTE: Because the model is used elsewhere, do not save changes // when closing it. //--------------------------------------------------------------------------- using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; using System; namespace ReplaceViewModel_CSharp.csproj { partial class SolidWorksMacro { public void Main() { ModelDoc2 swModel; ModelDocExtension swModelDocExt; DrawingDoc swDrawingDoc; SelectionMgr swSelectionMgr; DrawingComponent swDrawingComponent; View swView; Component2 swComponent; object view; object instance; object[] views = new object[1]; object[] instances = new object[1]; DispatchWrapper[] viewsIn = new DispatchWrapper[1]; DispatchWrapper[] instancesIn = new DispatchWrapper[1]; bool status; swModel = (ModelDoc2)swApp.ActiveDoc; swDrawingDoc = (DrawingDoc)swModel; status = swDrawingDoc.ActivateView("Drawing View1"); //Select the view in which to replace the model swModelDocExt = (ModelDocExtension)swModel.Extension; status = swModelDocExt.SelectByID2("Drawing View1", "DRAWINGVIEW", 0, 0, 0, false, 0, null, 0); swSelectionMgr = (SelectionMgr)swModel.SelectionManager; swView = (View)swSelectionMgr.GetSelectedObject6(1, -1); view = (object)swView; views[0] = view; viewsIn[0] = new DispatchWrapper(views[0]); // Select the instance of the model to replace status = swModelDocExt.SelectByID2("Assem20-3@Drawing View1", "COMPONENT", 0, 0, 0, false, 0, null, 0); swDrawingComponent = (DrawingComponent)swSelectionMgr.GetSelectedObject6(1, -1); swComponent = (Component2)swDrawingComponent.Component; instance = (object)swComponent; instances[0] = instance; instancesIn[0] = new DispatchWrapper(instances[0]); status = swDrawingDoc.ReplaceViewModel("C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\bagel.sldprt", (viewsIn), (instancesIn)); } public SldWorks swApp; } }
void SetSheetsSelected( System.object NewSheetList)
//This example shows how to modify the setups of multiple drawing sheets. //-------------------------------------------------------- // Preconditions: // 1. Verify that the drawing and sheet format files exist. // 2. Open the Immediate window. // // Postconditions: // 1. Opens the drawing. // 2. Sets Sheet1, Sheet2 and Sheet3 drawing sheet formats // to portrait. // 3. Rebuilds the drawing. // 4. Click each sheet tab, click Zoom to Fit, and examine // the sheet. // // NOTE: Because the drawing is used elsewhere, do not // save changes. //--------------------------------------------------------- using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using System.Runtime.InteropServices; using System; namespace Macro1CSharp.csproj { public partial class SolidWorksMacro { public void Main() { ModelDoc2 swModel = default(ModelDoc2); ModelDocExtension swModelDocExt = default(ModelDocExtension); DrawingDoc swDrawing = default(DrawingDoc); string fileName = null; bool status = false; int errors = 0; int warnings = 0; object sheetNameArray = null; string[] sheetNames = new string[2]; fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\advdrawings\\foodprocessor.slddrw"; swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocDRAWING, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); swModelDocExt = (ModelDocExtension)swModel.Extension; swDrawing = (DrawingDoc)swModel; sheetNames[0] = "Sheet2"; sheetNames[1] = "Sheet3"; sheetNameArray = sheetNames; swDrawing.SetSheetsSelected(sheetNameArray); status = swDrawing.SetupSheet6("Sheet3", (int)swDwgPaperSizes_e.swDwgPapersUserDefined, (int)swDwgTemplates_e.swDwgTemplateCustom, 1, 1, true, "C:\\ProgramData\\SOLIDWORKS\\SOLIDWORKS 2017\\lang\\english\\sheetformat\\a4 - portrait.slddrt", 0.2794, 0.2159, "Default", true, 0, 0, 0, 0, 0, 0); swModel.ForceRebuild3(true); swModel.ViewZoomtofit2(); } /// <summary> /// The SldWorks swApp variable is pre-assigned for you. /// </summary> public SldWorks swApp; } }
void SuppressView()
//This example shows how to automatically insert center marks in multiple drawing views. //---------------------------------------------------------------------------- // Preconditions: Open public_documents\samples\tutorial\advdrawings\foodprocessor.slddrw. // // Postconditions: // 1. Clears the Tools > Options > Document Properties > Centerlines/Center Marks > // Scale by view scale check box. // 2. Activates Sheet3. // 3. Suppresses Drawing View9. // 4. Inserts center marks in Drawing View9 and Drawing View11. // 5. Unsuppresses Drawing View9. // 6. Examine the drawing. // // NOTE: Because the drawing is used elsewhere, do not save changes. // --------------------------------------------------------------------------- using System; using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; namespace AutoInsertCenterMarks_CSharp.csproj { partial class SolidWorksMacro { ModelDoc2 Part; DrawingDoc Draw; ModelDocExtension ModelDocExt; View swActiveView; bool boolstatus; public void Main() { Part = (ModelDoc2)swApp.ActiveDoc; Draw = (DrawingDoc)Part; ModelDocExt = (ModelDocExtension)Part.Extension; // Clear the Scale by view scale check box to set gap ModelDocExt.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swDetailingCenterMarkScaleByViewScale, (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified, false); Draw.ActivateSheet("Sheet3"); // Suppress Drawing View9 boolstatus = ModelDocExt.SelectByID2("Drawing View9", "DRAWINGVIEW", 0, 0, 0, false, 0, null, 0); Draw.SuppressView(); // Insert center marks for all holes, fillets, and slots in the specified view boolstatus = Draw.ActivateView("Drawing View9"); swActiveView = (View)Draw.ActiveDrawingView; boolstatus = swActiveView.AutoInsertCenterMarks2(7, 11, true, true, true, 0.0025, 0.0025, true, true, 0); boolstatus = Draw.ActivateView("Drawing View11"); swActiveView = (View)Draw.ActiveDrawingView; boolstatus = swActiveView.AutoInsertCenterMarks2(7, 11, true, true, false, 0.005, 0.005, true, false, 0); Part.ClearSelection2(true); // Unsuppress Drawing View9 boolstatus = ModelDocExt.SelectByID2("Drawing View9", "DRAWINGVIEW", 0, 0, 0, false, 0, null, 0); Draw.UnsuppressView(); } public SldWorks swApp; } }