IFeature Interface

本文档详细介绍了如何使用SolidWorks API来访问和操作模型中的特征,包括获取特征信息、编辑特征定义、处理特征的可见性和选择状态,以及管理特征的显示尺寸和属性。示例代码涵盖了从获取特征创建者、属性和修改日期,到编辑特征定义、绘制显示尺寸、获取和修改特征状态等多个方面,展示了SolidWorks API的强大功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Solidworks学习笔记-链接Solidworks

属性

NameDescription备注
CreatedByGets the name of the user who created the feature.  获取创建该特征的用户的名称。
CustomPropertyManagerGets the custom property information for weldment and cut-list item features only.  仅获取焊件和切割清单项目特征的自定义属性信息。
DateCreatedGets the date on which the feature was created.  获取创建要素的日期。
DateModifiedGets the date on which the feature was last modified.  获取上次修改特征的日期。
DescriptionGets or sets the description for this feature.  获取或设置此特征的描述。
ExcludeFromCutListGets or sets whether to exclude this feature from the cut list.  获取或设置是否从切割清单中排除该特征。
NameGets or sets the name of the current feature.  获取或设置当前特征的名称。
VisibleGets the visibility state of this feature.  获取此特征的可见性状态。
This example shows how to get the names of the creators of features in a part document.

//-------------------------------------------------
// Preconditions: 
// 1. Verify that the specified part exists.
// 2. Open the Immediate window.
//
// Postconditions: 
// 1. Gets the names of the features and their creators.
// 2. Examine the Immediate window.
//-------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
 
namespace CloseDocCSharp.csproj
{
 
    partial class SolidWorksMacro
    {
 
 
        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            Feature swFeat = default(Feature);
            string Filename = null;
            int errors = 0;
            int warnings = 0;
 
            Filename = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\cstick.sldprt";
 
            // Open document
            swApp.OpenDoc6(Filename, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
            swModel = (ModelDoc2)swApp.ActiveDoc;
 
            // Get first feature in this part document
            swFeat = (Feature)swModel.FirstFeature();
 
            // Iterate over features in this part document in 
            // FeatureManager design tree 
            while ((swFeat != null))
            {
                // Write the name of the feature and its 
                // creator to the Immediate window
                Debug.Print("  Feature " + swFeat.Name + " created by " + swFeat.CreatedBy);
 
                // Get next feature in this part document
                swFeat = (Feature)swFeat.GetNextFeature();
            }
 
            swApp.CloseDoc(Filename);
 
        }
 
        /// <summary>
        /// The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
 
        public SldWorks swApp;
 
    }
}

方法

NameDescription备注
AddCommentAdds a comment to this feature.  对此特征添加评论。
AddPropertyExtensionAdds a property extension to this feature.  向此特征添加属性扩展。
DeSelectDeselects this feature.  取消选择此特征。
EnumDisplayDimensionsThis method returns a display dimensions enumeration for this feature.  此方法返回此特征的显示尺寸枚举。
GetAffectedFaceCountGets the number of faces modified by a feature, such as a draft feature.  获取特征修改的面数,例如草图特征。
GetAffectedFacesGets the faces modified by a feature, such as a draft feature.  获取由特征(例如草图特征)修改的面。
GetBoxGets the bounding box for this feature.  获取此特征的边界框。
GetChildrenGets the child features belonging to this feature.  获取属于此特征的子特征。
GetCreatedVersionGets the SOLIDWORKS version number in which the selected feature was created.  获取创建选定特征的 SOLIDWORKS 版本号。
GetDefinitionGets the feature data object for a feature, such as an advanced mate, extrusion, loft, fillet, chamfer, etc., in order to access the parameters that control the definition of this feature.  获取特征的特征数据对象,例如高级配合、拉伸、放样、圆角、倒角等,以访问控制此特征定义的参数。
GetDisplayDimensionGets the display dimension object for the specified pattern property.  获取指定图案属性的显示尺寸对象。
GetEditStatusGets whether the feature can currently be edited.  获取当前是否可以编辑该要素。
GetErrorCode2Gets the error code for this feature.  获取此特征的错误代码。
GetFaceCountGets the number of faces in this feature.  获取此特征中的面数。
GetFacesGets the faces in this feature.  获取此特征中的面。
GetFirstDisplayDimensionProvides access to the dimensions that belong to this feature by returning the first display dimension associated with this feature.  通过返回与此特征关联的第一个显示维度,提供对属于此特征的维度的访问。
GetFirstSubFeatureGets the first sub-feature that belongs to this feature.  获取属于此特征的第一个子特征。
GetIDGets the feature ID of this feature.  获取此特征的特征 ID。
GetImportedFileNameGets the file name from an imported feature.  从导入的特征中获取文件名。
GetMaterialIdNameGets the material name.  获取材质名称。
GetMaterialPropertyValues2Gets the material property values for this feature in the specified configurations.  获取此特征在指定配置中的材料属性值。
GetMaterialUserNameGets the material name for this feature, which is visible to the user.  获取此特征的材料名称,该名称对用户可见。
GetModifiedVersionGets the SOLIDWORKS version number in which this feature was last modified.  获取上次修改此特征的 SOLIDWORKS 版本号。
GetNameForSelectionGets the selected feature's type and name.  获取所选特征的类型和名称。
GetNextDisplayDimensionGets the next display dimension associated with this feature.  获取与此特征关联的下一个显示维度。
GetNextFeatureGets the next feature in the part.  获取零件中的下一个特征。
GetNextSubFeatureGets the next sub-feature from the owner of this sub-feature.  从该子特征的所有者那里获取下一个子特征。
GetOwnerFeatureGets the feature that owns this feature.  获取拥有此特征的特征。
GetParentsGets the parent features for this feature.  获取此特征的父特征。
GetPropertyExtensionGets the property extension on this feature.  获取此特征的属性扩展。
GetSpecificFeature2Gets the more specific interface to a selected feature.  获取所选特征的更具体的界面。
GetTextureGets the texture applied to this feature in the specified configuration.  获取在指定配置中应用于此特征的纹理。
GetTypeNameGets the type of feature. NOTE: To get the underlying type of feature of an Instant3D feature (i.e., "ICE"), call this method; otherwise, call IFeature::GetTypeName2.获取要素的类型。注意:要获取 Instant3D 特征(即“ICE”)的基础特征类型,请调用此方法;否则,请调用 IFeature::GetTypeName2。
GetTypeName2Gets the type of feature.NOTE: To get the underlying type of feature of an Instant3D feature (i.e., "ICE"), call IFeature::GetTypeName; otherwise, call this method. 获取特征类型。注意:要获取 Instant3D 特征(即“ICE”)的基础特征类型,请调用 IFeature::GetTypeName;否则,调用此方法。
GetUIStateGets the user-interface state of the current feature.  获取当前特征的用户界面状态。
GetUpdateStampGets the current update stamp for this feature.  获取此特征的当前更新标记。
HasFrozenUpdatePendingGets whether this feature has pending freeze updates.  获取此特征是否有挂起的冻结更新。
HasMaterialPropertyValuesGets whether this feature has an appearance.  获取此特征是否具有外观。
IGetAffectedFacesGets the faces modified by a feature, such as a draft feature.  获取由特征(例如草图特征)修改的面。
IGetBoxGets the bounding box for this feature.  获取此特征的边界框。
IGetChildCountGets the number of child features that belong to this feature.  获取属于此特征的子特征的数量。
IGetChildrenGets the child features belonging to this feature.  获取属于此特征的子特征。
IGetDefinitionGets the feature data object for a feature, such as an extrusion, loft, fillet, chamfer, etc., in order to access the parameters that control the definition of this feature.  获取特征的特征数据对象,例如拉伸、放样、圆角、倒角等,以访问控制此特征定义的参数。
IGetFaces2Gets the faces in this feature.  获取此特征中的面。
IGetFirstSubFeatureGets the first sub-feature that belongs to this feature.  获取属于此特征的第一个子特征。
IGetMaterialPropertyValues2Gets the material property values for this feature in the specified configurations.  获取此特征在指定配置中的材料属性值。
IGetNextFeatureGets the next feature.  获取下一个特征。
IGetNextSubFeatureGets the next sub-feature from the owner of this sub-feature.  从该子特征的所有者那里获取下一个子特征。
IGetParentCountGets the number of parent features for this feature.  获取此特征的父特征数。
IGetParentsGets the parent features for this feature.  获取此特征的父特征。
IIsSuppressed2Gets whether the feature in the specified configurations is suppressed.  获取指定配置中的特征是否被压缩。
IListExternalFileReferences2Gets the names and statuses of the external references for the feature in a part or assembly.  获取零件或装配体中特征的外部参考的名称和状态。
IModifyDefinition2Updates the definition of a feature with the new values in an associated feature data object obtained with IFeature::IGetDefinition.  使用通过 IFeature::IGetDefinition 获得的关联特征数据对象中的新值更新特征定义。
IParameterGets a pointer to the object for the specified parameter or a pointer to the specified parameter.  获取指向指定参数的对象的指针或指向指定参数的指针。
IRemoveMaterialProperty2Removes material property values from this feature.  从此特征中删除材料属性值。
IsBase2Gets whether this feature is a base feature.  获取此特征是否为基础特征。
IsDimXpertAnnotationGets whether this feature is a DimXpert annotation.  获取此特征是否为 DimXpert 注释。
IsDimXpertFeatureGets whether this feature is a DimXpert feature.  获取此特征是否为 DimXpert 特征。
ISetBody3Replaces the body of the base feature.  替换基本特征的主体。
ISetMaterialPropertyValues2Sets the material property values for this feature in the specified configurations.  在指定的配置中设置此特征的材料属性值。
ISetSuppression2Sets the suppression state of this feature.  设置此特征的压缩状态。
IsFrozenGets whether this feature is frozen.  获取此特征是否被冻结。
IsHiddenLockGets whether this feature is the freeze bar.  获取此特征是否为冻结栏。
IsRolledBackGets whether this feature is rolled back.  获取此特征是否回滚。
IsSuppressed2Gets whether the feature in the specified configurations is suppressed.  获取指定配置中的特征是否被压缩。
ListExternalFileReferences2Gets the names and statuses of the external references on the feature in a part or assembly.  获取零件或装配体中特征的外部参考的名称和状态。
ListExternalFileReferencesCountGets the number of external references on the feature in a part or assembly.  获取零件或装配体中特征的外部参考数。
MakeSubFeatureMakes a feature become a subfeature of this feature.  使特征成为该特征的子特征。
ModifyDefinitionUpdates the definition of a feature with the new values in an associated feature data object obtained with IFeature::GetDefinition.  使用通过 IFeature::GetDefinition 获得的关联特征数据对象中的新值更新特征定义。
MoveFreezeBarTo2Moves the freeze bar to the specified location in the FeatureManager design tree.  将冻结栏移动到 FeatureManager 设计树中的指定位置。
ParameterGets a pointer to the object for the specified parameter or a pointer to the specified parameter.  获取指向指定参数的对象的指针或指向指定参数的指针。
RemoveMaterialProperty2Removes material property values from this feature.  从此特征中删除材料属性值。
RemoveTextureRemoves texture from this feature in either all of the configurations or only the specified configuration.  在所有配置或仅指定配置中从此特征中移除纹理。
RemoveTextureByDisplayStateRemoves texture from this feature in the specified display state.  在指定的显示状态下从此特征中移除纹理。
ResetPropertyExtensionDeletes the property extension for this feature.  删除此特征的属性扩展。
Select2Selects and marks this feature.  选择并标记此特征。
SetBodiesToKeepSet the bodies to keep and their configurations for features that create multiple bodies in parts and assemblies.  为在零件和装配体中创建多个实体的特征设置要保留的实体及其配置。
SetBody2Replaces an imported base feature body.  替换导入的基础特征实体。
SetImportedFileNameSets the file name of an imported feature.  设置导入特征的文件名。
SetMaterialIdNameSets the material name for this feature.  设置此特征的材质名称。
SetMaterialPropertyValues2Sets the material property values for this feature in the specified configurations.  在指定的配置中设置此特征的材料属性值。
SetMaterialUserNameSets the material user name for this feature, which is visible to the user.  设置此特征的材质用户名,用户可见。
SetSuppression2Sets the suppression state of this feature.  设置此特征的压缩状态。
SetTextureApplies texture to this feature in either all configurations or only the specified configuration.  在所有配置中或仅在指定配置中将纹理应用于此特征。
SetTextureByDisplayStateApplies texture to this feature in the specified display state.  在指定的显示状态下将纹理应用于此特征。
SetUIStateSets the user-interface state of the current feature.  设置当前特征的用户界面状态。
UpdateExternalFileReferencesUpdates the external file references on this model.  更新此模型上的外部文件引用。

