ISelectionMgr Interface

Solidworks学习笔记-链接Solidworks

属性

NameDescription备注
EnableContourSelectionEnables and disables contour selection.  启用和禁用轮廓选择。
EnableSelectionEnables or disables selection.  启用或禁用选择。
SelectionColorGets or sets the selection color.  获取或设置选择颜色。
//----------------------------------------------------------------------------
// Preconditions: Ensure that the specified document template exists.
//
// Postconditions: The selected sketch region is extruded.
// ---------------------------------------------------------------------------

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 EnableContourSelection_CSharp.csproj
{
    partial class SolidWorksMacro
    {

        ModelDoc2 swModel;
        object vSkLines;
        bool boolstatus;

        public void Main()
        {
            swModel = (ModelDoc2)swApp.NewDocument("C:\\ProgramData\\SOLIDWORKS\\SOLIDWORKS 2014\\templates\\Part.prtdot", 0, 0, 0);
            swModel = (ModelDoc2)swApp.ActiveDoc;
            boolstatus = swModel.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swDisplayOrigins, true);
            swModel.ClearSelection2(true);

            vSkLines = swModel.SketchManager.CreateCornerRectangle(-0.0390769010920735, 0.0405984975017191, 0, 0.0129020232818107, -0.0166534302871355, 0);
            swModel.ClearSelection2(true);
            vSkLines = swModel.SketchManager.CreateCornerRectangle(-0.00751826843645631, 0.0156092594749566, 0, 0.0487922329685375, -0.041704950991857, 0);
            swModel.ClearSelection2(true);
            swModel.SketchManager.InsertSketch(true);

            // Enable contour selection
            ((SelectionMgr)(swModel.SelectionManager)).EnableContourSelection = true;
            // Select a contour to extrude
            swModel.Extension.SelectByID2("Sketch1", "SKETCHREGION", 0, 0.01, 0, true, 4, null, 0);
            swModel.FeatureManager.FeatureExtrusion3(true, false, false, 0, 0, 0.01, 0.01, false, false, false,
            false, 0, 0, false, false, false, false, true, true, true,
            0, 0, false);
            // Disable contour selection
            ((SelectionMgr)(swModel.SelectionManager)).EnableContourSelection = false;
            swModel.ClearSelection2(true);

        }

        public SldWorks swApp;

    }

} 

方法

NameDescription备注
AddSelectionListObjectAdds the specified object to the selection list.  将指定的对象添加到选择列表中。
AddSelectionListObjectsAdds the specified objects to the selection list.  将指定的对象添加到选择列表中。
ClearSelectionColorsClears all of selection color settings.  清除所有选择颜色设置。
CreateCallout2Creates a callout for the selection.  为选择创建标注。
CreateSelectDataCreates a ISelectData object to use as argument with Select methods.  创建一个 ISelectData 对象以用作 Select 方法的参数。
DeSelect2Deselects the specified entity.  取消选择指定的实体。
GetPreSelectedObjectGets the preselected object when the preselection notify event is fired.  触发预选通知事件时获取预选对象。
GetSelectByIdSpecificationGets the selection specification for the specified object.  获取指定对象的选择规范。
GetSelectedObject6Gets the selected object.  获取选定的对象。
GetSelectedObjectCount2Gets the number of selected objects.  获取选定对象的数量。
GetSelectedObjectLoop2Gets the loop, if selected, for the selected edge.  获取选定边的循环(如果已选中)。
GetSelectedObjectMarkGets the value of the mark for the specified selection.  获取指定选择的标记值。
GetSelectedObjectsComponent4Gets the selected component in an assembly or drawing.  获取装配体或工程图中的选定零部件。
GetSelectedObjectsDrawingView2Gets the drawing view for the selected object.  获取选定对象的图纸视图。
GetSelectedObjectsFaceGets the face of the specified selection if the specified selection is a silhouette edge.  如果指定选择是轮廓边缘,则获取指定选择的面。
GetSelectedObjectType3Gets the type of object selected.  获取所选对象的类型。
GetSelectionPoint2Gets the selected point in model space coordinates from the currently selected object.  从当前选定的对象获取模型空间坐标中的选定点。
GetSelectionPointInSketchSpace2Gets the selection point projected on to the active sketch and returned in sketch space.  获取投影到活动草图上并在草图空间中返回的选择点。
GetSelectionSpecificationGets the selection specification at the specified index of the current selection list.  获取当前选择列表的指定索引处的选择规范。
IDeSelect2Deselects the specified entity.  取消选择指定的实体。
IGetSelectionPoint2Gets the selected point in model space coordinates from the currently selected object.  从当前选定的对象获取模型空间坐标中的选定点。
IGetSelectionPointInSketchSpace2Gets the selection point projected on to the active sketch and returned in sketch space.  获取投影到活动草图上并在草图空间中返回的选择点。
IsInEditTarget2Gets whether the selected object is in the edit target.  获取所选对象是否在编辑目标中。
ResumeSelectionListReinstates the previously suspended selection list.  恢复之前暂停的选择列表。
SetCalloutAdds a callout to the currently selected object.  向当前选定的对象添加标注。
SetSelectedObjectMarkSets the mark value for the specified selection.  设置指定选择的标记值。
SetSelectionPoint2Sets the selection point in model space.  在模型空间中设置选择点。
SuspendSelectionListSuspends the current selection list.  暂停当前​​选择列表。
This example shows how to insert and modify an indent feature.

//---------------------------------------------------------------
// Preconditions:
// 1. Verify that the part to open exists.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Opens the specified part.
// 2. Selects the boss-extrude body and a face on the
//    extrude-thin body.
// 3. Inserts an indent feature.
// 4. Modifies the thickness of the indent feature.
// 5. Examine the Immediate window, FeatureManager design tree,
//    and graphics area.
//
// NOTE: Because the part 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
{
    public partial class SolidWorksMacro
    {
 
 
        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            ModelDocExtension swModelDocExt = default(ModelDocExtension);
            FeatureManager swFeatureMgr = default(FeatureManager);
            SelectionMgr swSelectionMgr = default(SelectionMgr);
            Feature swFeature = default(Feature);
            IndentFeatureData swIndentFeatureData = default(IndentFeatureData);
            Body2 targetBody = default(Body2);
            Face2 swFace = default(Face2);
            Body2 toolRegionBody = default(Body2);
            string fileName = null;
            bool status = false;
            int errors = 0;
            int warnings = 0;
            object[] toolBodyRegions = null;
            int toolBodyRegionType = 0;
            int nbrBodies = 0;
            int i = 0;
 
            //Open part where to insert indent feature
            fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\multibody\\multi_inter.sldprt";
            swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
 
            //Select solid body for target body,
            //select face for tool body region, and
            //and insert indent feature
            swModelDocExt = (ModelDocExtension)swModel.Extension;
            status = swModelDocExt.SelectByID2("Boss-Extrude1", "SOLIDBODY", 0, 0, 0, false, 1, null, 0);
            status = swModelDocExt.SelectByID2("", "FACE", -0.0371343422566497, -0.0149999999999864, 0.0883053842352979, true, 4, null, 0);
            swFeatureMgr = (FeatureManager)swModel.FeatureManager;
            swFeature = (Feature)swFeatureMgr.InsertIndent(0.01, 0, true, true, false, false);
 
            //Access and modify indent feature
            Debug.Print("Indent feature name: " + swFeature.Name);
            swIndentFeatureData = (IndentFeatureData)swFeature.GetDefinition();
            swIndentFeatureData.AccessSelections(swModel, null);
            nbrBodies = swIndentFeatureData.GetBodiesCount();
            Debug.Print("  Number of bodies: " + nbrBodies);
            targetBody = (Body2)swIndentFeatureData.TargetBody;
            Debug.Print("  Name of target body: " + targetBody.Name);
            toolBodyRegions = (object[])swIndentFeatureData.ToolBodyRegion;
            Debug.Print("  Number of tool body regions: " + toolBodyRegions.Length);
            for (i = 0; i < nbrBodies; i++)
            {
                swModel.ClearSelection2(true);
                swSelectionMgr = (SelectionMgr)swModel.SelectionManager;
                status = swSelectionMgr.AddSelectionListObject(toolBodyRegions[i], null);
                toolBodyRegionType = swSelectionMgr.GetSelectedObjectType3(1, -1);
                Debug.Print("  Type of object selected for tool body region (2 = face; 3 = vertex): " + toolBodyRegionType);
                //If object selected for tool body region is a face,
                //then get the name of its body
                if (toolBodyRegionType == 2)
                {
                    swFace = (Face2)toolBodyRegions[i];
                    toolRegionBody = (Body2)swFace.GetBody();
                    Debug.Print("  Name of body of tool body region: " + toolRegionBody.Name);
                }
            }
            Debug.Print("  Original thickness: " + swIndentFeatureData.Thickness);
            //Change thickness
            swIndentFeatureData.Thickness = 0.011;
            Debug.Print("  Modified thickness: " + swIndentFeatureData.Thickness);
            status = swFeature.ModifyDefinition(swIndentFeatureData, swModel, null);
 
 
        }
 
        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}
This example shows how to populate the selection list with objects that have not been pre-selected through the user interface.

//----------------------------------------------------------------------------
// Preconditions:
// 1. Open a model that contains Sketch1 and Sketch2.
// 2. Open the Immediate window.
//
//' Postconditions:
// 1. Suspends the selection list containing Sketch1.
// 2. Populates another selection list with two objects.
// 3. Gets the type of the last object in the selection list.
// 4. Resumes the previous selection list with Sketch1.
// 5. Places Sketch1 in edit mode.
// 6. Inspect the Immediate window and graphics area.
// ---------------------------------------------------------------------------
	using Microsoft.VisualBasic;
	using System;
	using System.Collections;
	using System.Collections.Generic;
	using System.Data;
	using System.Diagnostics;
	using System.Runtime.InteropServices;
	using SolidWorks.Interop.sldworks;
	using SolidWorks.Interop.swconst;
	namespace AddObjectToSelectionList_CSharp.csproj
	{
	    partial class SolidWorksMacro
	    {
	        ModelDoc2 swModel;
	        SelectionMgr selMgr;
	        SelectData selData;
	        FeatureManager featMgr;
	        Feature feat;
	        DispatchWrapper[] arrObjIn = new DispatchWrapper[2];
	        Feature[] selObjs = new Feature[2];
	        object selobj;
	        int featCount;
	        int i;
	        string typeName;
	        int j;
	        int numAdded;
	        bool boolstatus;
	        int ret;
	        int count;
	        public void Main()
	        {
	            swModel = (ModelDoc2)swApp.ActiveDoc;
	            selMgr = (SelectionMgr)swModel.SelectionManager;
	            selData = (SelectData)selMgr.CreateSelectData();
	            featMgr = swModel.FeatureManager;
	            featCount = featMgr.GetFeatureCount(true);
	            feat = (Feature)swModel.FirstFeature();
	            j = 0;
	            for (i = 0; i <= featCount; i++)
	            {
	                if ((feat != null))
	                {
	                    typeName = feat.Name;
	                    typeName = typeName.ToUpper();
	                    if ("SKETCH" == typeName.Substring(0, 6))
	                    {
	                        selObjs[j] = feat;
	                        arrObjIn[j] = new DispatchWrapper(selObjs[j]);
	                        j = j + 1;
	                    }
	                    feat = (Feature)feat.GetNextFeature();
	                }
	            }
	            // Add one object to the 
	current selection list
	            boolstatus = swModel.Extension.SelectByID2("Sketch1", "SKETCH", 
	0, 0, 0, false, 
	0, null, 
	0);
	            // Start a new selection list
	            ret = selMgr.SuspendSelectionList();
	            Debug.Print("The current selection list with " + ret + " object (Sketch1) is suspended.");
	            // Add two objects to the new 
	selection list
	            numAdded = selMgr.AddSelectionListObjects((arrObjIn), selData);
	            Debug.Print("A new selection list is started.");
	            // Get number of objects in the 
	new selection list (should be 2)
	            count = selMgr.GetSelectedObjectCount();
	            Debug.Print("The selection list now contains " + count + " objects.");
	            // Get the last object in the 
	new selection list
	            selobj = selMgr.GetSelectedObject6(count, 
	-1);
	            Debug.Print("The last object in the selection list is of swSelectType_e = " + selMgr.GetSelectedObjectType3(count, -1) + ".");
	            // Go back to the previous 
	selection list
	            selMgr.ResumeSelectionList();
	            Debug.Print("The previous selection list is resumed.");
	            // Get the number of objects in 
	the selection list (should be 1)
	            count = selMgr.GetSelectedObjectCount();
	            Debug.Print("The selection list now contains " + count + " object (Sketch1).");
	            swModel.EditSketch();
	            Debug.Print("Sketch1 
	is in edit mode.");
	        }
	        public SldWorks swApp;
	    }
	} 
This example shows how to select multiple objects and add the selected objects to different selection boxes on a PropertyManager page.

 

//-------------------------------------------------------------------------
// Preconditions:
// 1. Verify that the assembly to open exists.
// 2. Copy SolidWorksMacro.cs to the project.
// 3. Add a class module and copy clsPropMgr.cs to that module.
// 4. Add the SolidWorks.Interop.swpublished primary interop assembly
//    reference to your project (click Project > Add Reference, 
//    browse to install_dir\api\redist\CLR2, select
//    SolidWorks.Interop.swpublished.dll > OK).
// 5. Verify that the Tools > Options > System Options > Stop VSTA debugger 
//    on macro exit checkbox is clear.
//
// Postconditions:
// 1. Opens the specified assembly.
// 2. Creates a PropertyManager page. 
// 3. Examine the PropertyManager page to verify that three selected faces 
//    appear in the top selection box, and two selected faces appear 
//    in the bottom selection box.
// 4. Close the PropertyManager page.

// NOTE: 
//   *  Reselect the Tools > Options > System Options > Stop VSTA debugger 
//      on macro exit checkbox, if it was selected prior to running the macro.
//   *  Because the assembly document is used elsewhere,
//      do not save changes.
//--------------------------------------------------------------------------- 
// SolidWorksMacro.cs

using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
 
namespace CreatePropertyManagerPageCSharp.csproj
{
    partial class SolidWorksMacro
    {
        public SldWorks swApp;
        public ModelDoc2 swModel;
        public ModelDocExtension swModelDocExt;
        public SelectionMgr swSelectionMgr;
        public const int mark = 1;
        public const int mark2 = 2;
        public clsPropMgr pm;
 
        public void Main()
        {
 
            int openDocErrors = 0;
            int openDocWarnings = 0;
            Face2[] selections1 = new Face2[3];
            Face2[] selections2 = new Face2[2];
            int i = 0;
            int j = 0;
            bool status = false;
            int nbrSelections = 0;
 
 
            swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStopDebuggingVstaOnExit, false);

            string fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\advdrawings\\bladed shaft.sldasm";
            swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref openDocErrors, ref openDocWarnings);
            swModelDocExt = (ModelDocExtension)swModel.Extension;
            swSelectionMgr = (SelectionMgr)swModel.SelectionManager;
 
            //Create a new instance of the PropertyManager class 
            pm = new clsPropMgr(swApp);
            pm.Show();
 
            //Selections for top selection box
            status = swModelDocExt.SelectByID2("", "FACE", 0.00369805475952489, 0.0901975482463513, 0.00315907187808762, true, mark, null, 0);
            status = swModelDocExt.SelectByID2("", "FACE", 0.00860570843923369, 0.0737431971170679, 0.0039892160950501, true, mark, null, 0);
            status = swModelDocExt.SelectByID2("", "FACE", 0.0100013029872912, 0.0446884591512742, 0.00996173127262523, true, mark, null, 0);
            nbrSelections = swSelectionMgr.GetSelectedObjectCount2(-1);
            nbrSelections = nbrSelections - 1;
            for (i = 0; i <= nbrSelections; i++)
            {
                selections1[i] = (Face2)swSelectionMgr.GetSelectedObject6(i + 1, -1);
            }
 
            swModel.ClearSelection2(true);
 
            //Selections for bottom selection box
            status = swModelDocExt.SelectByID2("", "FACE", -0.0264206017159268, -0.00342602957275062, 0.00987615560137556, true, mark2, null, 0);
            status = swModelDocExt.SelectByID2("", "FACE", -0.00128130257782288, -0.00354158999988385, 0.0177003152412567, true, mark2, null, 0);
            nbrSelections = swSelectionMgr.GetSelectedObjectCount2(-1);
            nbrSelections = nbrSelections - 1;
            for (j = 0; j <= nbrSelections; j++)
            {
                selections2[j] = (Face2)swSelectionMgr.GetSelectedObject6(j + 1, -1);
            }
 
            swModel.ClearSelection2(true);
 
            //Populate selection boxes
            SelectBoxFaces1(selections1, mark);
            SelectBoxFaces2(selections2, mark2);
 
        }
        private void SelectBoxFaces1(Face2[] selections, int selectionBoxMark)
        {
            SelectData swSelectData = default(SelectData);
            swSelectData = (SelectData)swSelectionMgr.CreateSelectData();
            swSelectData.Mark = selectionBoxMark;
            swModelDocExt.MultiSelect2(selections, true, swSelectData);
        }
        private void SelectBoxFaces2(Face2[] selections, int selectionBoxMark)
        {
            SelectData swSelectData = default(SelectData);
            swSelectData = (SelectData)swSelectionMgr.CreateSelectData();
            swSelectData.Mark = selectionBoxMark;
            swModelDocExt.MultiSelect2(selections, true, swSelectData);
        }
 
    }
 
} 

Back to top

// clsPropMgr.cs

using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using SolidWorks.Interop.swpublished;
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
 
namespace CreatePropertyManagerPageCSharp.csproj
{
    [ComVisibleAttribute(true)]
 
    public class clsPropMgr : PropertyManagerPage2Handler9
    {
        //General objects required for the PropertyManager page 
        PropertyManagerPage2 pm_Page;
        PropertyManagerPageGroup pm_Group;
        PropertyManagerPageSelectionbox pm_Selection;
        PropertyManagerPageSelectionbox pm_Selection2;
 
 
        //Each object in the page needs a unique ID 
        const int GroupID = 1;
        const int SelectionID = 3;
        const int ComboID = 4;
        const int ListID = 5;
        const int Selection2ID = 6;
 
        public void Show()
        {
            pm_Page.Show2(0);
        }
 
        //The following runs when a new instance 
        //of the class is created 
        public clsPropMgr(SldWorks swApp)
        {
 
            string PageTitle = null;
            string caption = null;
            string tip = null;
            long options = 0;
            int longerrors = 0;
            int controlType = 0;
            int alignment = 0;
 
 
            //Set the variables for the page 
            PageTitle = "MultiSelect2 Test";
            options = (int)swPropertyManagerButtonTypes_e.swPropertyManager_OkayButton + (int)swPropertyManagerButtonTypes_e.swPropertyManager_CancelButton + (int)swPropertyManagerPageOptions_e.swPropertyManagerOptions_PushpinButton;
 
            //Create the PropertyManager page 
            pm_Page = (PropertyManagerPage2)swApp.CreatePropertyManagerPage(PageTitle, (int)options, this, ref longerrors);
 
            //Make sure that the page was created properly 
            if (longerrors == (int)swPropertyManagerPageStatus_e.swPropertyManagerPage_Okay)
            {
                //Begin adding the controls to the page 
 
                //Create the group box 
                caption = "";
                options = (int)swAddGroupBoxOptions_e.swGroupBoxOptions_Visible + (int)swAddGroupBoxOptions_e.swGroupBoxOptions_Expanded;
                pm_Group = (PropertyManagerPageGroup)pm_Page.AddGroupBox(GroupID, caption, (int)options);
 
                //Create two selection boxes 
                controlType = (int)swPropertyManagerPageControlType_e.swControlType_Selectionbox;
                caption = "";
                alignment = (int)swPropertyManagerPageControlLeftAlign_e.swControlAlign_Indent;
                options = (int)swAddControlOptions_e.swControlOptions_Visible + (int)swAddControlOptions_e.swControlOptions_Enabled;
                tip = "Select multiple faces.";
 
                pm_Selection = (PropertyManagerPageSelectionbox)pm_Group.AddControl(SelectionID, (short)controlType, caption, (short)alignment, (int)options, tip);
                pm_Selection2 = (PropertyManagerPageSelectionbox)pm_Group.AddControl(Selection2ID, (short)controlType, caption, (short)alignment, (int)options, tip);
 
                'Only faces can populate the selection boxes
                swSelectType_e[] filters = new swSelectType_e[1];
                filters[0] = swSelectType_e.swSelFACES;
 
                object filterObj = null;
                filterObj = filters;
 
                pm_Selection.SingleEntityOnly = false;
                pm_Selection.AllowMultipleSelectOfSameEntity = true;
                pm_Selection.Height = 50;
                pm_Selection.SetSelectionFilters(filterObj);
                pm_Selection.Mark = SolidWorksMacro.mark;
 
                pm_Selection2.SingleEntityOnly = false;
                pm_Selection2.AllowMultipleSelectOfSameEntity = true;
                pm_Selection2.Height = 50;
                pm_Selection2.SetSelectionFilters(filterObj);
                pm_Selection2.Mark = SolidWorksMacro.mark2;
            }
            else
            {
                //If the page is not created 
                System.Windows.Forms.MessageBox.Show("An error occurred while attempting to create the " + "PropertyManager Page");
 
            }
        }
 