This example shows how to get the bounding boxes for the selected feature and face. This example also shows how to draw 3D sketches depicting the bounding boxes.

//----------------------------------------------
// Preconditions:
// 1. Verify that the part to open exists.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Selects the Sweep1 feature.
// 2. Creates a 3D sketch of the bounding box of
//    the selected Sweep1 feature.
// 3. Selects the top face.
// 4. Creates a 3D sketch of the bounding box of the 
//    selected face.
// 5. Examine the graphics area and the Immediate
//    window.
//
// NOTE: Because this 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 GetBoxFeatureFaceCSharp.csproj
{
    public partial class SolidWorksMacro
    {
 
 
        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            ModelDocExtension swModelDocExt = default(ModelDocExtension);
            SelectionMgr swSelMgr = default(SelectionMgr);
            Feature swFeat = default(Feature);
            Face2 swFace = default(Face2);
            object BoxFeatureArray = null;
            double[] BoxFeatureDblArray = new double[7];
            object BoxFaceArray = null;
            double[] BoxFaceDblArray = new double[7];
            SketchManager swSketchMgr = default(SketchManager);
            SketchPoint[] swSketchPt = new SketchPoint[9];
            SketchSegment[] swSketchSeg = new SketchSegment[13];
            bool status = false;
            int errors = 0;
            int warnings = 0;
            string fileName = null;
            int i = 0;
 
            // Open part document
            fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\cstick.sldprt";
            swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
 
            // Select feature
            swModelDocExt = (ModelDocExtension)swModel.Extension;
            swSelMgr = (SelectionMgr)swModel.SelectionManager;
            status = swModelDocExt.SelectByID2("Sweep1", "BODYFEATURE", 0, 0, 0, false, 0, null, 0);
            swFeat = (Feature)swSelMgr.GetSelectedObject6(1, -1);
 
            // Get selected feature's bounding box
            Debug.Print("Feature:");
            status = swFeat.GetBox(ref BoxFeatureArray);
            Debug.Assert(status);
 
            BoxFeatureDblArray = (double[])BoxFeatureArray;
 
            Debug.Print("  Pt1 = " + "(" + BoxFeatureDblArray[0] * 1000.0 + ", " + BoxFeatureDblArray[1] * 1000.0 + ", " + BoxFeatureDblArray[2] * 1000.0 + ") mm");
            Debug.Print("  Pt2 = " + "(" + BoxFeatureDblArray[3] * 1000.0 + ", " + BoxFeatureDblArray[4] * 1000.0 + ", " + BoxFeatureDblArray[5] * 1000.0 + ") mm");
            swModel.Insert3DSketch2(true);
            swModel.SetAddToDB(true);
            swModel.SetDisplayWhenAdded(false);

            swSketchMgr = (SketchManager)swModel.SketchManager;
            // Draw points at each corner of bounding box
            swSketchPt[0] = (SketchPoint)swSketchMgr.CreatePoint(BoxFeatureDblArray[3], BoxFeatureDblArray[1], BoxFeatureDblArray[5]);
            swSketchPt[1] = (SketchPoint)swSketchMgr.CreatePoint(BoxFeatureDblArray[0], BoxFeatureDblArray[1], BoxFeatureDblArray[5]);
            swSketchPt[2] = (SketchPoint)swSketchMgr.CreatePoint(BoxFeatureDblArray[0], BoxFeatureDblArray[1], BoxFeatureDblArray[2]);
            swSketchPt[3] = (SketchPoint)swSketchMgr.CreatePoint(BoxFeatureDblArray[3], BoxFeatureDblArray[1], BoxFeatureDblArray[2]);
            swSketchPt[4] = (SketchPoint)swSketchMgr.CreatePoint(BoxFeatureDblArray[3], BoxFeatureDblArray[4], BoxFeatureDblArray[5]);
            swSketchPt[5] = (SketchPoint)swSketchMgr.CreatePoint(BoxFeatureDblArray[0], BoxFeatureDblArray[4], BoxFeatureDblArray[5]);
            swSketchPt[6] = (SketchPoint)swSketchMgr.CreatePoint(BoxFeatureDblArray[0], BoxFeatureDblArray[4], BoxFeatureDblArray[2]);
            swSketchPt[7] = (SketchPoint)swSketchMgr.CreatePoint(BoxFeatureDblArray[3], BoxFeatureDblArray[4], BoxFeatureDblArray[2]);
           // Now draw bounding box
           swSketchSeg[0] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[0].X, swSketchPt[0].Y, swSketchPt[0].Z, swSketchPt[1].X, swSketchPt[1].Y, swSketchPt[1].Z);
           swSketchSeg[1] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[1].X, swSketchPt[1].Y, swSketchPt[1].Z, swSketchPt[2].X, swSketchPt[2].Y, swSketchPt[2].Z);
           swSketchSeg[2] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[2].X, swSketchPt[2].Y, swSketchPt[2].Z, swSketchPt[3].X, swSketchPt[3].Y, swSketchPt[3].Z);
           swSketchSeg[3] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[3].X, swSketchPt[3].Y, swSketchPt[3].Z, swSketchPt[0].X, swSketchPt[0].Y, swSketchPt[0].Z);
           swSketchSeg[4] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[0].X, swSketchPt[0].Y, swSketchPt[0].Z, swSketchPt[4].X, swSketchPt[4].Y, swSketchPt[4].Z);
           swSketchSeg[5] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[1].X, swSketchPt[1].Y, swSketchPt[1].Z, swSketchPt[5].X, swSketchPt[5].Y, swSketchPt[5].Z);
           swSketchSeg[6] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[2].X, swSketchPt[2].Y, swSketchPt[2].Z, swSketchPt[6].X, swSketchPt[6].Y, swSketchPt[6].Z);
           swSketchSeg[7] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[3].X, swSketchPt[3].Y, swSketchPt[3].Z, swSketchPt[7].X, swSketchPt[7].Y, swSketchPt[7].Z);
           swSketchSeg[8] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[4].X, swSketchPt[4].Y, swSketchPt[4].Z, swSketchPt[5].X, swSketchPt[5].Y, swSketchPt[5].Z);
           swSketchSeg[9] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[5].X, swSketchPt[5].Y, swSketchPt[5].Z, swSketchPt[6].X, swSketchPt[6].Y, swSketchPt[6].Z);
           swSketchSeg[10] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[6].X, swSketchPt[6].Y, swSketchPt[6].Z, swSketchPt[7].X, swSketchPt[7].Y, swSketchPt[7].Z);
           swSketchSeg[11] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[7].X, swSketchPt[7].Y, swSketchPt[7].Z, swSketchPt[4].X, swSketchPt[4].Y, swSketchPt[4].Z);
 
            swModel.SetDisplayWhenAdded(true);
            swModel.SetAddToDB(false);
            swModel.Insert3DSketch2(true);
 
            swModel.ClearSelection2(true);
 
            // Get selected face's bounding box
            status = swModelDocExt.SelectByID2("", "FACE", -7.62173696102764E-05, 0.219999999999857, 0.00945327855254163, false, 0, null, 0);
            swFace = (Face2)swSelMgr.GetSelectedObject6(1, -1);
 
            // Get selected face's bounding box
            Debug.Print("Face =");
            BoxFaceArray = (object)swFace.GetBox();
 
            BoxFaceDblArray = (double[])BoxFaceArray;
 
 
            Debug.Print("  Pt1 = " + "(" + BoxFaceDblArray[0] * 1000.0 + ", " + BoxFaceDblArray[1] * 1000.0 + ", " + BoxFaceDblArray[2] * 1000.0 + ") mm");
            Debug.Print("  Pt2 = " + "(" + BoxFaceDblArray[3] * 1000.0 + ", " + BoxFaceDblArray[4] * 1000.0 + ", " + BoxFaceDblArray[5] * 1000.0 + ") mm");
 
            swModel.Insert3DSketch2(true);
            swModel.SetAddToDB(true);
            swModel.SetDisplayWhenAdded(false);
 
            // Draw points at each corner of bounding box
            swSketchPt[0] = (SketchPoint)swSketchMgr.CreatePoint(BoxFaceDblArray[3], BoxFaceDblArray[1], BoxFaceDblArray[5]);
            swSketchPt[1] = (SketchPoint)swSketchMgr.CreatePoint(BoxFaceDblArray[0], BoxFaceDblArray[1], BoxFaceDblArray[5]);
            swSketchPt[2] = (SketchPoint)swSketchMgr.CreatePoint(BoxFaceDblArray[0], BoxFaceDblArray[1], BoxFaceDblArray[2]);
            swSketchPt[3] = (SketchPoint)swSketchMgr.CreatePoint(BoxFaceDblArray[3], BoxFaceDblArray[1], BoxFaceDblArray[2]);
            swSketchPt[4] = (SketchPoint)swSketchMgr.CreatePoint(BoxFaceDblArray[3], BoxFaceDblArray[4], BoxFaceDblArray[5]);
            swSketchPt[5] = (SketchPoint)swSketchMgr.CreatePoint(BoxFaceDblArray[0], BoxFaceDblArray[4], BoxFaceDblArray[5]);
            swSketchPt[6] = (SketchPoint)swSketchMgr.CreatePoint(BoxFaceDblArray[0], BoxFaceDblArray[4], BoxFaceDblArray[2]);
            swSketchPt[7] = (SketchPoint)swSketchMgr.CreatePoint(BoxFaceDblArray[3], BoxFaceDblArray[4], BoxFaceDblArray[2]);
 
            // Now draw bounding box
           swSketchSeg[0] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[0].X, swSketchPt[0].Y, swSketchPt[0].Z, swSketchPt[1].X, swSketchPt[1].Y, swSketchPt[1].Z);
           swSketchSeg[1] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[1].X, swSketchPt[1].Y, swSketchPt[1].Z, swSketchPt[2].X, swSketchPt[2].Y, swSketchPt[2].Z);
           swSketchSeg[2] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[2].X, swSketchPt[2].Y, swSketchPt[2].Z, swSketchPt[3].X, swSketchPt[3].Y, swSketchPt[3].Z);
           swSketchSeg[3] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[3].X, swSketchPt[3].Y, swSketchPt[3].Z, swSketchPt[0].X, swSketchPt[0].Y, swSketchPt[0].Z);
           swSketchSeg[4] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[0].X, swSketchPt[0].Y, swSketchPt[0].Z, swSketchPt[4].X, swSketchPt[4].Y, swSketchPt[4].Z);
           swSketchSeg[5] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[1].X, swSketchPt[1].Y, swSketchPt[1].Z, swSketchPt[5].X, swSketchPt[5].Y, swSketchPt[5].Z);
           swSketchSeg[6] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[2].X, swSketchPt[2].Y, swSketchPt[2].Z, swSketchPt[6].X, swSketchPt[6].Y, swSketchPt[6].Z);
           swSketchSeg[7] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[3].X, swSketchPt[3].Y, swSketchPt[3].Z, swSketchPt[7].X, swSketchPt[7].Y, swSketchPt[7].Z);
           swSketchSeg[8] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[4].X, swSketchPt[4].Y, swSketchPt[4].Z, swSketchPt[5].X, swSketchPt[5].Y, swSketchPt[5].Z);
           swSketchSeg[9] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[5].X, swSketchPt[5].Y, swSketchPt[5].Z, swSketchPt[6].X, swSketchPt[6].Y, swSketchPt[6].Z);
           swSketchSeg[10] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[6].X, swSketchPt[6].Y, swSketchPt[6].Z, swSketchPt[7].X, swSketchPt[7].Y, swSketchPt[7].Z);
           swSketchSeg[11] = (SketchSegment)swSketchMgr.CreateLine(swSketchPt[7].X, swSketchPt[7].Y, swSketchPt[7].Z, swSketchPt[4].X, swSketchPt[4].Y, swSketchPt[4].Z);
 
            swModel.SetDisplayWhenAdded(true);
            swModel.SetAddToDB(false);
            swModel.Insert3DSketch2(true);
 
        }
 
 
 
        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}