        #region IPropertyManagerPage2Handler9 Members
 
        void IPropertyManagerPage2Handler9.AfterActivation()
        {
 
            throw new Exception("The method or operation is not implemented.");
        }
 
        void IPropertyManagerPage2Handler9.AfterClose()
        {
 
            throw new Exception("The method or operation is not implemented.");
        }
 
        int IPropertyManagerPage2Handler9.OnActiveXControlCreated(int Id, bool Status)
        {
 
            throw new Exception("The method or operation is not implemented.");
        }
 
        void IPropertyManagerPage2Handler9.OnButtonPress(int Id)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnCheckboxCheck(int Id, bool Checked)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnClose(int Reason)
        {
 
            if (Reason == (int)swPropertyManagerPageCloseReasons_e.swPropertyManagerPageClose_Cancel)
            {
                //Do something when the cancel button is clicked 
            }
            else if (Reason == (int)swPropertyManagerPageCloseReasons_e.swPropertyManagerPageClose_Okay)
            {
                //Do something else when the OK button is clicked 
            }
 
        }
 
        void IPropertyManagerPage2Handler9.OnComboboxEditChanged(int Id, string Text)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnComboboxSelectionChanged(int Id, int Item)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnGainedFocus(int Id)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnGroupCheck(int Id, bool Checked)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnGroupExpand(int Id, bool Expanded)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        bool IPropertyManagerPage2Handler9.OnHelp()
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        bool IPropertyManagerPage2Handler9.OnKeystroke(int Wparam, int Message, int Lparam, int Id)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnListboxSelectionChanged(int Id, int Item)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnLostFocus(int Id)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        bool IPropertyManagerPage2Handler9.OnNextPage()
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnNumberboxChanged(int Id, double Value)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnOptionCheck(int Id)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnPopupMenuItem(int Id)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnPopupMenuItemUpdate(int Id, ref int retval)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        bool IPropertyManagerPage2Handler9.OnPreview()
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        bool IPropertyManagerPage2Handler9.OnPreviousPage()
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnRedo()
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnSelectionboxCalloutCreated(int Id)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnSelectionboxCalloutDestroyed(int Id)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnSelectionboxFocusChanged(int Id)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnSelectionboxListChanged(int Id, int Count)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnSliderPositionChanged(int Id, double Value)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnSliderTrackingCompleted(int Id, double Value)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        bool IPropertyManagerPage2Handler9.OnSubmitSelection(int Id, object Selection, int SelType, ref string ItemText)
        {
 
            // This method must return true for selections to occur
            Debug.Print("OnSubmitSelection fired.");
            return true;
 
 
        }
 
        bool IPropertyManagerPage2Handler9.OnTabClicked(int Id)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnTextboxChanged(int Id, string Text)
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnUndo()
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnWhatsNew()
        {
 
            throw new Exception("The method or operation is not implemented.");
 
        }
 
        void IPropertyManagerPage2Handler9.OnListboxRMBUp(int Id, int PosX, int PosY)
        {
            throw new Exception("The method or operation is not implemented.");
        }
 
        int IPropertyManagerPage2Handler9.OnWindowFromHandleControlCreated(int Id, bool Status)
        {
            throw new Exception("The method or operation is not implemented.");
        }
 
        void IPropertyManagerPage2Handler9.OnNumberBoxTrackingCompleted(int Id, double Value)
        {
            throw new Exception("The method or operation is not implemented.");
        }
 
        #endregion
 
    }
 
}
This example shows how to select the edges on all circular holes on a face.

NOTE: A circular hole can be defined in a many ways; for example, a circle inside an extruded sketch or a circle that is part of a cut-extrude feature. Thus, there is no ready way to detect a hole solely based on the feature information. However, by directly examining the geometry and topology of the model, it is possible to deduce holes. This code uses many of the geometry- and topology-related objects and methods to traverse a face and look for circular holes. 

//------------------------------------------------------------------
// Preconditions: Verify that the specified part to open exists.
//
// Postconditions:
// 1. Opens the specified part document.
// 2. Changes the view orientation to Back.
// 3. Selects a face.
// 4. Examines the geometry and topology of the selected face and
//    identifies the holes in the face.
// 5. Deselects the face.
// 6. Selects all edges of all circular holes on the face.
// 7. Examine the graphics area.
//
// NOTE: Because the part 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 CoEdgeCSharp.csproj
{
    public partial class SolidWorksMacro
    {
        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            ModelDocExtension swModelDocExt = default(ModelDocExtension);
            SelectionMgr swSelMgr = default(SelectionMgr);
            SelectData swSelData = default(SelectData);
            Face2 swFace = default(Face2);
            string fileName = null;
            int errors = 0;
            int warnings = 0;
            bool bRet = false;
 
            fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\advdrawings\\gear- caddy.sldprt";
            swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
            swModel.ShowNamedView2("*Back", 2);
            swModelDocExt = (ModelDocExtension)swModel.Extension;
            bRet = swModelDocExt.SelectByID2("", "FACE", 0.0290197084065686, 0.0111645373580202, 0, false, 0, null, 0);
            swSelMgr = (SelectionMgr)swModel.SelectionManager;
            swFace = (Face2)swSelMgr.GetSelectedObject6(1, -1);
            swSelData = (SelectData)swSelMgr.CreateSelectData();
            swModel.ClearSelection2(true);
            SelectHoleEdges(swFace, swSelData);
 
        }
        public double[] GetFaceNormalAtMidCoEdge(CoEdge swCoEdge)
        {
            Face2 swFace = default(Face2);
            Surface swSurface = default(Surface);
            Loop2 swLoop = default(Loop2);
            double[] varParams = null;
            double[] varPoint = null;
            double dblMidParam = 0;
            double[] dblNormal = new double[3];
            bool bFaceSenseReversed = false;
 
            varParams = (double[])swCoEdge.GetCurveParams();
            if (varParams[6] > varParams[7])
            {
                dblMidParam = (varParams[6] - varParams[7]) / 2 + varParams[7];
            }
            else
            {
                dblMidParam = (varParams[7] - varParams[6]) / 2 + varParams[6];
            }
            varPoint = (double[])swCoEdge.Evaluate(dblMidParam);
 
            // Get the face of the given coedge
            // Check for the sense of the face
            swLoop = (Loop2)swCoEdge.GetLoop();
            swFace = (Face2)swLoop.GetFace();
            swSurface = (Surface)swFace.GetSurface();
            bFaceSenseReversed = swFace.FaceInSurfaceSense();
            varParams = (double[])swSurface.EvaluateAtPoint(varPoint[0], varPoint[1], varPoint[2]);
            if (bFaceSenseReversed)
            {
                // Negate the surface normal as it is opposite from the face normal
                dblNormal[0] = -varParams[0];
                dblNormal[1] = -varParams[1];
                dblNormal[2] = -varParams[2];
            }
            else
            {
                dblNormal[0] = varParams[0];
                dblNormal[1] = varParams[1];
                dblNormal[2] = varParams[2];
            }
            return dblNormal;
 
        }
 
        public double[] GetTangentAtMidCoEdge(CoEdge swCoEdge)
        {
            double[] varParams = null;
            double dblMidParam = 0;
            double[] dblTangent = new double[3];
            varParams = (double[])swCoEdge.GetCurveParams();
            if (varParams[6] > varParams[7])
            {
                dblMidParam = (varParams[6] - varParams[7]) / 2.0 + varParams[7];
            }
            else
            {
                dblMidParam = (varParams[7] - varParams[6]) / 2.0 + varParams[6];
            }
            varParams = (double[])swCoEdge.Evaluate(dblMidParam);
            dblTangent[0] = varParams[3];
            dblTangent[1] = varParams[4];
            dblTangent[2] = varParams[5];
            return dblTangent;
 
        }
 
        public double[] GetCrossProduct(double[] varVec1, double[] varVec2)
        {
            double[] dblCross = new double[3];
 
            dblCross[0] = varVec1[1] * varVec2[2] - varVec1[2] * varVec2[1];
            dblCross[1] = varVec1[2] * varVec2[0] - varVec1[0] * varVec2[2];
            dblCross[2] = varVec1[0] * varVec2[1] - varVec1[1] * varVec2[0];
            return dblCross;
 
        }
 
        public bool VectorsAreEqual(double[] varVec1, double[] varVec2)
        {
            bool functionReturnValue = false;
            double dblMag = 0;
            double dblDot = 0;
            double[] dblUnit1 = new double[3];
            double[] dblUnit2 = new double[3];
            dblMag = Math.Pow((varVec1[0] * varVec1[0] + varVec1[1] * varVec1[1] + varVec1[2] * varVec1[2]), 0.5);
            dblUnit1[0] = varVec1[0] / dblMag;
            dblUnit1[1] = varVec1[1] / dblMag;
            dblUnit1[2] = varVec1[2] / dblMag;
            dblMag = Math.Pow((varVec2[0] * varVec2[0] + varVec2[1] * varVec2[1] + varVec2[2] * varVec2[2]), 0.5);
            dblUnit2[0] = varVec2[0] / dblMag;
            dblUnit2[1] = varVec2[1] / dblMag;
            dblUnit2[2] = varVec2[2] / dblMag;
            dblDot = dblUnit1[0] * dblUnit2[0] + dblUnit1[1] * dblUnit2[1] + dblUnit1[2] * dblUnit2[2];
            dblDot = Math.Abs(dblDot - 1.0);
            // Compare within a tolerance
            //1.0e-10
            if (dblDot < 1E-10)
            {
                functionReturnValue = true;
            }
            else
            {
                functionReturnValue = false;
            }
            return functionReturnValue;
 
        }
 
        public void SelectHoleEdges(Face2 swFace, SelectData swSelData)
        {
            Loop2 swThisLoop = default(Loop2);
            CoEdge swThisCoEdge = default(CoEdge);
            CoEdge swPartnerCoEdge = default(CoEdge);
            Entity swEntity = default(Entity);
            double[] varThisNormal = null;
            double[] varPartnerNormal = null;
            double[] varCrossProduct = null;
            double[] varTangent = null;
            object[] vEdgeArr = null;
            Edge swEdge = default(Edge);
            Curve swCurve = default(Curve);
            bool bRet = true;
            int count = 0;
            bool bCount = true;
 
            swThisLoop = (Loop2)swFace.GetFirstLoop();
            while ((swThisLoop != null))
            {
                // Hole is inner loop
                // Circular or elliptical hole has only one edge
                bRet = swThisLoop.IsOuter();
                count = swThisLoop.GetEdgeCount();
                if (count != 1)
                {
                    bCount = false;
                }
                else
                {
                    bCount = true;
                }
                if ((bRet == false) && (bCount == true))
                {
                    swThisCoEdge = (CoEdge)swThisLoop.GetFirstCoEdge();
                    swPartnerCoEdge = (CoEdge)swThisCoEdge.GetPartner();
                    varThisNormal = (double[])GetFaceNormalAtMidCoEdge(swThisCoEdge);
                    varPartnerNormal = (double[])GetFaceNormalAtMidCoEdge(swPartnerCoEdge);
                    if (!VectorsAreEqual(varThisNormal, varPartnerNormal))
                    {
                        // There is a sufficient change between the two faces to determine
                        // what kind of transition is being made
                        varCrossProduct = (double[])GetCrossProduct(varThisNormal, varPartnerNormal);
                        varTangent = (double[])GetTangentAtMidCoEdge(swThisCoEdge);
                        if (VectorsAreEqual(varCrossProduct, varTangent))
                        {
                            // Hole
                            vEdgeArr = (object[])swThisLoop.GetEdges();
                            Debug.Assert(0 < vEdgeArr.Length);
                            swEdge = (Edge)vEdgeArr[0];
                            swCurve = (Curve)swEdge.GetCurve();
                            // Ignore elliptical holes
                            if (swCurve.IsCircle())
                            {
                                swEntity = (Entity)swEdge;
                                bRet = swEntity.Select4(true, swSelData);
                                Debug.Assert(bRet);
                            }
                        }
                    }
                }
 
 
                // Move on to the next
                swThisLoop = (Loop2)swThisLoop.GetNext();
            }
        }
 
        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}