This example shows how to insert a DeleteFace feature and how to modify that feature.

// --------------------------------------------------------------------------- 
// Preconditions: 
// 1. Open public_documents\samples\tutorial\fillets\knob.sldprt.
// 2. Open the Immediate window.
// 
// Postconditions: 
// 1. Creates and modifies a DeleteFace feature.
// 2. Examine the Immediate window.
// 
// NOTE: Because this part document is used elsewhere, do not save changes.
// --------------------------------------------------------------------------- 

using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Diagnostics;
namespace DeleteFaceFeatureDataCSharp.csproj
{
    public partial class SolidWorksMacro
    {
        public void Main()
        {                  

        ModelDoc2 swModel = default(ModelDoc2); 
        ModelDocExtension swModelDocExt = default(ModelDocExtension);
        Feature swFeature = default(Feature); 
        DeleteFaceFeatureData swDeleteFaceFeature = default(DeleteFaceFeatureData); 
        string featureName = null; 
        bool boolstatus = false; 
        int opt = 0; 
        

        swModel = (ModelDoc2)swApp.ActiveDoc; 
        swModelDocExt = (ModelDocExtension)swModel.Extension;

 

        // Select a face for the 
        // DeleteFace feature 
        boolstatus = swModel.Extension.SelectByID2("", "FACE", 0.002251015125069, -0.001872569429423, 0.02015405789763, false, 0, null, 0);
   

        // Create a DeleteFace feature 
        boolstatus = swModelDocExt.InsertDeleteFace((int)swFaceDeleteOption_e.swFaceDelete_Default);        


        // Get the DeleteFace feature 
        swFeature = (Feature)swModel.FirstFeature(); 
        while ((swFeature != null)) { 
            featureName = swFeature.Name;              

            while (featureName != "DeleteFace1") { 
                swFeature = (Feature)swFeature.GetNextFeature(); 
                featureName = swFeature.Name; 
            } 
            

            Debug.Print("Feature name: " + featureName); 
            swDeleteFaceFeature = (DeleteFaceFeatureData)swFeature.GetDefinition(); 
            boolstatus = swDeleteFaceFeature.AccessSelections(swModel, null); 
            Debug.Print(" Number of deleted faces: " + swDeleteFaceFeature.GetDeletedFacesCount()); 
            

            // Get the DeleteFace feature's option 
            opt = swDeleteFaceFeature.Options; 
            Debug.Print(" Before changing the option..."); 
            DeleteFaceOptions(opt); 

            

            // Change the DeleteFace feature's option 
            swDeleteFaceFeature.Options = (int)swFaceDeleteOption_e.swFaceDelete_Patch; 
            opt = swDeleteFaceFeature.Options; 
            Debug.Print(" After changing the option..."); 
            DeleteFaceOptions(opt); 

            

            // Save modification made to DeleteFace feature 
            boolstatus = swFeature.ModifyDefinition(swDeleteFaceFeature, swModel, null); 

 

            // Get next feature until no more features 
            swFeature = (Feature)swFeature.GetNextFeature(); 

        }               

    } 
    

    public void DeleteFaceOptions(long options) 
    { 
        switch (options) { 
            case 0: 
                Debug.Print("  Option = swFaceDelete_Default"); 
                break; 
            case 1: 
                Debug.Print("  Option = swFaceDelete_Patch"); 
                break; 
            case 2: 
                Debug.Print("  Option = swFaceDelete_Fill"); 
                break; 
            case 3: 
                Debug.Print("  Option = swFaceDelete_FillWithTangent"); 
                break; 
        } 
    } 

    

        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;

    }

}
This example shows how to get the display dimensions for various pattern properties of a linear pattern.

//----------------------------------------------------------------------------
// Preconditions:
// 1. Open a part with a linear pattern.
// 2. Select the linear pattern feature.
// 3. Open the Immediate window.
//
// Postconditions: 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 GetDisplayDimension_CSharp.csproj
{
    partial class SolidWorksMacro
    {

        ModelDoc2 Part;
        SelectionMgr selMan;
        Feature feat;
        DisplayDimension dispDim;

        public void Main()
        {
            Part = (ModelDoc2)swApp.ActiveDoc;
            selMan = (SelectionMgr)Part.SelectionManager;
            feat = (Feature)selMan.GetSelectedObject6(1, -1);
            Debug.Print(" Feature = " + feat.Name);

            dispDim = (DisplayDimension)feat.GetDisplayDimension((int)swFeatureDimensionParameter_e.swPatternInstanceCount1);
            Debug.Print(" Instance count 1 display dimension = " + dispDim.GetNameForSelection());
            Debug.Print(" Type of dimension as defined in swDimensionType_e = " + dispDim.Type2);
            dispDim = (DisplayDimension)feat.GetDisplayDimension((int)swFeatureDimensionParameter_e.swPatternSpacing1);
            Debug.Print(" Spacing 1 display dimension = " + dispDim.GetNameForSelection());

        }


        public SldWorks swApp;

    }

}
This example shows how to get the editing status of one or more features.

//------------------------------------------------------------------------
// Preconditions
// 1. Open public_documents\samples\tutorial\introtosw\pressure_plate.sldprt.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. At System.Diagnostics.Debugger.Break(), examine the the Immediate  
//    window, graphics area, and FeatureManager design tree.
// 2. Press F5.
// 3. Examine the Immediate window again.
//
// NOTE: Because this document is used elsewhere, do not save changes.
//-------------------------------------------------------------------------
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()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            FeatureManager swFeatMgr = default(FeatureManager);
            SelectionMgr swSelMgr = default(SelectionMgr);
            ModelDocExtension swModelDocExt = default(ModelDocExtension);
            Object[] varFeat;
            long editStatus = 0;
            bool retVal = false;
            long i = 0;
            string featName = null;
 
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swFeatMgr = swModel.FeatureManager;
            swSelMgr = (SelectionMgr)swModel.SelectionManager;
            swModelDocExt = swModel.Extension;
 
            // Traverse through the FeatureManager design tree 
            // to get the editing status of all features 
            // Change the editing status of a sketch and feature 
            // during feature traversal 
            varFeat = (Object[])swFeatMgr.GetFeatures(true);
            editStatus = (long)swFeatureEditStatus_e.swFeature_NonEditable;
            for (i = varFeat.GetLowerBound(0); i <= varFeat.GetUpperBound(0); i++)
            {
                Feature swFeat = default(Feature);
                swFeat = (Feature)varFeat[i];
                featName = swFeat.Name;
                switch ((featName))
                {
                    case "Sketch2":
                        // Select and edit a sketch 
                        retVal = swModelDocExt.SelectByID2("Sketch2", "SKETCH", 0, 0, 0, false, 0, null, 0);
                        swModel.EditSketch();
 
                        System.Diagnostics.Debugger.Break();
                        // Examine the Immediate window, graphics area, and FeatureManager design tree
                        // All of the features beneath Extrude1 cannot be edited because
                        // Extrude2's Sketch2 is in edit mode
                        // Press F5
 
                        break;
 
                    case "Extrude3":
                        // Close the open sketch 
                        swModel.InsertSketch2(true);
                        break;
                    case "Cut-Extrude2":
                        // Select and edit a feature 
                        retVal = swModelDocExt.SelectByID2("Cut-Extrude2", "BODYFEATURE", 0, 0, 0, false, 0, null, 0);
                        swModel.FeatEdit();
                        break;
                }
 
                // Get the editing status of the current feature 
                editStatus = swFeat.GetEditStatus();
                switch ((editStatus))
                {
                    case 0:
                        Debug.Print(swFeat.Name + " can be edited.");
                        break;
                    case 1:
                        Debug.Print(swFeat.Name + " cannot currently be edited.");
                        break;
                    case 2:
                        Debug.Print(swFeat.Name + " is already being edited.");
                        break;
                }
                swFeat = null;
            }
 
            // End feature editing 
            swModel.InsertSketch2(true);
        }
        public SldWorks swApp;
    }
}
This example shows how to eliminate multiple feature faces.