This example shows how to deselect a previously selected and marked entity.

//---------------------------------------------------------
// Preconditions:
// 1. Verify that the part to open exists.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Selects the Base-Extrude feature.
// 2. Examine the graphics area and FeatureManager
//    design tree to verify.
// 3. At System.Diagnostics.Debugger.Break(), press F5 
//    to continue.
// 4. Deselects the Base-Extrude feature.
// 5. Examine the Immediate window, graphics area, and
//    FeatureManager design tree to verify.
//--------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
 
namespace DeSelect2ObjectCSharp.csproj
{
    public partial class SolidWorksMacro
    {
 
 
        public void Main()
        {
 
            ModelDoc2 swModel = default(ModelDoc2);
            DocumentSpecification swDocSpecification = default(DocumentSpecification);
            SelectionMgr swSelMgr = default(SelectionMgr);
            ModelDocExtension swModelExt = default(ModelDocExtension);
            bool bRet = false;
            int lMark = 0;
            int lMarkedIdx = 0;
            int lNumMarkedSelections = 0;
            int lNumAllSelections = 0;
 
            // Open the document
            swDocSpecification = (DocumentSpecification)swApp.GetOpenDocSpec("C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\swutilities\\bracket_a.sldprt");
            swModel = (ModelDoc2)swApp.ActiveDoc;
            if (swModel == null)
            {
                swModel = (ModelDoc2)swApp.OpenDoc7(swDocSpecification);
            }
 
            swSelMgr = (SelectionMgr)swModel.SelectionManager;
            swModelExt = (ModelDocExtension)swModel.Extension;
            // Select the Base-Extrude feature and mark it with a value of 8
            bRet = swModelExt.SelectByID2("Base-Extrude", "BODYFEATURE", 0, 0, 0, false, 8, null, (int)swSelectOption_e.swSelectOptionDefault);
 
            System.Diagnostics.Debugger.Break();
            // Examine the graphics area to verify 
            // that Base-Extrude is selected
            // Press F5 to continue
 
            // Look for a given mark value
            lMark = 8;
            // Get the number of marked selections
            lNumMarkedSelections = swSelMgr.GetSelectedObjectCount2(lMark);
            Debug.Print("Number of marked selections = " + lNumMarkedSelections);
 
            // Get the total number of selections
            lNumAllSelections = swSelMgr.GetSelectedObjectCount2(-1);
            Debug.Print("Number of selections        = " + lNumAllSelections);
 
            Debug.Print(" ");
 
            // Deselect the marked selection
            for (lMarkedIdx = 1; lMarkedIdx <= lNumAllSelections; lMarkedIdx++)
            {
                Debug.Print("Selected object #" + lMarkedIdx + " deselected? " + swSelMgr.DeSelect2(lMarkedIdx, lMark));
            }
 
            // Examine the graphics area to verify that Base-Extrude is deselected
 
        }
 
        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}
This example shows how to get a preselected object when a preselection event is fired.

//-----------------------------------------------------------
// Preconditions:
// 1. Open a part, assembly, or drawing document.
// 2. Click Tools > Options > System Options > Stop VSTA debugger 
//    on macro exit if the check box is selected.
// 3. If a part or assembly document is active, then
//    preselect (mouse over) a face.
//    - or -
//    If a drawing document is active, then pre-elect
//    an edge.
// 4. Open the Immediate window.
//
// Postconditions:
// 1. When a face is preselected in a part or assembly
//    document, or an edge is pre-selected in a drawing document,
//    then that interface's UserSelectionPreNotify event is fired.
// 2. To stop running the macro, click Debug > Stop Debugging 
//    in the SolidWorks Visual Studio Tools for Applications IDE.
// 3. Examine the Immediate window.
// 4. Click Tools > Options > System Options > Stop VSTA debugger 
//    on macro exit to select the check box.
//------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Collections;
using System.Diagnostics;
namespace Macro1CSharp.csproj
{
    partial class SolidWorksMacro
    {
        public PartDoc pDoc;
        public AssemblyDoc aDoc;
        public DrawingDoc dDoc;
        public void Main()
        {
 
            ModelDoc2 swModel;
            Hashtable openPart;
            Hashtable openAssembly;
            Hashtable openDrawing;
 
            swModel = (ModelDoc2)swApp.ActiveDoc;
 
            // Determine the document type 
            // and set up event handlers 
            if (swModel.GetType() == (int)swDocumentTypes_e.swDocPART)
            {
                pDoc = (PartDoc)swModel;
                openPart = new Hashtable();
            }
            else if (swModel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY)
            {
                aDoc = (AssemblyDoc)swModel;
                openAssembly = new Hashtable();
            }
            else if (swModel.GetType() == (int)swDocumentTypes_e.swDocDRAWING)
            {
                dDoc = (DrawingDoc)swModel;
                openDrawing = new Hashtable();
            }
            AttachEventHandlers();
        }
        public void AttachEventHandlers()
        {
            AttachSWEvents();
        }
        public void AttachSWEvents()
        {
            if ((pDoc != null))
            {
                pDoc.UserSelectionPreNotify += this.pDoc_UserSelectionPreNotify;
            }
            if ((aDoc != null))
            {
                aDoc.UserSelectionPreNotify += this.aDoc_UserSelectionPreNotify;
            }
            if ((dDoc != null))
            {
                dDoc.UserSelectionPreNotify += this.dDoc_UserSelectionPreNotify;
            }
        }
        private int pDoc_UserSelectionPreNotify(int SelectionType)
        {
            int functionReturnValue = 0;
            ModelDoc2 swModel;
            SelectionMgr swSelMgr;
            object SelectedObject;
            Face2 swFace;
            Feature swFeature;
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swSelMgr = (SelectionMgr)swModel.SelectionManager;
            SelectedObject = (object)swSelMgr.GetPreSelectedObject();
            if (SelectionType == (int)swSelectType_e.swSelFACES)
            {
                swFace = (Face2)SelectedObject;
                swFeature = (Feature)swFace.GetFeature();
                Debug.Print("Name of feature whose face you preselected: " + swFeature.Name);
                Debug.Print("   Mouse over a different face, or click Debug > Stop Debugging to stop running macro");
                Debug.Print(" ");
                functionReturnValue = 1;
            }
            return functionReturnValue;
        }
        public int aDoc_UserSelectionPreNotify(int SelectionType)
        {
            int functionReturnValue = 0;
            ModelDoc2 swModel;
            SelectionMgr swSelMgr;
            object SelectedObject;
            Face2 swFace;
            Feature swFeature;
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swSelMgr = (SelectionMgr)swModel.SelectionManager;
            SelectedObject = (object)swSelMgr.GetPreSelectedObject();
            if (SelectionType == (int)swSelectType_e.swSelFACES)
            {
                swFace = (Face2)SelectedObject;
                swFeature = (Feature)swFace.GetFeature();
                Debug.Print("Name of feature whose face you preselected: " + swFeature.Name);
                Debug.Print("   Mouse over a different face, or click Debug > Stop Debugging to stop running macro");
                Debug.Print(" ");
                functionReturnValue = 1;
            }
            return functionReturnValue;
        }
        private int dDoc_UserSelectionPreNotify(int SelectionType)
        {
            int functionReturnValue = 0;
            ModelDoc2 swModel;
            SelectionMgr swSelMgr;
            object SelectedObject;
            Edge swEdge;
            Body2 swBody;
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swSelMgr = (SelectionMgr)swModel.SelectionManager;
            SelectedObject = (object)swSelMgr.GetPreSelectedObject();
            if (SelectionType == (int)swSelectType_e.swSelEDGES)
            {
                swEdge = (Edge)SelectedObject;
                swBody = (Body2)swEdge.GetBody();
                Debug.Print("Name of body whose edge you preselected: " + swBody.Name);
                Debug.Print("   Mouse over a different edge, or click Debug > Stop Debugging to stop running macro");
                Debug.Print(" ");
                functionReturnValue = 1;
            }
            return functionReturnValue;
        }
        /// <summary> 
        /// The SldWorks swApp variable is pre-assigned for you. 
        /// </summary> 
        public SldWorks swApp;
    }
}
This example shows how to get the selection specification of a selected object.

//----------------------------------------------------------------------------
// Preconditions:
// 1. Open a model document that contains at least two features.
// 2. Select two features in the FeatureManager design tree.
// 3. Open an Immediate window.
//
// Postconditions:
// 1. Gets the selection specifications of the first and second selections.
// 2. Inspect the 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 GetSelectionSpecification_CSharp.csproj
{
    partial class SolidWorksMacro
    {
 
        ModelDoc2 Part;
        SelectionMgr SelMgr;
        Feature selObject;
        string selectByString;
        string objectTypeStr;
        int objectTypeInt;
        double X;
        double Y;
        double Z;
 
        public void Main()
        {
            Part = (ModelDoc2)swApp.ActiveDoc;
            SelMgr = (SelectionMgr)Part.SelectionManager;
 
            // Get the selection specification of the first selected object
            selObject = (Feature)SelMgr.GetSelectedObject6(1, -1);
            SelMgr.GetSelectByIdSpecification(selObject, out selectByString, out objectTypeStr, out objectTypeInt);
            Debug.Print("Name of selected feature: " + selectByString);
            Debug.Print("Type of object: " + objectTypeStr);
            Debug.Print("Type of object as defined in swSelectType_e: " + objectTypeInt);
 
            Debug.Print("");
 
            // Get the selection specification of the selected object in position 2 of the selection list
            SelMgr.GetSelectionSpecification(2, out selectByString, out objectTypeStr, out objectTypeInt, out X, out Y, out Z);
            Debug.Print("Name of selected feature: " + selectByString);
            Debug.Print("Type of object: " + objectTypeStr);
            Debug.Print("Type of object as defined in swSelectType_e: " + objectTypeInt);
            Debug.Print("X Coordinate: " + X);
            Debug.Print("Y Coordinate: " + Y);
            Debug.Print("Z Coordinate: " + Z);
 
        }
 
 
        public SldWorks swApp;
 
    }
}
This example shows how to create an imported body surface from a sketch.

 

'--------------------------------------

'

' Preconditions: A circular sketch is selected.

'

' Postconditions: A cylindrical imported surface body is created.

'

'--------------------------------------

using System;

namespace BodyFromSketchProfile

{

/// <summary>

/// Summary description for Class1

/// </summary>

class Application

{

static double ExtrudeDepth = 0.1;

/// <summary>

/// Main entry point for the application

/// </summary>

[STAThread]

static void Main(string[] args)

{

bool bRetval;

SldWorks.ISldWorks swApp;

SldWorks.IModelDoc2 swDoc;

SldWorks.IPartDoc swPart;

SldWorks.IBody2 swBody;

SldWorks.ISketch swSketch;

SldWorks.IFeature swFeature;

 

swApp = new SldWorks.SldWorksClass();

swDoc = swApp.IActiveDoc2;

swPart = (SldWorks.IPartDoc) swDoc;

 

SldWorks.ISelectionMgr swSelMgr;

swSelMgr = swDoc.ISelectionManager;

swFeature = (SldWorks.IFeature) swSelMgr.GetSelectedObject6(1,0);

swSketch = (SldWorks.ISketch) swFeature.GetSpecificFeature2();

if (swSketch != null)

{

SldWorks.IEnumSketchSegments swSegs;

swSegs = swSketch.IEnumSketchSegments();

 

int nFetched = 0;

int segcount = 0;

SldWorks.SketchSegment swSeg;

System.Collections.ArrayList ProfileSegs = new System.Collections.ArrayList();

System.Collections.ArrayList BodySurfaces = new System.Collections.ArrayList();

SldWorks.ISurface swSurface;

 

swSegs.Next(1, out swSeg, ref nFetched);

while (nFetched != 0)

{

if (swSeg.ConstructionGeometry == false)

{

swBody = swPart.ICreateNewBody2();

 

segcount++;

SldWorks.ISketchPoint swStartPt;

SldWorks.ISketchPoint swEndPt;

SldWorks.ICurve swCurve = null;

 

switch (swSeg.GetType())

{

case (int)SwConst.swSketchSegments_e.swSketchARC:

{

SldWorks.ISketchArc swSkArc;

swSkArc = (SldWorks.ISketchArc) swSeg;

 

SldWorks.ISketchPoint swCenterPt;

double [] normal;

double radius;

 

swCenterPt = swSkArc.IGetCenterPoint2();

swStartPt = swSkArc.IGetStartPoint2();

swEndPt = swSkArc.IGetEndPoint2();

normal = (double[])swSkArc.GetNormalVector();

radius = swSkArc.GetRadius();

 

double []center = new double[3];

double []startpt = new double[3];

double []endpt = new double[3];

 

center[0] = swCenterPt.X;

center[1] = swCenterPt.Y;

center[2] = swCenterPt.Z;

startpt[0] = swStartPt.X;

startpt[1] = swStartPt.Y;

startpt[2] = swStartPt.Z;

endpt[0] = swEndPt.X;

endpt[1] = swEndPt.Y;

endpt[2] = swEndPt.Z;

 

swCurve = swBody.IAddProfileArc(center, normal, radius, startpt, endpt);

break;

}

case (int)SwConst.swSketchSegments_e.swSketchLINE:

{

SldWorks.ISketchLine swSkLine;

swSkLine = (SldWorks.ISketchLine) swSeg;

 

swStartPt = swSkLine.IGetStartPoint2();

swEndPt = swSkLine.IGetEndPoint2();

 

double []root = new double[3];

double []dir = new double[3];

 

root[0] = swStartPt.X;

root[1] = swStartPt.Y;

root[2] = swStartPt.Z;

 

dir[0] = swEndPt.X - root[0];

dir[1] = swEndPt.Y - root[1];

dir[2] = swEndPt.Z - root[2];

 

swCurve = swBody.IAddProfileLine(root, dir);

 

break;

}

default:

System.Diagnostics.Debug.Assert(false, "Unhandled sketch segment type");

break;

}

// Have the curve and the start and end points

// Create the side of the extrusion

 

ProfileSegment curSeg = new ProfileSegment(swSeg, swCurve);

double []surfeval;

double []extruAxis = new double[3];

 

extruAxis[0] = 0.0;

extruAxis[1] = 0.0;

extruAxis[2] = 1.0;

 

ProfileSegs.Add(curSeg);

 

swSurface = swBody.ICreateExtrusionSurface((SldWorks.Curve)swCurve, extruAxis);

 

//Create a trimming loop for the surface

int nCurves = 4;

int []Order = {2, 2, 2, 2};

int []Dim = {2, 2, 2, 2};

int []Periodic = {0, 0, 0, 0};

int []nKnots = {4, 4, 4, 4};

int []nCtrlPts = {2, 2, 2, 2};

double []Knots = {0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1};

double []CtrlPts = new double[16];

 

double x = curSeg.iStartPt.X;

double y = curSeg.iStartPt.Y;

double z = curSeg.iStartPt.Z;

surfeval = (double[])swSurface.GetClosestPointOn(x, y, z);

CtrlPts[0] = surfeval[3];

CtrlPts[1] = surfeval[4];

CtrlPts[14] = surfeval[3];

CtrlPts[15] = surfeval[4];

 

x = curSeg.iEndPt.X;

y = curSeg.iEndPt.Y;

z = curSeg.iEndPt.Z;

surfeval = (double[])swSurface.GetClosestPointOn(x, y, z);

CtrlPts[2] = surfeval[3];

CtrlPts[3] = surfeval[4];

CtrlPts[4] = surfeval[3];

CtrlPts[5] = surfeval[4];

 

x = curSeg.iEndPt.X;

y = curSeg.iEndPt.Y;

z = curSeg.iEndPt.Z;

surfeval = (double[])swSurface.GetClosestPointOn(x, y, z + ExtrudeDepth);

CtrlPts[6] = surfeval[3];

CtrlPts[7] = surfeval[4];

CtrlPts[8] = surfeval[3];

CtrlPts[9] = surfeval[4];

 

x = curSeg.iStartPt.X;

y = curSeg.iStartPt.Y;

z = curSeg.iStartPt.Z;

surfeval = (double[])swSurface.GetClosestPointOn(x, y, z + ExtrudeDepth);

CtrlPts[10] = surfeval[3];

CtrlPts[11] = surfeval[4];

CtrlPts[12] = surfeval[3];

CtrlPts[13] = surfeval[4];

 

swSurface.AddTrimmingLoop(nCurves, Order, Dim, Periodic, nKnots, nCtrlPts, Knots, CtrlPts);

 

bRetval = swBody.CreateTrimmedSurface();

bRetval = swBody.CreateBodyFromSurfaces();

}

swSegs.Next(1, out swSeg, ref nFetched);

}

}

}// Main

}// Application

class ProfileSegment

{

public SldWorks.ISketchSegment iSkSeg;

public SldWorks.ICurve iCurve;

public SldWorks.ISketchPoint iStartPt;

public SldWorks.ISketchPoint iEndPt;

public ProfileSegment(SldWorks.ISketchSegment swSkSeg, SldWorks.ICurve swCurve)

{

iSkSeg = swSkSeg;

iCurve = swCurve;

 

switch (iSkSeg.GetType())

{

case (int)SwConst.swSketchSegments_e.swSketchARC:

{

SldWorks.ISketchArc swSkArc;

swSkArc = (SldWorks.ISketchArc) iSkSeg;

 

iStartPt = swSkArc.IGetStartPoint2();

iEndPt = swSkArc.IGetEndPoint2();

break;

}

 

case (int)SwConst.swSketchSegments_e.swSketchLINE:

{

SldWorks.ISketchLine swSkLine;

swSkLine = (SldWorks.ISketchLine) iSkSeg;

 

iStartPt = swSkLine.IGetStartPoint2();

iEndPt = swSkLine.IGetEndPoint2();

 

break;

}

default:

System.Diagnostics.Debug.Assert(false, "Unhandled sketch segment type");

break;

}

}

 }

class Vector

{

private

double []coords = new double[3];

 

public Vector(double x, double y, double z)

{

coords[0] = x; coords[1] = y; coords[2] = z;

}

}

}// BodyFromSketchProfile
This example shows how to get the areas of mid-surface faces.

//-----------------------------------------------------------
// Postconditions:
// 1. Verify that the part to open exists.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Opens the part.
// 2. Selects two faces and inserts a midsurface feature.
// 3. Gets the number of faces in the midsurface feature.
// 4. Gets the areas of the faces in the midsurface feature.
// 5. Examine the Immediate window, FeatureManager design
//    tree, and graphics area.
//
// NOTE: Because the part 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
{
    public partial class SolidWorksMacro
    {
 
 
        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            ModelDocExtension swModelDocExt = default(ModelDocExtension);
            FeatureManager swFeatureManager = default(FeatureManager);
            MidSurface3 swMidSurfaceFeature = default(MidSurface3);
            Feature swFeature = default(Feature);
            SelectionMgr swSelectionMgr = default(SelectionMgr);
            Face2 swFace = default(Face2);
            bool status = false;
            int errors = 0;
            int warnings = 0;
            string fileName = null;
            int count = 0;
            object[] faces = null;
            int i = 0;
 
            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("", "FACE", -0.0533080255641494, 0.0299999999999727, 0.0131069871973182, true, 0, null, 0);
            status = swModelDocExt.SelectByID2("", "FACE", -0.0370905424398416, 0, 0.0289438729892595, true, 0, null, 0);
            swFeatureManager = (FeatureManager)swModel.FeatureManager;
            swFeatureManager.InsertMidSurface(null, null, 0.0, false);
            status = swModelDocExt.SelectByID2("Surface-MidSurface1", "REFSURFACE", 0, 0, 0, false, 0, null, 0);
            swSelectionMgr = (SelectionMgr)swModel.SelectionManager;
            swFeature = (Feature)swSelectionMgr.GetSelectedObject6(1, -1);
            swMidSurfaceFeature = (MidSurface3)swFeature.GetSpecificFeature2();
            count = swMidSurfaceFeature.GetFaceCount();
            Debug.Print("Number of faces for midsurface feature: " + count);
            faces = (object[])swMidSurfaceFeature.GetFaces();
            for (i = faces.GetLowerBound(0); i <= faces.GetUpperBound(0); i++)
            {
                swFace = (Face2)faces[i];
                Debug.Print("Area of face " + i + " of midsurface feature: " + swFace.GetArea());
            }
 
        }
 
        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}
This example shows how to create a library feature with references in order to position the library feature on a model. 

//------------------------------------------------------
// Preconditions:
// 1. Verify that the specified part template and library feature
//    exist.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Creates a new part containing a boss extrude.
// 2. Creates a library feature data object.
//    a. Initializes the newly created library feature using
//       the specified library feature.
//    b. Gets the type of references required for the library
//       feature.
//    c. Sets the name of the active library feature configuration.
//    d. Selects the face where to create the library feature.
//    e. Creates the library feature.
//    f. Accesses the library feature and selects the edges where to
//       position the it.
//    g. Sets the references for positioning the library feature.
//    h. Updates the definition of the library feature.
//    i. Unsuppresses the library feature.
// 3. Examine the Immediate window, FeatureManager design tree, and
//    graphics area.
//-------------------------------------------------------
 
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
 
namespace Macro1CSharp.csproj
{
    partial class SolidWorksMacro
    {
        public void Main()
        {
            Feature swFeature = default(Feature);
            ModelDoc2 swModel = default(ModelDoc2);
            ModelDocExtension swModelDocExt = default(ModelDocExtension);
            SketchManager swSketchManager = default(SketchManager);
            SelectionMgr swSelectionManager = default(SelectionMgr);
            FeatureManager swFeatureManager = default(FeatureManager);
            LibraryFeatureData swLibFeat = default(LibraryFeatureData);
            bool status = false;
            object[] sketchLines = null;
            object Refs = null;
            object RefTypes = null;
            int RefCount = 0;
            int k = 0;
            int i = 0;
            DispatchWrapper[] LibRefs = null;
 
            // Create part
            swModel = (ModelDoc2)swApp.NewDocument("C:\\ProgramData\\SolidWorks\\SOLIDWORKS 2016\\templates\\Part.prtdot", 0, 0, 0);
            swModelDocExt = (ModelDocExtension)swModel.Extension;
            status = swModelDocExt.SelectByID2("Top Plane", "PLANE", 0, 0, 0, false, 0, null, 0);
            swModel.ClearSelection2(true);
            status = swModelDocExt.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swSketchAddConstToRectEntity, (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified, false);
            status = swModelDocExt.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swSketchAddConstLineDiagonalType, (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified, true);
            swSketchManager = (SketchManager)swModel.SketchManager;
            sketchLines = (object[])swSketchManager.CreateCornerRectangle(0, 0, 0, 1, 0.5, 0);
            swModel.ShowNamedView2("*Trimetric", 8);
            swModel.ClearSelection2(true);
            status = swModelDocExt.SelectByID2("Line2", "SKETCHSEGMENT", 0, 0, 0, false, 0, null, 0);
            status = swModelDocExt.SelectByID2("Line1", "SKETCHSEGMENT", 0, 0, 0, true, 0, null, 0);
            status = swModelDocExt.SelectByID2("Line4", "SKETCHSEGMENT", 0, 0, 0, true, 0, null, 0);
            status = swModelDocExt.SelectByID2("Line3", "SKETCHSEGMENT", 0, 0, 0, true, 0, null, 0);
            swFeatureManager = (FeatureManager)swModel.FeatureManager;
            swFeature = (Feature)swFeatureManager.FeatureExtrusion2(true, false, false, 0, 0, 0.01, 0.01, false, false, false,
            false, 0.0174532925199433, 0.0174532925199433, false, false, false, false, true, true, true,
            0, 0, false);
            swSelectionManager = (SelectionMgr)swModel.SelectionManager;
            swSelectionManager.EnableContourSelection = false;
 
            // Create library feature 
            swLibFeat = (LibraryFeatureData)swFeatureManager.CreateDefinition((int)swFeatureNameID_e.swFmLibraryFeature);
 
            // Initialize newly created library feature using the specified library part 
            status = swLibFeat.Initialize("C:\\ProgramData\\SOLIDWORKS\\SOLIDWORKS 2016\\design library\\features\\metric\\slots\\straight slot.sldlfp");
 
            // Get the type of references required for the library feature 
            RefCount = swLibFeat.GetReferencesCount();
            Refs = (object[])swLibFeat.GetReferences2((int)swLibFeatureData_e.swLibFeatureData_FeatureRespect, out RefTypes);
 
            if ((RefTypes != null))
            {
                Debug.Print("Types of references required (edge = 1): ");
                int[] RefType = (int[])RefTypes;
                for (k = RefType.GetLowerBound(0); k <= RefType.GetUpperBound(0); k++)
                {
                    Debug.Print("    " + RefType[k].ToString());
                }
            }
 
 
            // Set the name of the active library feature configuration 
            swLibFeat.ConfigurationName = "Default";
 
            // Select the face where to create the library feature 
            status = swModelDocExt.SelectByID2("", "FACE", 0.522458766456054, 0.288038964184011, 0.00999999999987722, false, 0, null, 0);
 
            // Create the library feature 
            swFeature = (Feature)swFeatureManager.CreateFeature(swLibFeat);
 
            // Access the library feature to position it on the part 
            swLibFeat = null;
            swLibFeat = (LibraryFeatureData)swFeature.GetDefinition();
            status = swLibFeat.AccessSelections(swModel, null);
 
            // Select the edges where to position the library feature
            status = swModelDocExt.SelectByID2("", "EDGE", 0.960865149149924, 0.497807163546383, 0.0131011390528215, true, 0, null, 0);
            status = swModelDocExt.SelectByID2("", "EDGE", 0.99866860703213, 0.481385806014544, 0.0113313929676906, true, 0, null, 0);
 
            int selCount = 0;
            selCount = swSelectionManager.GetSelectedObjectCount2(-1);
 
            object[] selectedObjects = new object[selCount];
 
            for (i = 0; i < selCount; i++)
            {
                object selectedObject = null;
                selectedObject = (object)swSelectionManager.GetSelectedObject6(i + 1, -1);
                selectedObjects[i] = selectedObject;
            }
 
            // Convert the .NET array to IDispatch
            LibRefs = (DispatchWrapper[])ObjectArrayToDispatchWrapperArray((selectedObjects));
 
            // Set the references for positioning the library feature on the part 
            swLibFeat.SetReferences(LibRefs);
 
            // Update the definition of the library feature 
            status = swFeature.ModifyDefinition(swLibFeat, swModel, null);
 
            // Unsuppress the library feature
            status = swModelDocExt.SelectByID2("straight slot<1>", "BODYFEATURE", 0, 0, 0, false, 0, null, 0);
            swModel.EditUnsuppress2();
 
            swModel.ClearSelection2(true);
        }
 