NOTE: In SOLIDWORKS, a face is the result of evaluating a feature. A face can be owned by several features. IFeature::GetFaces returns all faces owned by a feature. This is different from faces highlighted in the user interface when a feature is selected, because the user interface filters out multiple feature faces. This filter is for display purposes only. An application must use IFace::GetFeature to filter out multiple feature faces. This method returns only the oldest feature from a face; that is, the first owning feature in the FeatureManager design tree. 

//-----------------------------------------------
// Preconditions:
// 1. Open a part document.
// 2. Select a feature in the FeatureManager design
//    tree.
// 3. Open the Immediate window.
//
// Postconditions:
// 1. Gets the name of the feature and number
//    of faces.
// 2. Colors the faces of the feature blue.
//    NOTE: The faces are the same faces as if you
//    selected the feature in the user interface.
// 3. Examine the Immediate window and graphics area.
//-----------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
 
namespace GetFaceCountCSharp.csproj
{
    public partial class SolidWorksMacro
    {
        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            SelectionMgr swSelMgr = default(SelectionMgr);
            SelectData swSelData = default(SelectData);
            Feature swFeat = default(Feature);
            Feature swFaceFeat = default(Feature);
            object[] faceArr = null;
            double[] featColors = null;
            Face2 swFace = default(Face2);
            Entity swEnt = default(Entity);
            bool status = false;
 
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swSelMgr = (SelectionMgr)swModel.SelectionManager;
            swFeat = (Feature)swSelMgr.GetSelectedObject6(1, -1);
            swSelData = (SelectData)swSelMgr.CreateSelectData();
 
            Debug.Print("Feature = " + swFeat.Name + " [" + swFeat.GetTypeName() + "]");
            Debug.Print("  Face count = " + swFeat.GetFaceCount());
 
            swModel.ClearSelection2(true);
 
            featColors = (double[])swModel.MaterialPropertyValues;
            featColors[0] = 0;    //R
            featColors[1] = 0;    //G
            featColors[2] = 1;    //B
 
            faceArr = (object[])swFeat.GetFaces();
            if ((faceArr == null))
                return;
            foreach (object oneFace in faceArr)
            {
                swFace = (Face2)oneFace;
                swEnt = (Entity)swFace;
                swFaceFeat = (Feature)swFace.GetFeature();
                // Check to see if face is owned by multiple features
                if (object.ReferenceEquals(swFaceFeat, swFeat))
                {
                    status = swEnt.Select4(true, swSelData);
                    Debug.Assert(status);
                    swFace.MaterialPropertyValues = featColors;
                }
                else
                {
                    Debug.Print("  Other feature = " + swFaceFeat.Name + " [" + swFaceFeat.GetTypeName() + "]");
                }
            }
 
        }
 
        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}
This example shows how to get display dimension annotations.

//-----------------------------------------------------------
// Preconditions:
// 1. Verify that the specified part document exists.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Opens the specified part document and selects
//    a sketch containing multiple dimensions.
// 2. Iterates the display dimensions and gets 
//    each display dimension annotation and its position.
// 3. Moves each display dimension annotation 100mm to
//    the right.
// 4. Examine the graphics area and Immediate window.
//
// NOTE: Because the part document is used elsewhere, do not
// save changes.
//------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
 
namespace TraverseAnnotationsCSharp.csproj
{
    public partial class SolidWorksMacro
    { 
 
        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            ModelDocExtension swModelDocExt = default(ModelDocExtension);
            SelectionMgr swSelMgr = default(SelectionMgr);
            Annotation swAnnotation = default(Annotation);
            double[] annotationPosition = null;
            Feature swFeature = default(Feature);
            DisplayDimension swDispDim = default(DisplayDimension);
            string fileName = null;
            int errors = 0;
            int warnings = 0;
            bool status = false;
 
            //Open part document
            fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\tolanalyst\\offset\\top_plate.sldprt";
            swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
 
            //Get and edit sketch with dimensions
            swModelDocExt = (ModelDocExtension)swModel.Extension;
            status = swModelDocExt.SelectByID2("Sketch1", "SKETCH", 0, 0, 0, false, 0, null, 0);
            swSelMgr = (SelectionMgr)swModel.SelectionManager;
            swFeature = (Feature)swSelMgr.GetSelectedObject6(1, -1);
            swModel.EditSketch();
 
            //Get the first display dimension 
            swDispDim = (DisplayDimension)swFeature.GetFirstDisplayDimension();
 
            //Iterate through all of the display dimension
            //annotations in the sketch
            while ((swDispDim != null))
            {
                Debug.Print("Display dimension annotation name:");
                //Get the display dimension annotation
                swAnnotation = (Annotation)swDispDim.GetAnnotation();
                Debug.Print("  " + swAnnotation.GetName());
                //Get the position of the display dimension annotation
                annotationPosition = (double[])swAnnotation.GetPosition();
                if ((annotationPosition != null))
                {
                    //Move the display dimension annotation 100mm to the right
                    swAnnotation.SetPosition2(annotationPosition[0] + 0.1, annotationPosition[1], annotationPosition[2]);
                }
                //Get the next display dimension
                swDispDim = (DisplayDimension)swFeature.GetNextDisplayDimension(swDispDim);
            }
 
        }
 
        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}
This example shows how to get the types and persistent IDs of underlying features of Instant3D features.

//-----------------------------------------------------
// Preconditions:
// 1. Verify that the specified part exists.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Opens the part and traverses the FeatureManager
//    design tree.
// 2. Gets the types of features, including the types
//    of underlying features and persistent IDs
//    of Instant3D features.
// 3. Examine the Immediate window.
//-----------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Diagnostics;

namespace Instant3DFeatureCSharp.csproj
{

    partial class SolidWorksMacro
    {


        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            Feature swFeature = default(Feature);
            string fileName = null;
            int errors = 0;
            int warnings = 0;

            fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\block.sldprt";
            swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);

            swFeature = (Feature)swModel.FirstFeature();

            SelectFeat(swFeature);

        }

        public bool SelectFeat(Feature featureTemp)
        {
            while ((featureTemp != null))
            {
                string featureName = null;
                featureName = featureTemp.GetTypeName2();

                Debug.Print(featureName);

                // Instant3D features are ICE features
                if (featureName == "ICE")
                {
                    Debug.Print("   Type:     " + featureTemp.GetTypeName());
                    Debug.Print("   ID:       " + featureTemp.GetID());
                }

                featureTemp = (Feature)featureTemp.GetNextFeature();
            }
            return true;
        }


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

        public SldWorks swApp;

    }
}
This example shows how to get the feature type and name of the selected feature for use with IModelDocExtension::SelectByID2.

//-------------------------------------------------------------------------------
// Preconditions: 
// 1. Open public_documents\samples\tutorial\floxpress\ball valve\ball_valve.sldasm.
// 2. Expand any component in the FeatureManager design tree 
//    and select one of its features. 
//

// Postconditions: 
// 1. Gets the selected feature's type and name.
// 2. Examine the Immediate window.
// 
// NOTE: Because this assembly document is used elsewhere, do not save changes.
//-------------------------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Diagnostics;
namespace GetNameForSelectionFeatureCSharp.csproj
{
    partial class SolidWorksMacro
    {
        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            ModelDocExtension swModelDocExt = default(ModelDocExtension);
            SelectionMgr swSelMgr = default(SelectionMgr);
            Feature swFeat = default(Feature);
            string featName = null;
            string featType = null;


            swModel = (ModelDoc2)swApp.ActiveDoc;
            swSelMgr = (SelectionMgr)swModel.SelectionManager;
            swModelDocExt = (ModelDocExtension)swModel.Extension;


            // Get the selected feature 
            swFeat = (Feature)swSelMgr.GetSelectedObject6(1, -1);

            swModel.ClearSelection2(true);


            // Get the feature's type and name 
            featName = swFeat.GetNameForSelection(out featType);
            swModelDocExt.SelectByID2(featName, featType, 0, 0, 0, true, 0, null, 0);


            // Print the feature's type and name 
            // to the Immediate window 
            Debug.Print("Feature type: " + featType);
            Debug.Print("Feature name: " + featName);
        }


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


        public SldWorks swApp;
    }
}
This example shows how to get the selections for a reference axis feature.

//-------------------------------------------------
// Preconditions:
// 1. Verify that the document to open exists.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Opens the specified document.
// 2. Gets the Axis1 feature.
// 3. Gets the entities that define Axis1.
// 4. Gets the type and name of the entities that define 
//    Axis1.
// 5. Examine the Immediate window.
//-------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
 
namespace IRefAxisFeatureDataGetSelectionCSharp.csproj
{
    public partial class SolidWorksMacro
    {
 
 
        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            PartDoc swPart = default(PartDoc);
            Feature swFeat = default(Feature);
            RefAxisFeatureData swRefAxisFeatureData = default(RefAxisFeatureData);
            Entity swEntity = default(Entity);
            int warnings = 0;
            int errors = 0;
            string fileName = null;
            object[] obj = null;
            object types = null;
            string aType = null;
            string name = null;
            int i = 0;
            int[] entTypes;
 
            fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\button.sldprt";
            swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
            swPart = (PartDoc)swModel;
 
            swFeat = (Feature)swPart.FeatureByName("Axis1");
            swRefAxisFeatureData = (RefAxisFeatureData)swFeat.GetDefinition();
            swRefAxisFeatureData.AccessSelections(swModel, null);
            obj = (object[])swRefAxisFeatureData.GetSelections(out types);
            swRefAxisFeatureData.ReleaseSelectionAccess();
 
            entTypes = (int[])types;
 
            Debug.Print("Entity:");
            Debug.Print("");
            for (i = 0; i < obj.GetLength(0); i++)
            {
                swEntity = (Entity)obj[i];
                swFeat = (Feature)swEntity;
                swEntity.Select(false);
                name = swFeat.GetNameForSelection(out aType);
                Debug.Print("  Type: " + entTypes[i]);
                Debug.Print("  Name: " + name);
                Debug.Print("");
            }
 
 
        }
 
        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}
This example shows how to add a spring to a motion study.

//---------------------------------------------------------------------------
// Preconditions:  
// 1. Open public_documents\samples\tutorial\api\wrench.sldasm.
// 2. Verify that the MotionManager tab is visible. If it is not visible,
//    click View > MotionManager.
// 3. Right-click the project, select Add Reference, click Browse, and 
//    select install_dir\api\redist\CLR2\SolidWorks.Interop.swmotionstudy.dll.
// 4. Open the Immediate window.
//
// Postconditions: 
// 1. Adds a spring feature between the grips of the wrench.
// 2. Examine the Immediate window.
//
// NOTE: Because the assembly is used elsewhere, do not save changes. 
//--------------------------------------------------------------------------

using SolidWorks.Interop.sldworks;

using SolidWorks.Interop.swconst;

using SwMotionStudy;

using System;

using System.Diagnostics;

namespace ExampleCS.csproj

{

    public partial class SolidWorksMacro

    {

        public void Main()

        {

            ModelDoc2 swModel;

            ModelDocExtension swModelDocExt;

            MotionStudyManager swMotionMgr;

            MotionStudy swMotionStudy1;

            SimulationSpringFeatureData swSpringFeat;

            bool boolstatus;

            Feature swFeat;

            SelectionMgr swSelMgr;

 

            swModel = swApp.ActiveDoc as ModelDoc2;

            swModelDocExt = swModel.Extension;

            swSelMgr = swModel.SelectionManager as SelectionMgr;

 

            // Get the MotionManager

            swMotionMgr = swModelDocExt.GetMotionStudyManager() as MotionStudyManager;

            if ((swMotionMgr == null))

            {

                return; 

            }

 

            // Get "MotionStudy1_Distance=0.5in"

            swMotionStudy1 = swMotionMgr.GetMotionStudy("MotionStudy1_Distance=0.5in");

            if ((swMotionStudy1 == null))

            {

                swApp.SendMsgToUser("MotionStudy1_Distance=0.5in is not available.");

                return; 

            }

 

            // Activate swMotionStudy1

            swMotionStudy1.Activate();

 

            // Define spring feature

            swSpringFeat = swMotionStudy1.CreateDefinition((int)swFeatureNameID_e.swFmAEMLinearMotionSpring) as SimulationSpringFeatureData;

            if (swSpringFeat == null)

            {

                Debug.Print("ERROR: Creation of Spring feature data object failed.");

                return;

            }

 

            // Select spring's endpoints

            Face2 swFace1;

            Face2 swFace2;

            swModel.ShowNamedView2("*Left", 3);

            boolstatus = swModelDocExt.SelectByID2("", "FACE", 0.03344586330968, 0.0525345575174, 0, true, 0, null, 0);

            swFace1 = swSelMgr.GetSelectedObject6(1, -1) as Face2;

            boolstatus = swModelDocExt.SelectByID2("", "FACE", 0.02244533711473, 0.0131288302002, 2.238961779386E-04, true, 0, null,

0);

            swFace2 = swSelMgr.GetSelectedObject6(2, -1) as Face2;

 

           // Set spring's characteristics

            swSpringFeat.SetEndPoints(swFace1, swFace2);

            swSpringFeat.CoilDiameter = 0.0102;

            swSpringFeat.NumberOfCoils = 3;

            swSpringFeat.WireDiameter = 0.00152;

            swSpringFeat.FreeLength = 0.02;

 

            // Create Spring feature

            swFeat = swMotionStudy1.CreateFeature(swSpringFeat) as Feature;            

            if (swFeat == null)

            {

                Debug.Print(" ERROR: Creation of the Spring feature failed.");

            }

            else

            {

                Debug.Print("Type of the feature added: " + swFeat.GetTypeName2());

            }

            Debug.Print("Type of spring as defined in swSpringType_e: " + swSpringFeat.Type.ToString());

        }

 

        /// <summary>

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

        /// </summary>

        public SldWorks swApp;

    }

}
This example shows how to move the freeze bar to another location in the FeatureManager design tree.