        public DispatchWrapper[] ObjectArrayToDispatchWrapperArray(object[] Objects)
        {
            int ArraySize = 0;
            ArraySize = Objects.GetUpperBound(0);
            DispatchWrapper[] d = new DispatchWrapper[ArraySize + 1];
            int ArrayIndex = 0;
            for (ArrayIndex = 0; ArrayIndex <= ArraySize; ArrayIndex++)
            {
                d[ArrayIndex] = new DispatchWrapper(Objects[ArrayIndex]);
            }
            return d;
        }
 
 
        /// <summary> 
        /// The SldWorks swApp variable is pre-assigned for you. 
        /// </summary> 
        public SldWorks swApp;
        public DispatchWrapper[] LibRefs;
 
 
    }
}
This example shows how to insert a hole table annotation and get some of its properties.

//--------------------------------------------------------------------------
// Preconditions:
// 1. Verify that the specified files exist:
//    * part document
//    * drawing document template
//    * hole table template
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Opens the specified part document.
// 2. Creates a drawing of the part document.
// 3. Inserts a hole table annotation at the specified vertex.
// 4. Prints to the Immediate window:
//   * the hole table's datum origin x and y labels
//   * whether to display hole sizes using ANSI inch letters
//     and drill numbers
// 5. Examine the Immediate window and drawing.
//
// NOTE: Because the model 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 GetLabels_CSharp.csproj
{
    public partial class SolidWorksMacro
    {
 
 
        public void Main()
        {
 
            ModelDoc2 swModel;
            DrawingDoc swDrawingDoc;
            View swView;
            ModelView swModelView;
            ModelDocExtension swModelDocExt;
            SelectionMgr swSelectionMgr;
            HoleTableAnnotation swHoleTableAnnotation;
            HoleTable swHoleTable;
            DatumOrigin swDatumOrigin;
            string fileName;
            string drawingDocTemplate;
            string holeTableTemplate;
            bool status;
            int errors = 0;
            int warnings = 0;
 
            //Open part document and create drawing document
            fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\tolanalyst\\minimum_clearance\\top_plate.sldprt";
            swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
            drawingDocTemplate = "C:\\ProgramData\\SolidWorks\\SolidWorks 2016\\templates\\Drawing.drwdot";
            swDrawingDoc = (DrawingDoc)swApp.NewDocument(drawingDocTemplate, (int)swDwgPaperSizes_e.swDwgPaperBsize, 0.2794, 0.4318);
            swView = (View)swDrawingDoc.CreateDrawViewFromModelView3(fileName, "*Front", 0.193046827497194, 0.155595183164983, 0);
 
            //Insert hole table annotation
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swDrawingDoc = (DrawingDoc)swModel;
            swModelView = (ModelView)swModel.ActiveView;
            swModelDocExt = (ModelDocExtension)swModel.Extension;
            status = swDrawingDoc.ActivateView("Drawing View1");
            status = swModelDocExt.SelectByID2("", "VERTEX", 0.216278249046016, 0.198389907070707, 0.0080000000000382, false, 0, null, 0);
            status = swModelDocExt.SelectByID2("", "FACE", 0.228097744219978, 0.151927063973064, 0.0040000000000191, false, 0, null, 0);
            swModel.ClearSelection2(true);
            status = swModelDocExt.SelectByID2("", "VERTEX", 0.216278249046016, 0.198389907070707, 0.0080000000000382, true, 1, null, 0);
            status = swModelDocExt.SelectByID2("", "FACE", 0.228097744219978, 0.151927063973064, 0.0040000000000191, true, 2, null, 0);
            swSelectionMgr = (SelectionMgr)swModel.SelectionManager;
            swView = (View)swSelectionMgr.GetSelectedObjectsDrawingView2(1, -1);
            holeTableTemplate = "C:\\Program Files\\SolidWorks Corp\\SolidWorks\\lang\\english\\standard hole table--letters.sldholtbt";
            swHoleTableAnnotation = (HoleTableAnnotation)swView.InsertHoleTable2(false, 0.0540658670033671, 0.253819263748597, 1, "A", holeTableTemplate);
            swModel.ClearSelection2(true);
 
            //Get hole table and its datum origin
            swHoleTable = (HoleTable)swHoleTableAnnotation.HoleTable;
            swDatumOrigin = (DatumOrigin)swHoleTable.DatumOrigin;
 
            //Get datum origin's x and y labels
            Debug.Print("Datum origin:");
            Debug.Print("  X label: " + swDatumOrigin.XLabel);
            Debug.Print("  Y label: " + swDatumOrigin.YLabel);
 
            //Get whether to display hole sizes using ANSI inch letters and drill numbers
            Debug.Print("Display ANSI inch letter and drill number sizes in hole table? " + swHoleTable.ShowANSIInchLetterNumberDrillSizes);
 
        }
 
        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}
This example shows how to insert a part number column in a BOM table.

//---------------------------------------------------
// Preconditions:
// 1. Open a drawing that contains a BOM table.
// 2. Right-click the BOM table, select Select,
//    and select Table.
// 3. Open the Immediate window.
//
// Postconditions:
// 1. Inserts a part number column at the end of the
//    the BOM table.
// 2. Examine the BOM table and Immediate window.
//--------------------------------------------------- 
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Diagnostics;
using System.Windows.Forms;
namespace InsertColumn2TableAnnotationCSharp.csproj

{

partial class SolidWorksMacro

{

    

    public void Main()

    {

        ModelDoc2 swModel = default(ModelDoc2);

        bool boolstatus = false;

        SelectionMgr SelMgr = default(SelectionMgr);

        TableAnnotation theTableAnnotation = default(TableAnnotation);

        int SelObjType = 0;

        int TableAnnotationType = 0;

 

        swModel = (ModelDoc2)swApp.ActiveDoc;

        SelMgr = (SelectionMgr)swModel.SelectionManager;

        SelObjType = SelMgr.GetSelectedObjectType3(1, -1);

        if (SelObjType != (int)swSelectType_e.swSelANNOTATIONTABLES)

        {

            MessageBox.Show("Select a BOM table in the drawing before running this example.");

            return;

        }

        theTableAnnotation = (TableAnnotation)SelMgr.GetSelectedObject6(1, -1);

        TableAnnotationType = theTableAnnotation.Type;

        if (TableAnnotationType != (int)swTableAnnotationType_e.swTableAnnotation_BillOfMaterials)

        {

            MessageBox.Show("Select a BOM table in the drawing before running this example.");

            return;

        }

        Debug.Print("Table before inserting a column...");

        // Display table before inserting a column

        DisplayTableColumnProps(theTableAnnotation);

 

        // Insert new column 

        boolstatus = theTableAnnotation.InsertColumn2((int)swTableItemInsertPosition_e.swTableItemInsertPosition_Last, 0, "New Column", (int)swInsertTableColumnWidthStyle_e.swInsertColumn_DefaultWidth);

        boolstatus = theTableAnnotation.SetColumnType2(theTableAnnotation.ColumnCount - 1, (int)swTableColumnTypes_e.swBomTableColumnType_PartNumber, true);

 

        Debug.Print(" ");

 

        Debug.Print("Table after inserting a column...");

        // Display table after inserting a column

        DisplayTableColumnProps(theTableAnnotation);

    }

 

 

    public void DisplayTableColumnProps(TableAnnotation theTableAnnotation)

    {

        int ColCount = 0;

        int i = 0;

        string iString = null;

        int ColType = 0;

        string ColTypeString = null;

        string ColTitle = null;

        Debug.Print("Col# " + "Type  " + "Title");

        ColCount = theTableAnnotation.ColumnCount;

        for (i = 0; i <= ColCount - 1; i++)

        {

            ColType = theTableAnnotation.GetColumnType2(i, true);

            ColTypeString = System.Convert.ToString(ColType);

            ColTitle = theTableAnnotation.GetColumnTitle2(i, true);

            iString = System.Convert.ToString(i);

            Debug.Print(iString + "    " + ColTypeString + "  " + ColTitle);

        }

    }

    /// <summary> 

    /// The SldWorks swApp variable is pre-assigned for you. 

    /// </summary> 

    public SldWorks swApp;

} 

}
This example shows how to create a drag arrow manipulator, which is called a handle in the user interface.

//---------------------------------------------------------------------------
// Preconditions:
// 1. Open a part or assembly and select a face.
// 2. De-select Tools > Options > Stop VSTA debugger on macro exit.
// 3. Select Project > Add Reference > .NET > SolidWorks.Interop.swpublished.
// 4. Rename the namespace to match the name of your C# project.
// 5. Open an Immediate window.
//
// Postconditions:
// 1. A unidirectional drag arrow manipulator or handle is created on the selected face.
// 2. Drag the handle to another location. The first time you drag the handle,
//    IDragArrowManipulator::FixedLength is set to true,
//    and the origin is moved in the direction of the drag. For second and
//    subsequent drags, IDragArrowManipulator::FixedLength is set to false,
//    and the origin is not changed.
// 3. When you drag the handle a ruler displays. 
//    IDragArrowManipulator::ShowRuler is true.
// 4. When you drag the handle past length = 0, the handle flips direction.
//    IDragArrowManipulator::AllowFlip is true.
// 5. Inspect the Immediate window.
//--------------------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using SolidWorks.Interop.swpublished;
using System;
using System.Runtime;
using System.Diagnostics;
namespace CreateDragArrow_CSharp.csproj
{
    partial class SolidWorksMacro
    {
        Manipulator swManip;
        DragArrowManipulator swDrag;
        SwManHandler2 swDragHdlr = new SwManHandler2();

        public void Main()
        {
            
            Face2 swFace;
            MathUtility swMathUtil = default(MathUtility);
            ModelDoc2 swModel = default(ModelDoc2);
            ModelViewManager swModViewMgr = default(ModelViewManager);
            SelectionMgr swSelMgr = default(SelectionMgr);
            object vPickPt = null;
            MathPoint swPickPt = default(MathPoint);

            swMathUtil = (MathUtility)swApp.GetMathUtility();
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swSelMgr = (SelectionMgr)swModel.SelectionManager;
            swFace = (Face2)swSelMgr.GetSelectedObject6(1, 0);

            double[] nVector = new double[3];
            object vVector = null;
            nVector[0] = 0;
            nVector[1] = 1;
            nVector[2] = 0;
            vVector = nVector;

            MathVector swN = default(MathVector);
            swN = (MathVector)swMathUtil.CreateVector((vVector));

            vPickPt = swSelMgr.GetSelectionPoint2(1, -1);
            swPickPt = (MathPoint)swMathUtil.CreatePoint((vPickPt));
            swModViewMgr = swModel.ModelViewManager;

            swManip = swModViewMgr.CreateManipulator((int)swManipulatorType_e.swDragArrowManipulator, swDragHdlr);
            swDrag = (DragArrowManipulator)swManip.GetSpecificManipulator();

            swDrag.AllowFlip = true;
            swDrag.ShowRuler = true;
            swDrag.ShowOppositeDirection = true;
            swDrag.Length = 0.02;
            swDrag.Direction = swN;
            swDrag.LengthOppositeDirection = 0.01;
            swDrag.Origin = swPickPt;
            swManip.Show(swModel);
            swDrag.Update();

            MathPoint origin = default(MathPoint);
            origin = swDrag.Origin;

            object pt = null;
            pt = origin.ArrayData;

        }
        public SldWorks swApp;
    }
    [System.Runtime.InteropServices.ComVisible(true)]
    public class SwManHandler2 : SwManipulatorHandler2
    {
        int doneonce;

        const int lenFact = 1;
        private bool SwManipulatorHandler2_OnHandleLmbSelected(object pManipulator)
        {

            Debug.Print("SwManipulatorHandler2_OnHandleLmbSelected");
            return true;

        }
         bool ISwManipulatorHandler2.OnHandleLmbSelected(object pManipulator)
        {
            return SwManipulatorHandler2_OnHandleLmbSelected(pManipulator);
        }

        private bool SwManipulatorHandler2_OnDelete(object pManipulator)
        {

            Debug.Print("SwManipulatorHandler2_OnDelete");
            return true;

        }
         bool ISwManipulatorHandler2.OnDelete(object pManipulator)
        {
            return SwManipulatorHandler2_OnDelete(pManipulator);
        }

        private void SwManipulatorHandler2_OnDirectionFlipped(object pManipulator)
        {
           

            Debug.Print("SwManipulatorHandler2_OnDirectionFlipped");

        }
         void ISwManipulatorHandler2.OnDirectionFlipped(object pManipulator)
        {
            SwManipulatorHandler2_OnDirectionFlipped(pManipulator);
        }


        private bool SwManipulatorHandler2_OnDoubleValueChanged(object pManipulator, int Id, ref double Value)
        {

           
            doneonce = doneonce + 1;
            Debug.Print("SwManipulatorHandler2_OnDoubleValueChanged");

            Debug.Print("  ID               = " + Id);

            Debug.Print("  Value            = " + Value);
            DragArrowManipulator swTmpManipulator = default(DragArrowManipulator);
            swTmpManipulator = (DragArrowManipulator)pManipulator;
            //Update origin
            MathPoint swMathPoint = default(MathPoint);
            swMathPoint = swTmpManipulator.Origin;
            double[] varMathPt = null;
            varMathPt = (double[])swMathPoint.ArrayData;
            varMathPt[1] = varMathPt[1] + lenFact / 1000;
            swMathPoint.ArrayData = varMathPt;
            if ((doneonce == 1))
            {
                swTmpManipulator.FixedLength = true;
            }
            swTmpManipulator.Origin = swMathPoint;
            
            swTmpManipulator.Update();
            return true;
        }
         bool ISwManipulatorHandler2.OnDoubleValueChanged(object pManipulator, int Id, ref double Value)
        {
            return SwManipulatorHandler2_OnDoubleValueChanged(pManipulator, Id, ref Value);
        }


        private void SwManipulatorHandler2_OnEndDrag(object pManipulator, int handleIndex)
        {
            DragArrowManipulator swTmpManipulator = default(DragArrowManipulator);
            swTmpManipulator = (DragArrowManipulator)pManipulator;
            swTmpManipulator.FixedLength = false;
            doneonce = doneonce + 1;
            Debug.Print("SwManipulatorHandler2_OnEndDrag");

            Debug.Print("  HandleIndex      = " + handleIndex);




            if ((handleIndex == (int)swDragArrowManipulatorOptions_e.swDragArrowManipulatorDirection2))
            {
                Debug.Print(" Direction1");


            }
            else
            {
                Debug.Print(" Direction2");

            }

        }
         void ISwManipulatorHandler2.OnEndDrag(object pManipulator, int handleIndex)
        {
            SwManipulatorHandler2_OnEndDrag(pManipulator, handleIndex);
        }

        private void SwManipulatorHandler2_OnEndNoDrag(object pManipulator, int handleIndex)
        {

            Debug.Print("SwManipulatorHandler2_OnEndNoDrag");


        }
         void ISwManipulatorHandler2.OnEndNoDrag(object pManipulator, int handleIndex)
        {
            SwManipulatorHandler2_OnEndNoDrag(pManipulator, handleIndex);
        }



        private void SwManipulatorHandler2_OnHandleRmbSelected(object pManipulator, int handleIndex)
        {
            Debug.Print("SwManipulatorHandler2_OnHandleRmbSelected");

            Debug.Print("  handleIndex      = " + handleIndex);

        }
         void ISwManipulatorHandler2.OnHandleRmbSelected(object pManipulator, int handleIndex)
        {
            SwManipulatorHandler2_OnHandleRmbSelected(pManipulator, handleIndex);
        }



        private void SwManipulatorHandler2_OnHandleSelected(object pManipulator, int handleIndex)
        {
            Debug.Print("SwManipulatorHandler2_OnHandleSelected");

            Debug.Print("  HandleIndex      = " + handleIndex);

        }
         void ISwManipulatorHandler2.OnHandleSelected(object pManipulator, int handleIndex)
        {
            SwManipulatorHandler2_OnHandleSelected(pManipulator, handleIndex);
        }


        private void SwManipulatorHandler2_OnItemSetFocus(object pManipulator, int Id)
        {
            

            Debug.Print("SwManipulatorHandler2_OnItemSetFocus");

            Debug.Print("  ID               = " + Id);

        }
         void ISwManipulatorHandler2.OnItemSetFocus(object pManipulator, int Id)
        {
            SwManipulatorHandler2_OnItemSetFocus(pManipulator, Id);
        }


        private bool SwManipulatorHandler2_OnStringValueChanged(object pManipulator, int Id, ref string Value)
        {


            Debug.Print("SwManipulatorHandler2_OnStringValueChanged");

            Debug.Print("  ID               = " + Id);

            Debug.Print("  Value            = " + Value);
            return true;

        }
         bool ISwManipulatorHandler2.OnStringValueChanged(object pManipulator, int Id, ref string Value)
        {
            return SwManipulatorHandler2_OnStringValueChanged(pManipulator, Id, ref Value);
        }


        private void SwManipulatorHandler2_OnUpdateDrag(object pManipulator, int handleIndex, object newPosMathPt)
        {
            Debug.Print("SwManipulatorHandler2_OnUpdateDrag");

            Debug.Print("  HandleIndex      = " + handleIndex);

        }
         void ISwManipulatorHandler2.OnUpdateDrag(object pManipulator, int handleIndex, object newPosMathPt)
        {
            SwManipulatorHandler2_OnUpdateDrag(pManipulator, handleIndex, newPosMathPt);
        }



    }
}
This example shows how to get the objects in a selection set.

//----------------------------------------------------------------------
// Preconditions:
// 1. Verify that the assembly to open exists.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Opens the assembly.
// 2. Creates two selection sets.
// 3. Traverses the nodes in the FeatureManager design tree. If the
//    name of the node is Selection-Set1(3), then:
//    a. Gets the type of feature for this node.
//    b. Gets the Selection Sets folder.
//    c. Gets the selection set by name.
//    d. Suspends the current selection list, starts a new selection list, 
//       and adds the objects in the selection set to the new selection 
//       list.
//    e. Gets the number of objects in the selection list and traverses
//       the selection list.
//       1. Gets the type of object in the selection list.
//       2. Casts the object to a component.
//       3. Gets the name of the component.
//    f. Reinstates the suspended selection list.
// 4. Examine the Immediate window.
//
// NOTE: Because the assembly 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
{
    public partial class SolidWorksMacro
    {
        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            FeatureManager swFeatureMgr = default(FeatureManager);
            TreeControlItem rootNode = default(TreeControlItem);
            ModelDocExtension swModelDocExtension = default(ModelDocExtension);
            SelectionSet swSelectionSet1 = default(SelectionSet);
            SelectionSet swSelectionSet2 = default(SelectionSet);
            bool status = false;
            int errors = 0;
            int warnings = 0;
            string fileName = null;
 
            fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\wrench.sldasm";
            swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
            Debug.Print("File = " + swModel.GetPathName());
            swModelDocExtension = (ModelDocExtension)swModel.Extension;
 
            //Create a selection set
            status = swModelDocExtension.SelectByID2("arm1-1@wrench", "COMPONENT", 0, 0, 0, false, 0, null, 0);
            status = swModelDocExtension.SelectByID2("arm2-1@wrench", "COMPONENT", 0, 0, 0, true, 0, null, 0);
            status = swModelDocExtension.SelectByID2("clamp2-1@wrench", "COMPONENT", 0, 0, 0, true, 0, null, 0);
            swSelectionSet1 = (SelectionSet)swModelDocExtension.SaveSelection(out errors);
            swModel.ClearSelection2(true);
 
            //Create another selection set
            status = swModelDocExtension.SelectByID2("centerlink-1@wrench", "COMPONENT", 0, 0, 0, false, 0, null, 0);
            status = swModelDocExtension.SelectByID2("screw-1@wrench", "COMPONENT", 0, 0, 0, true, 0, null, 0);
            status = swModelDocExtension.SelectByID2("screw-1@wrench", "COMPONENT", 0, 0, 0, false, 0, null, 0);
            swSelectionSet2 = (SelectionSet)swModelDocExtension.SaveSelection(out errors);
            swModel.ClearSelection2(true);
 
            swFeatureMgr = (FeatureManager)swModel.FeatureManager;
            rootNode = (TreeControlItem)swFeatureMgr.GetFeatureTreeRootItem();
            if ((rootNode != null))
            {
                traverse_node(rootNode, swFeatureMgr, swModel);
            }
 
        }
 
        private void traverse_node(TreeControlItem node, FeatureManager swFeatureMgr, ModelDoc2 swModel)
        {
            TreeControlItem childNode = default(TreeControlItem);
            Feature featureNode = default(Feature);
            int nodeObjectType = 0;
            object nodeObject = null;
 
            nodeObjectType = node.ObjectType;
            nodeObject = (object)node.Object;
            switch (nodeObjectType)
            {
                case (int)swTreeControlItemType_e.swFeatureManagerItem_Feature:
                    if ((nodeObject != null))
                    {
                        featureNode = (Feature)nodeObject;
                        if (featureNode.Name == "Selection-Set1(3)")
                        {
                            Feature swSelectionSetFeature = default(Feature);
                            SelectionSetFolder swSelectionSetFolderFeature = default(SelectionSetFolder);
                            SelectionSet swSelectionSet = default(SelectionSet);
                            Component2 swComponent = default(Component2);
                            SelectionMgr swSelectionMgr = default(SelectionMgr);
                            int nbrSelections = 0;
                            int i = 0;
                            object selObj = null;
 
                            swSelectionSetFeature = (Feature)node.Object;
                            Debug.Print("Feature name: " + swSelectionSetFeature.Name);
                            Debug.Print("  Feature type: " + swSelectionSetFeature.GetTypeName2());
                            swSelectionSetFolderFeature = (SelectionSetFolder)swFeatureMgr.GetSelectionSetFolder();
                            swSelectionSet = (SelectionSet)swSelectionSetFolderFeature.GetSelectionSetByName(swSelectionSetFeature.Name);
                            Debug.Print("Selection set name: " + swSelectionSet.GetName());

                            swSelectionMgr = (SelectionMgr)swModel.SelectionManager;
                            swSelectionMgr.SuspendSelectionList();

                            swSelectionSet.Select();

                            nbrSelections = swSelectionMgr.GetSelectedObjectCount2(-1);
                            Debug.Print("  Number of objects selected in this selection set: " + nbrSelections);
                            for (i = 1; i <= nbrSelections; i++)
                            {
                                //Get each object in the new selection list
                                selObj = (object)swSelectionMgr.GetSelectedObject6(i, -1);
                                Debug.Print("    Object[" + i + "] in the selection list is of swSelectType_e = " + swSelectionMgr.GetSelectedObjectType3(i, -1) + "");
                                //Cast the object
                                swComponent = (Component2)selObj;
                                Debug.Print("       Name of component: " + swComponent.Name2);
                            }
                            swSelectionMgr.ResumeSelectionList();
                        }
                    }
                    break;
                default:
                    break;
            }
            childNode = (TreeControlItem)node.GetFirstChild();
            while ((childNode != null))
            {
                traverse_node(childNode, swFeatureMgr, swModel);
                childNode = (TreeControlItem)childNode.GetNext();
            } 
 
        }
 
        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}
This example shows how to thicken a surface and then generate a boss.

//----------------------------------------------------------------------------
// Preconditions:
// 1. Open a model document and select a boundary surface.
// 2. Open an Immediate window.
//
// Postconditions:
// 1. Creates a thicken feature.
// 2. Inspect the 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 GetThickenFeatureData_CSharp.csproj
{
    partial class SolidWorksMacro
    {
 
 
        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            SelectionMgr swSelMgr = default(SelectionMgr);
            FeatureManager swFeatMgr = default(FeatureManager);
            Feature swFeat = default(Feature);
            ThickenFeatureData swThicken = default(ThickenFeatureData);
            bool bRet = false;
 
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swSelMgr = (SelectionMgr)swModel.SelectionManager;
            swFeatMgr = swModel.FeatureManager;
 
            bRet = swSelMgr.SetSelectedObjectMark(1, 1, (int)swSelectionMarkAction_e.swSelectionMarkSet);
 
            swFeat = swFeatMgr.FeatureBossThicken(0.001, (int)swThickenThicknessType_e.swThickenSideOne, 0, false, true, true, true);
            swThicken = (ThickenFeatureData)swFeat.GetDefinition();
 
            Debug.Print("Feature: " + swFeat.Name);
            Debug.Print("  Automatically select all bodies? " + swThicken.AutoSelect);
            Debug.Print("  True if thicken feature affects specified bodies, false if it affects all bodies: " + swThicken.FeatureScope);
            Debug.Print("  Is a boss feature? " + swThicken.IsBossFeature());
            Debug.Print("  Merge the results if a multibody part?  " + swThicken.Merge);
            Debug.Print("  Fill a volume?  " + swThicken.FillVolume);
            Debug.Print("  Thickness:  " + swThicken.Thickness * 1000.0 + " mm");
            Debug.Print("  Thickness type as defined in swThickenThicknessType_e:  " + swThicken.ThicknessSide);
 
        }
 
 
 
        public SldWorks swApp;
 
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值