//----------------------------------------------------------------------------
// Preconditions:
// 1. Open public_documents\samples\tutorial\api\FreezeBarNeedsRebuild2.sldprt.
// 2. Inspect the FeatureManager design tree:
//    * The rebuild indicator is displayed in the FeatureManager design tree.
//    * The freeze bar is below Boss-Extrude1 in the FeatureManager design tree.
//    * Boss-Extrude1 is frozen in the FeatureManager design tree.
//    * Boss-Extrude2 is unfrozen in the FeatureManager design tree.
//    * Boss-Extrude1 has freeze updates pending.
//    * Boss-Extrude2 has no freeze updates pending.
//    * The model needs to be rebuilt.
//
// Postconditions:
// 1. Removes the rebuild indicator from the part.
// 2. Inspect the Immediate window to see which features have hidden locks.
// 3. Press F5 to continue.
//    * Freeze bar moved to the top of the FeatureManager design tree.
//    * Boss-Extrude1 is unfrozen.
// 4. Press F5 to continue.
//    * Freeze bar moved to the bottom of the FeatureManager design tree.
//    * Boss-Extrude1 and Boss-Extrude2 are frozen.
// 5. Press F5 to continue.
//    * Freeze bar moved to after Boss-Extrude2.
//    * Boss-Extrude1 and Boss-Extrude2 are frozen.
// 6. Press F5 to continue.
//    * Freeze bar moved to the top of the FeatureManager design tree.
//    * Boss-Extrude1 and Boss-Extrude2 are unfrozen.
// 7. Press F5 to continue.
//    * The model does not need to be rebuilt.
//    * Boss-Extrude1 and Boss-Extrude2 have no freeze updates pending.
// 8. Press F5 to close the model.
// 9. Inspect the Immediate window.
//
// NOTE: Because the model is used elsewhere,
// do not save changes when closing it.
// ---------------------------------------------------------------------------
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
namespace MoveFreezeBar_CSharp.csproj
{
    partial class SolidWorksMacro
    {

        ModelDoc2 swModel;
        ModelDocExtension swModDocExt;
        int lRet;
        FeatureManager featMgr;
        SelectionMgr selMgr;
        Feature featFrozen;
        Feature featUnFrozen;
        Feature feat;
        bool boolstatus;
        Object[] vfeats;

        public void Main()
        {
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModDocExt = swModel.Extension;
            featMgr = swModel.FeatureManager;
            selMgr = (SelectionMgr)swModel.SelectionManager;
 

            swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swUserEnableFreezeBar, true);
            swModDocExt.ShowPartRebuildIndicators = false;

            Debug.Print("Number of Features is " + swModel.GetFeatureCount());

            vfeats = (Object[])featMgr.GetFeatures(true);

            for (int i = 0; i < vfeats.GetLength(0); i++ )
            {
                feat = (Feature)vfeats[i];
                Debug.Print("Feature name from FeatureManager design tree is " + feat.Name);
                Debug.Print(feat.Name + " has a hidden lock? " + feat.IsHiddenLock());
            }

            boolstatus = swModDocExt.SelectByID2("Boss-Extrude1", "BODYFEATURE", 0, 0, 0, false, 0, null, 0);
            boolstatus = swModDocExt.SelectByID2("Boss-Extrude2", "BODYFEATURE", 0, 0, 0, true, 0, null, 0);

            feat = featMgr.GetFreezeLocation();
            if ((feat != null))
            {
                Debug.Print("");
                Debug.Print("Freeze bar location is after " + feat.Name);
                Debug.Print(feat.Name + " is frozen? " + feat.IsFrozen());
            }

            lRet = swModDocExt.NeedsRebuild2;
            Debug.Print("Needs rebuild? " + lRet);

            featFrozen = (Feature)selMgr.GetSelectedObject6(1, -1);
            Debug.Print("Feature " + featFrozen.Name + " has frozen updates pending? " + featFrozen.HasFrozenUpdatePending());
            featUnFrozen = (Feature)selMgr.GetSelectedObject6(2, -1);
            Debug.Print("Feature " + featUnFrozen.Name + " has frozen updates pending? " + featUnFrozen.HasFrozenUpdatePending());
            Debug.Print("");

            swModel.ClearSelection2(true);

            System.Diagnostics.Debugger.Break();

            if ((featFrozen.HasFrozenUpdatePending()))
            {
                lRet = featMgr.EditFreeze2((int)swMoveFreezeBarTo_e.swMoveFreezeBarToBeforeFeature, featFrozen.Name, true, true);
                Debug.Print("Freeze bar moved to the top of the FeatureManager design tree. Press F5.");
                System.Diagnostics.Debugger.Break();
                lRet = featMgr.EditFreeze2((int)swMoveFreezeBarTo_e.swMoveFreezeBarToEnd, "", true, true);
                Debug.Print("Freeze bar moved to the bottom of the FeatureManager design tree. Press F5.");
                System.Diagnostics.Debugger.Break();
                lRet = featMgr.EditFreeze2((int)swMoveFreezeBarTo_e.swMoveFreezeBarToAfterFeature, featUnFrozen.Name, true, true);
                Debug.Print("Freeze bar moved to after Boss-Extrude2. Press F5.");
                System.Diagnostics.Debugger.Break();
                lRet = featMgr.EditFreeze2((int)swMoveFreezeBarTo_e.swMoveFreezeBarToTop, "", true, true);
                Debug.Print("Freeze bar moved to the top of the FeatureManager design tree. Press F5.");
                System.Diagnostics.Debugger.Break();
            }
            else
            {
                lRet = featMgr.EditFreeze2((int)swMoveFreezeBarTo_e.swMoveFreezeBarToBeforeFeature, featFrozen.Name, true, true);
                lRet = featMgr.EditFreeze2((int)swMoveFreezeBarTo_e.swMoveFreezeBarToEnd, "", true, true);
                lRet = featMgr.EditFreeze2((int)swMoveFreezeBarTo_e.swMoveFreezeBarToBeforeFeature, featUnFrozen.Name, true, true);
                lRet = featMgr.EditFreeze2((int)swMoveFreezeBarTo_e.swMoveFreezeBarToAfterFeature, featUnFrozen.Name, true, true);
                lRet = featMgr.EditFreeze2((int)swMoveFreezeBarTo_e.swMoveFreezeBarToTop, "", true, true);
            }

            lRet = swModDocExt.NeedsRebuild2;
            Debug.Print("Needs rebuild? " + lRet);

            Debug.Print("Feature " + featFrozen.Name + " has frozen updates pending? " + featFrozen.HasFrozenUpdatePending());
            Debug.Print("Feature " + featUnFrozen.Name + " has frozen updates pending? " + featUnFrozen.HasFrozenUpdatePending());

            feat = featMgr.GetFreezeLocation();
            // feat = Null if freeze bar is at the top of FeatureManager design tree
            if ((feat != null))
            {
                Debug.Print(feat.Name + " is frozen? " + feat.IsFrozen());
            }

            Debug.Print("Press F5 to close the model.");
            System.Diagnostics.Debugger.Break();

            swApp.CloseDoc("");

        }


        public SldWorks swApp;

    }
}
This example shows how to get whether a feature is frozen.

//---------------------------------------------------------------------------
// Preconditions:
// 1. Open a part or assembly.
// 2. Select a frozen feature in the FeatureManager design tree.
//
// Postconditions: 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 FeatureIsFrozen_CSharp.csproj
{
    partial class SolidWorksMacro
    {

        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            SelectionMgr swSelMgr = default(SelectionMgr);
            Feature swFeat = default(Feature);
            bool bRet = false;

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swSelMgr = (SelectionMgr)swModel.SelectionManager;
            swFeat = (Feature)swSelMgr.GetSelectedObject6(1, -1);

            bRet = swFeat.IsFrozen();
            Debug.Print("Feature is frozen? " + bRet);

        }

        public SldWorks swApp;
    }
} 

 
This example shows how to change a dimension value in a model.

NOTE: Most of the SOLIDWORKS API functions operate in meters. Thus, if you pass in XValue_Passed = 2.0 and your model units are millimeters, then it appears as a 2000.0 in the model. If you need to determine the units used in the model, you can use the IModelDoc2::LengthUnit property and perform the appropriate conversion.
//----------------------------------------------------------------------------
// Preconditions:
// 1. Verify that the specified assembly document to open exists.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Opens the specified assembly document.
// 2. Changes the specified dimension parameter of the selected feature.
// 3. Examine the Immediate window.
//
// NOTE: Because the assembly document is used elsewhere,
// do not save changes.
//----------------------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
namespace Macro1CSharp.csproj
{
    partial class SolidWorksMacro
    {
        ModelDoc2 swModel;
        Feature swFeature;
        SelectionMgr swSelectionManager;
        Dimension swDim;
        string fileName;
        bool boolstatus;
        int errors;
        int warnings;

        public void Main()
        {
            fileName = "C:\\Users\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\assem2.sldasm";
            swModel = swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);

            boolstatus = swModel.Extension.SelectByID2("LocalCirPattern1", "COMPPATTERN", 0, 0, 0, false, 0, null, 0);
            swSelectionManager = (SelectionMgr)swModel.SelectionManager;
            swFeature = (Feature)swSelectionManager.GetSelectedObject6(1, -1);

            swDim = (Dimension)swFeature.Parameter("D3");

            Debug.Print("D3@LocalCirPattern1 is " + swDim.SystemValue.ToString() + " before changing it.");

            // Change D3 of LocalCirPattern1 from 360 degrees to 270 degrees (4.72 radians)
            errors = swDim.SetSystemValue3(4.72, (int)swSetValueInConfiguration_e.swSetValue_InThisConfiguration, null);

            swModel.EditRebuild3();

            Debug.Print("D3@LocalCirPattern1 is " + swDim.SystemValue.ToString() + " after changing it.");

        }

        public SldWorks swApp;

    }
} 
This example shows how to select the default SOLIDWORKS Right Plane.

//---------------------------------------------------------
// Preconditions: Open a new part document.
//
// Postconditions:
// 1. Selects the Right Plane.
// 2. Examine the graphics area.
//---------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
namespace GetPlanes_CSharp.csproj
{
    partial class SolidWorksMacro
    {


        public void Main()
        {
            // Select Right Plane (1-based index)
            const long ReqPlane = 3;

            ModelDoc2 swModel = default(ModelDoc2);
            Feature swFeat = default(Feature);
            long PlaneCount = 0;
            bool bRet = false;

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swFeat = (Feature)swModel.FirstFeature();

            while ((swFeat != null))
            {
                if ("RefPlane" == swFeat.GetTypeName())
                {
                    PlaneCount = PlaneCount + 1;

                    if (ReqPlane == PlaneCount)
                    {
                        bRet = swFeat.Select2(false, 0);
                        break; 
                    }
                }

                swFeat = (Feature)swFeat.GetNextFeature();
            }

        }



        public SldWorks swApp;

    }
}
This example shows how to cut a body and keep all bodies.

//----------------------------------------------------------------------------
// Preconditions:
//  1. Verify that the specified part document template exists.
//  2. Open the Immediate window.
//
// Postconditions:
// 1. Opens a new part document.
// 2. Creates a body.
// 3. Splits the body into two bodies.
// 4. Examine the graphics area and Immediate window.
//-----------------------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
 
namespace Macro1CSharp.csproj
{
    public partial class SolidWorksMacro
    {
        public PartDoc swPart;
        ModelDoc2 Part;
        bool boolstatus;
        Feature Feature;
 
        public void Main()
        {
            //Open new part document
            Part = (ModelDoc2)swApp.NewDocument("C:\\ProgramData\\SOLIDWORKS\\SOLIDWORKS 2015\\templates\\part.prtdot", 0, 0, 0);
 
            //Set up event
            swPart = (PartDoc)Part;
            AttachEventHandlers();
 
            //Create body
            CreateBodiesAndSketch();
            boolstatus = Part.Extension.SelectByID2("Sketch2", "SKETCH", 0, 0, 0, false, 0, null, 0);
            Feature = (Feature)Part.FeatureManager.FeatureCut3(true, false, false, (int)swEndConditions_e.swEndCondThroughAll, (int)swEndConditions_e.swEndCondBlind, 0.01, 0.01, false, false, false, false, 0.01745329251994, 0.01745329251994, false, false, false, false, false, true, true, false, false, false, (int)swStartConditions_e.swStartSketchPlane, 0, false);
             if ((Feature == null))
            {
                Debug.Print("No feature created.");
            }
        }
 
        public void CreateBodiesAndSketch()
        {
            //Create body
            boolstatus = Part.Extension.SelectByID2("Front Plane", "PLANE", -0.06869486923422, 0.06291203863612, -0.006492164309718, false, 0, null, 0);
            Part.ClearSelection2(true);
            Part.SketchRectangle(-0.0424567617866, 0.0388405707196, 0, 0.05638579404467, -0.03750124069479, 0, false);
            Part.ShowNamedView2("*Trimetric", 8);
            Part.ClearSelection2(true);
            boolstatus = Part.Extension.SelectByID2("Line2", "SKETCHSEGMENT", 0, 0, 0, false, 0, null, 0);
            boolstatus = Part.Extension.SelectByID2("Line1", "SKETCHSEGMENT", 0, 0, 0, true, 0, null, 0);
            boolstatus = Part.Extension.SelectByID2("Line4", "SKETCHSEGMENT", 0, 0, 0, true, 0, null, 0);
            boolstatus = Part.Extension.SelectByID2("Line3", "SKETCHSEGMENT", 0, 0, 0, true, 0, null, 0);
            Part.FeatureManager.FeatureExtrusion3(true, false, false, 0, 0, 0.12, 0.01, false, false, false,
            false, 0.01745329251994, 0.01745329251994, false, false, false, false, false, false, false,
            0, 0, false);
            Part.ClearSelection2(true);
 
            //Create sketch for cut feature
            boolstatus = Part.Extension.SelectByID2("", "FACE", -0.02909828822015, 0.03884057071963, 0.09843602253397, false, 0, null, 0);
            Part.SketchManager.InsertSketch(true);
            Part.ClearSelection2(true);
            object[] vSkLines = null;
            vSkLines = (object[])Part.SketchManager.CreateCornerRectangle(-0.0628943705795, -0.07743122635196, 0, 0.1160562766823, -0.04532565168643, 0);
            Part.ClearSelection2(true);
            boolstatus = Part.Extension.SelectByID2("Line2", "SKETCHSEGMENT", 0, 0, 0, false, 0, null, 0);
            boolstatus = Part.Extension.SelectByID2("Line1", "SKETCHSEGMENT", 0, 0, 0, true, 0, null, 0);
            boolstatus = Part.Extension.SelectByID2("Line4", "SKETCHSEGMENT", 0, 0, 0, true, 0, null, 0);
            boolstatus = Part.Extension.SelectByID2("Line3", "SKETCHSEGMENT", 0, 0, 0, true, 0, null, 0);
 
        }
 
        public void AttachEventHandlers()
        {
            AttachSWEvents();
        }
 
        public void AttachSWEvents()
        {
            swPart.PromptBodiesToKeepNotify += this.swPart_PromptBodiesToKeepNotify;
        }
 
        private int swPart_PromptBodiesToKeepNotify(object swFeat, ref object bodies)
        {
            Debug.Print("PartDoc_PromptBodiesToKeepNotify fired.");
            Feature theFeature = default(Feature);
            object[] bodiesArr = null;
            bodiesArr = (object[])bodies;
            if ((swFeat != null))
            {
                theFeature = (Feature)swFeat;
                object[] bodiesToKeep = new object[1];
                //Change BodyOption to Body1 or Body2 to show other options
                string BodyOption = null;
                BodyOption = "AllBodies";
                switch (BodyOption)
                {
                    case "AllBodies":
                        theFeature.SetBodiesToKeep(true, bodiesToKeep, (int)swInConfigurationOpts_e.swThisConfiguration, null);
                        break;
                    case "Body1":
                        bodiesToKeep[0] = bodiesArr[0];
                        theFeature.SetBodiesToKeep(false, bodiesToKeep, (int)swInConfigurationOpts_e.swThisConfiguration, null);
                        break;
                    case "Body2":
                        bodiesToKeep[0] = bodiesArr[1];
                        theFeature.SetBodiesToKeep(false, bodiesToKeep, (int)swInConfigurationOpts_e.swThisConfiguration, null);
                        break;
                }
            }
            return 1;
        }
 
        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值