IComponent2 Interface 学习

Solidworks学习笔记-链接Solidworks

在此基础上学习

允许访问程序集中的组件。

属性

NameDescription备注
ComponentReferenceGets or sets a component reference for this component.  获取或设置此组件的组件引用。
IMaterialPropertyValuesGets or sets the material properties for the selected component in the active configuration.  获取或设置活动配置中选定组件的材料属性。
IsGraphicsOnlyGets whether this component is graphics only.  获取此组件是否仅为图形。
IsSpeedPakGets whether the active configuration for this component is SpeedPak.  获取此组件的活动配置是否为 SpeedPak。
IsVirtualGets whether this component is a virtual component.NOTE: This property is a get-only property. Set is not implemented.获取此组件是否为虚拟组件。注意:此属性是一个仅获取属性。 
MaterialPropertyValuesGets or sets the material properties for the selected component in the active configuration.  获取或设置活动配置中选定组件的材料属性。
Name2Gets or sets the name of the selected component.   获取或设置所选组件的名称。
PresentationTransformGets or sets the component transform.  获取或设置组件转换。
ReferencedConfigurationGets or sets the active configuration used by this component.  获取或设置此组件使用的活动配置。
ReferencedDisplayState2Gets or sets the active display state of this component.  获取或设置此组件的活动显示状态。
SolvingGets the Solve as option (rigid or flexible) of this component.  获取该组件的 Solve as 选项(刚性或柔性)。
Transform2Gets or sets the component transform.  获取或设置组件转换。
UseNamedConfigurationGets whether a specified configuration or the in-use/last active configuration is used.  获取是使用指定配置还是使用中/上次活动配置。
VisibleGets or sets the visibility state of this component.  获取或设置此组件的可见性状态。

System.string ComponentReference {get; set;}

//This example shows how to get the name of a component to possibly use with a future //call to IModelDocExtension::SelectByID2, when selectively opening the assembly document //and specific components using ISldWorks::OpenDoc7 and IDocumentSpecification, etc. This //example also shows how to get and set a component reference.

//--------------------------------------------------------------------
// Preconditions:
// 1. Open an assembly document.
// 2. Select an entity (face, edge, vertex, or loop) on any
//    component in the graphics area.
// 3. Open the Immediate window.
//
// Postconditions:
// 1. Adds a component reference to the component to which the
//    entity belongs.
// 2. Examine the Immediate window.
// 3. Locate the component to which the component reference was added
//    in the FeatureManager design tree. If necessary, use the scrollbar
//    at the bottom of the FeatureManager design tree to see the component
//    reference.
//--------------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Diagnostics;
namespace GetSelectByIDStringComponent_CSharp.csproj
{
    partial class SolidWorksMacro
    {
        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            SelectionMgr swSelectionMgr = default(SelectionMgr);
            Entity swEntity = default(Entity);
            Component2 swComponent = default(Component2);

            swModel = (ModelDoc2)swApp.ActiveDoc;

            // Get the selected entity (i.e., face, edge, vertex, or loop) 
            // and get the name of its component 
            swSelectionMgr = (SelectionMgr)swModel.SelectionManager;
            swEntity = (Entity)swSelectionMgr.GetSelectedObject6(1, -1);
            swComponent = (Component2)swEntity.GetComponent();

            // Print the name of the component to which the 
            // the selected entity belongs 
            Debug.Print("Name of component to which the selected entity belongs: " + swComponent.GetSelectByIDString());

            // Set a component reference to this component 
            swComponent.ComponentReference = "TestComponentReference";
            Debug.Print("Component reference added to the component to which the selected entity belongs: " + swComponent.ComponentReference);

            // Rebuild the assembly to see the component reference 
            // beside the name of the component in the FeatureManager 
            // design tree 
            swModel.ForceRebuild3(true);
        }
        public SldWorks swApp;
    }
}

System.string Name2 {get; set;}

//This example shows how to traverse an assembly at the component and feature levels //using recursion.

//--------------------------------------------------------------------------
// Preconditions: 
// 1. Open an assembly document containing nested subassemblies.
// 2. Open the Immediate window.
//
// Postconditions: 
// 1. Traverses the assembly.
// 2. Examine the Immediate Window.
//---------------------------------------------------------------------------

using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Diagnostics;
namespace RecursiveTraverseAssemblyCSharp.csproj
{
 
    public partial class SolidWorksMacro
    {
 
        public void TraverseFeatureFeatures(Feature swFeat, long nLevel)
        {
            Feature swSubFeat;
            Feature swSubSubFeat;
            Feature swSubSubSubFeat;
            string sPadStr = " ";
            long i = 0;
 
            for (i = 0; i <= nLevel; i++)
            {
                sPadStr = sPadStr + " ";
            }
            while ((swFeat != null))
            {
                Debug.Print(sPadStr + swFeat.Name + " [" + swFeat.GetTypeName2() + "]");
                swSubFeat = (Feature)swFeat.GetFirstSubFeature();
 
                while ((swSubFeat != null))
                {
                    Debug.Print(sPadStr + "  " + swSubFeat.Name + " [" + swSubFeat.GetTypeName() + "]");
                    swSubSubFeat = (Feature)swSubFeat.GetFirstSubFeature();
 
                    while ((swSubSubFeat != null))
                    {
                        Debug.Print(sPadStr + "    " + swSubSubFeat.Name + " [" + swSubSubFeat.GetTypeName() + "]");
                        swSubSubSubFeat = (Feature)swSubSubFeat.GetFirstSubFeature();
 
                        while ((swSubSubSubFeat != null))
                        {
                            Debug.Print(sPadStr + "      " + swSubSubSubFeat.Name + " [" + swSubSubSubFeat.GetTypeName() + "]");
                            swSubSubSubFeat = (Feature)swSubSubSubFeat.GetNextSubFeature();
 
                        }
 
                        swSubSubFeat = (Feature)swSubSubFeat.GetNextSubFeature();
 
                    }
 
                    swSubFeat = (Feature)swSubFeat.GetNextSubFeature();
 
                }
 
                swFeat = (Feature)swFeat.GetNextFeature();
 
            }
 
        }
 
        public void TraverseComponentFeatures(Component2 swComp, long nLevel)
        {
            Feature swFeat;
 
            swFeat = (Feature)swComp.FirstFeature();
            TraverseFeatureFeatures(swFeat, nLevel);
        }
        public void TraverseComponent(Component2 swComp, long nLevel)
        {
            object[] vChildComp;
            Component2 swChildComp;
            string sPadStr = " ";
            long i = 0;
 
            for (i = 0; i <= nLevel - 1; i++)
            {
                sPadStr = sPadStr + " ";
            }
 
            vChildComp = (object[])swComp.GetChildren();
            for (i = 0; i < vChildComp.Length; i++)
            {
                swChildComp = (Component2)vChildComp[i];
                Debug.Print(sPadStr + "+" + swChildComp.Name2 + " <" + swChildComp.ReferencedConfiguration + ">");
 
                TraverseComponentFeatures(swChildComp, nLevel);
                TraverseComponent(swChildComp, nLevel + 1);
            }
        }
        public void TraverseModelFeatures(ModelDoc2 swModel, long nLevel)
        {
            Feature swFeat;
 
            swFeat = (Feature)swModel.FirstFeature();
            TraverseFeatureFeatures(swFeat, nLevel);
        }
        public void Main()
        {
 
            ModelDoc2 swModel;
            ConfigurationManager swConfMgr;
            Configuration swConf;
            Component2 swRootComp;
 
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swConfMgr = (ConfigurationManager)swModel.ConfigurationManager;
            swConf = (Configuration)swConfMgr.ActiveConfiguration;
            swRootComp = (Component2)swConf.GetRootComponent();
 
            System.Diagnostics.Stopwatch myStopwatch = new Stopwatch();
            myStopwatch.Start();
 
            Debug.Print("File = " + swModel.GetPathName());
 
            TraverseModelFeatures(swModel, 1);
 
            if (swModel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY)
            {
                TraverseComponent(swRootComp, 1);
            }
 
            myStopwatch.Stop();
            TimeSpan myTimespan = myStopwatch.Elapsed;
            Debug.Print("Time = " + myTimespan.TotalSeconds + " sec");
 
        }
 
 
        /// <summary> 
        /// The SldWorks swApp variable is pre-assigned for you. 
        /// </summary> 
        public SldWorks swApp;
    }
 
}
This example shows how to change the name of a component.

//-------------------------------------------------
// Preconditions:
// 1. Open an assembly document.
// 2. Select a component in the assembly.
// 3. Open the Immediate window.
// 4. Press F5.
//
// Postconditions:
// 1. The selected component's name is
//    changed to SW.
// 2. Examine the Immediate window and
//    FeatureManager design tree to verify.
//-------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
 
namespace ComponentName2CSharp.csproj
{
    partial class SolidWorksMacro
    {
        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            SelectionMgr swSelMgr = default(SelectionMgr);
            Component2 swComp = default(Component2);
 
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swSelMgr = (SelectionMgr)swModel.SelectionManager;
            swComp = (Component2)swSelMgr.GetSelectedObjectsComponent3(1, 0);
            if (swComp == null)
            {
                Debug.Print("Select a component and run the macro again.");
                return;
 
            }
            else
            {
                // swUserPreferenceToggle_e.swExtRefUpdateCompNames must be set to
                // false to change the name of a component using IComponent2::Name2
                swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swExtRefUpdateCompNames, false);
 
                // Print original name of component
                Debug.Print("  Original name of component = " + swComp.Name2);
 
                // Change name of component
                swComp.Name2 = "SW";
 
                // Print new name of component
                Debug.Print("  New name of component      = " + swComp.Name2);
            }
        }
 
 
        /// <summary>
        /// The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
 
        public SldWorks swApp;
 
    }
}

System.string ReferencedDisplayState2 {get; set;}

//This example shows how to set the active display state of a referenced component.

//--------------------------------------------------------
// Preconditions:
// 1. Open public_documents\samples\tutorial\driveworksxpress\mobile gantry.sldasm.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Selects leg<1>.
// 2. Gets the selected referenced component's active display state.
// 3. Sets the selected referenced component's active display state.
// 4. Examine the Immediate window, FeatureManager design tree,
//    and graphics area.
//
// 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 Macro1.csproj
{
    public partial class SolidWorksMacro
    {
        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            ModelDocExtension swModelDocExtension = default(ModelDocExtension);
            Component2 swComponent = default(Component2);
            SelectionMgr swSelectionManager = default(SelectionMgr);
            bool status = false;
 
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModelDocExtension = (ModelDocExtension)swModel.Extension;
            status = swModelDocExtension.SelectByID2("leg-1@mobile gantry", "COMPONENT", 0, 0, 0, false, 0, null, 0);
            swSelectionManager = (SelectionMgr)swModel.SelectionManager;
            swComponent = (Component2)swSelectionManager.GetSelectedObjectsComponent4(1, -1);
            Debug.Print("Get active display state: " + swComponent.ReferencedDisplayState2);
            swComponent.ReferencedDisplayState2 = "<Default<As Machined>>_Display State 1";
            Debug.Print("Set active display state: " + swComponent.ReferencedDisplayState2);
 
        }
 
        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}

System.int Solving {get;}

//This example shows how to find out if the selected component is resolved or suppressed, //hidden or visible, and whether or not it's a rigid or flexible subassembly. This //example also gets the persistent ID of the selected component.

//---------------------------------------------------
// Preconditions:
// 1. Ensure that the specified assembly document
//    to open exists.
// 2. Open the Immediate window.
// 3. Run the macro.
//
// Postconditions:
// 1. Opens the assembly document.
// 2. Selects the subassembly.
// 3. Prints to the Immediate window:
//    * Paths to the assembly and subassembly documents
//    * Whether the component is hidden, fixed,
//      or suppressed
//    * Component's persistent ID
//    * Component's solving state
// 4. Examine the Immediate window.
//----------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
 
namespace GetComponentStateCSharp.csproj
{
 
    partial class SolidWorksMacro
    {
 
 
        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            ModelDocExtension swModelDocExt = default(ModelDocExtension);
            AssemblyDoc swAssy = default(AssemblyDoc);
            SelectionMgr swSelMgr = default(SelectionMgr);
            Component2 swComp = default(Component2);
            string fileName = null;
            bool status = false;
            int errors = 0;
            int warnings = 0;
 
            // Open assembly document
            fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\advdrawings\\98food processor.sldasm";
            swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
            swModelDocExt = (ModelDocExtension)swModel.Extension;
 
            // Select subassembly
            status = swModelDocExt.SelectByID2("blade shaft-1@98food processor", "COMPONENT", 0, 0, 0, false, 0, null, 0);
            swSelMgr = (SelectionMgr)swModel.SelectionManager;
            swAssy = (AssemblyDoc)swModel;
            swComp = (Component2)swSelMgr.GetSelectedObjectsComponent3(1, 0);
 
            // Print to the Immediate window the path and state of the
            // selected component
            Debug.Print("File = " + swModel.GetPathName());
            Debug.Print("  Component   = " + swComp.Name2);
            Debug.Print("    Path           = " + swComp.GetPathName());
            Debug.Print("    IsHidden       = " + swComp.IsHidden(true));
            Debug.Print("    IsFixed        = " + swComp.IsFixed());
            Debug.Print("    GetSuppression = " + swComp.GetSuppression());
            Debug.Print("    ID             = " + swComp.GetID());
            // 0 =  if subassembly is rigid
            // 1 =  if subassembly is flexible
            // -1 = selected component is a part component
            Debug.Print("    Solving        = " + swComp.Solving);
        }
 
 
        /// <summary>
        /// The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
 
        public SldWorks swApp;
 
    }
}

MathTransform Transform2 {get; set;}

//This example shows how to transform a point from component space to assembly space.

//--------------------------------------------------------------
// Preconditions:
// 1. Verify that the specified assembly document to open
//    exists.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Opens the specified assembly document.
// 2. Selects a component.
// 3. Transforms the component's origin to a point in
//    assembly space.
// 4. Examine the Immediate window.
//--------------------------------------------------------------
 
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
 
namespace Transform2.csproj
{
    public partial class SolidWorksMacro
    {
 
        public void Main()
        {
            MathUtility swMathUtil = default(MathUtility);
            ModelDoc2 swModel = default(ModelDoc2);
            ModelDocExtension swModelDocExt = default(ModelDocExtension);
            SelectionMgr swSelMgr = default(SelectionMgr);
            Component2 swComp = default(Component2);
            MathTransform swXform = default(MathTransform);
            double[] nPt = new double[3];
            object vPt = null;
            MathPoint swPt = default(MathPoint);
            bool bRet = false;
            int errors = 0;
            int warnings = 0;
            string fileName = null;
 
            // Open assembly
            fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\smartcomponents\\stepped_shaft.sldasm";
            swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
            swModelDocExt = (ModelDocExtension)swModel.Extension;
            bRet = swModelDocExt.SelectByID2("stepped_shaft-1@stepped_shaft", "COMPONENT", 0, 0, 0, false, 0, null, 0);
 
            swMathUtil = (MathUtility)swApp.GetMathUtility();
            swSelMgr = (SelectionMgr)swModel.SelectionManager;
            swComp = (Component2)swSelMgr.GetSelectedObjectsComponent(1);
            swXform = (MathTransform)swComp.Transform2;
 
            // Point at component origin
            nPt[0] = 0.0;
            nPt[1] = 0.0;
            nPt[2] = 0.0;
            vPt = nPt;
            swPt = (MathPoint)swMathUtil.CreatePoint(vPt);
            swPt = (MathPoint)swPt.MultiplyTransform(swXform);
            Debug.Print("File = " + swModel.GetPathName());
            Debug.Print("  Component = " + swComp.Name2 + " [" + swComp.GetPathName() + "]");
            Debug.Print("    Point in component = (" + nPt[0] * 1000.0 + ", " + nPt[1] * 1000.0 + ", " + nPt[2] * 1000.0 + ") mm");
            Debug.Print("    Point in assembly = (" + ((double[])swPt.ArrayData)[0] * 1000.0 + ", " + ((double[])swPt.ArrayData)[1] * 1000.0 + ", " + ((double[])swPt.ArrayData)[2] * 1000.0 + ") mm");
 
 
        }
 
        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}

方法

NameDescription备注
AddPropertyExtensionAdds a property extension to this component.  向该组件添加属性扩展。
DeSelectDeselects this component.  取消选择该组件。
EnumBodies3Gets the bodies in the component in a multibody part.  获取多实体零件中组件中的实体。
EnumRelatedBodiesCreates an enumerated list of bodies.  创建实体的枚举列表。
EnumSectionedBodiesGets the sectioned bodies seen in the specified view and returns them in an enumerated list.  获取在指定视图中看到的分段实体,并在枚举列表中返回它们。
FeatureByNameGets the specified feature for this component.  获取此组件的指定名称的特征。
FindAttributeFinds an attribute on a component.  查找组件上的属性。
FirstFeatureGets the first feature in this component.  获取此组件中的第一个功能。
GetBodies3Gets the bodies in this component.  获取此组件中的主体。
GetBodyGets the body that belongs to this instance of this component.  获取属于此组件的此实例的主体。
GetBoxGets the bounding box for component.  获取组件的边界框。
GetChildrenGets all of the children components of this component.  获取此组件的所有子组件。
GetConstrainedStatusGets the constrained status of this component.  获取此组件的约束状态。
GetCorrespondingGets the corresponding object in the context of the assembly for a specific instance of the component.  获取组件的特定实例的程序集上下文中的相应对象。
GetCorrespondingEntityGets the entity that corresponds with the Dispatch pointer in the context of the component.  获取与组件上下文中的 Dispatch 指针对应的实体。
GetDecalsGets the decals applied to this component.  获取应用于此组件的贴花。
GetDecalsCountGets the number of decals applied to this component.  获取应用于此组件的贴花数量。
GetDrawingComponentGets the drawing component for this component.  获取此组件的绘图组件。
GetExcludeFromBOM2Gets whether this component is excluded from the bills of materials (BOMs) in the specified configurations.  获取此组件是否从指定配置的物料清单 (BOM) 中排除。
GetHiddenUnloadedChildrenCountGets the number of hidden children components of this component that were not loaded when an assembly was opened selectively.  获取在有选择地打开程序集时未加载的此组件的隐藏子组件的数量。
GetIDGets the component ID for this component.  获取此组件的组件 ID。
GetImportedPathGets the full path name of the model imported for this component.  获取为此组件导入的模型的完整路径名。
GetMaterialIdNameGets the material name for this component.  获取此组件的材料名称。
GetMaterialPropertyValues2Gets the material properties for this component.  获取此组件的材料属性。
GetMaterialUserNameGets the user-visible name of the material for this component.  获取此组件的材料的用户可见名称。
GetMatesGets the mates for this component.  获取此零部件的配合。
GetModelDoc2Gets the model document for this component.  获取此组件的模型文档。
GetModelMaterialPropertyValuesGets the material properties of this lightweight component in the specified configuration.  获取此轻量级组件在指定配置中的材料属性。
GetModelTextureGets the texture applied to this lightweight component in the specified configuration.  获取在指定配置中应用于此轻量级组件的纹理。
GetParentGets the parent component.  获取父组件。
GetPathNameGets the full path name for this component.  获取此组件的完整路径名。
GetPropertyExtensionGets the property extension on this component.  获取此组件的属性扩展。
GetReferencedDisplayStatesGets the display states of this component that are referenced by the specified assembly display state(s).  获取由指定程序集显示状态引用的此组件的显示状态。
GetRenderMaterials2Gets the appearances applied to this component in the specified display states.  获取在指定显示状态下应用于此组件的外观。
GetRenderMaterialsCount2Gets the number of appearances applied to this component in the specified display states.  获取在指定显示状态下应用于此组件的外观数量。
GetSectionedBodiesGets the sectioned bodies in the specified section view.  获取指定剖视图中的剖切实体。
GetSelectByIDStringGets the name of the component for possible use with IModelDocExtension::SelectByID2, for selectively opening a document using ISldWorks::OpenDoc7 and IDocumentSpecification, etc.  获取可能与 IModelDocExtension::SelectByID2 一起使用的组件的名称,用于使用 ISldWorks::OpenDoc7 和 IDocumentSpecification 等选择性地打开文档。
GetSmartComponentDataGets the features, components, and feature references of a Smart Component.  获取智能组件的特征、组件和特征参考。
GetSpecificTransformGet the collapsed or exploded transform of a component when the assembly is exploded.  装配爆炸时获取组件的折叠或爆炸变换。
GetSuppression2Gets the suppression state of this component.  获取此组件的压缩状态。
GetTessNormsGets the normal vector for each of the triangles, which make up the shaded picture tessellation for the component.  获取每个三角形的法向量,这些三角形构成了组件的阴影图片细分。
GetTessTrianglesGets the triangles that make up the shaded picture tessellation for this component.  获取构成此组件的阴影图片细分的三角形。
GetTessTriStripEdgesGets the edge IDs for the triangle strips.  获取三角形条带的边 ID。
GetTessTriStripNormsGets the normal vector for each of the triangles, which make up the shaded picture tessellation for this component.  获取每个三角形的法向量,这些三角形构成此组件的阴影图片细分。
GetTessTriStripsGets the vertices that make up the shaded picture tessellation for this component.  获取构成此组件的着色图片细分的顶点。
GetTextureGets the texture applied to this component in the specified configuration.  获取在指定配置中应用于此组件的纹理。
GetTotalTransformCombines the original transform of this component with the presentation transform of this component.  将此组件的原始转换与此组件的表示转换相结合。
GetUnloadedComponentNamesGets the component's unloaded children components' path names, referenced configuration names, reasons why they are unloaded, document types, and names.  获取组件已卸载的子组件的路径名称、引用的配置名称、卸载原因、文档类型和名称。
GetVisibilityGets the visibility state for this component.  获取此组件的可见性状态。
GetVisibilityInAsmDisplayStatesGets the visibilities of this component in the specified assembly display state(s).  获取此组件在指定装配显示状态下的可见性。
HasMaterialPropertyValuesGets whether this component has an appearance.  获取此组件是否具有外观。
HasUnloadedComponentsGets whether this component has hidden or suppressed unloaded children components.  获取此组件是否隐藏或抑制了卸载的子组件。
IFindAttributeFinds an attribute on a component.  查找组件上的属性。
IGetBodyGets the body that belongs to this instance of this component.  获取属于此组件的此实例的主体。
IGetBoxGets the bounding box for component.  获取组件的边界框。
IGetChildrenGets all of the children components of this component.  获取此组件的所有子组件。
IGetChildrenCountGets the number of children components for this component.  获取此组件的子组件数。
IGetCorrespondingEntityGets the entity that corresponds with the Dispatch pointer in the context of the component.  获取与组件上下文中的 Dispatch 指针对应的实体。
IGetDecalsGets the decals applied to this component.  获取应用于此组件的贴花。
IGetMaterialPropertyValues2Gets the material properties for this component.  获取此组件的材料属性。
IGetMaterialPropertyValuesForFaceGets the color of the specified face.  获取指定面的颜色。
IGetModelMaterialPropertyValuesGets the material properties of this lightweight component in the specified configuration.  获取此轻量级组件在指定配置中的材料属性。
IGetTemporaryBodyIDGets the current body tag ID, which is not a permanent ID.  获取当前正文标签 ID,该 ID 不是永久 ID。
IGetTessNormsGets the normal vector for each of the triangles, which make up the shaded picture tessellation for the component.  获取每个三角形的法向量,这些三角形构成了组件的阴影图片细分。
IGetTessTriangleCountGets the number of triangles that make up the shaded picture tessellation for this component.  获取构成此组件的着色图片细分的三角形数。
IGetTessTrianglesGets the triangles that make up the shaded picture tessellation for this component.  获取构成此组件的阴影图片细分的三角形。
IGetTessTriStripEdgesGets the edge IDs for the triangle strips.  获取三角形条带的边 ID。
IGetTessTriStripEdgeSizeGets the number of tessellation triangle edges.  获取细分三角形边的数量。
IGetTessTriStripNormsGets the normal vector for each of the triangles, which make up the shaded picture tessellation for this component.  获取每个三角形的法向量,这些三角形构成此组件的阴影图片细分。
IGetTessTriStripsGets the vertices that make up the shaded picture tessellation for this component.  获取构成此组件的着色图片细分的顶点。
IGetTessTriStripSizeGets the array size of floats required to contain the data returned when calling IComponent2::IGetTessTriStrips.  获取调用 IComponent2::IGetTessTriStrips 时包含返回数据所需的浮点数组大小。
IGetVisibilityGets the visibility state for this component.  获取此组件的可见性状态。
IListExternalFileReferences2Gets the names and statuses of the external references on the component.  获取组件上外部引用的名称和状态。
IRemoveMaterialProperty2Removes material property values from the component.  从组件中删除材料属性值。
IsDisplayDataOutOfDateGets the status of the display data for this component.  获取此组件的显示数据的状态。
IsEnvelopeGets whether this component is an envelope.  获取此组件是否为封套。
ISetMaterialPropertyValues2Sets the material properties for this component.  设置此组件的材料属性。
ISetVisibilitySets the visibility state for this component.  设置此组件的可见性状态。
IsFixedGets whether the component is fixed or floating.  获取组件是固定的还是浮动的。
IsHiddenGets whether this component is hidden or suppressed.  获取此组件是隐藏还是压缩。
IsLoadedGets whether a component is loaded.  获取组件是否已加载。
IsMirroredGets whether this component is mirrored.  获取此组件是否被镜像。
IsPatternInstanceGets whether the component is a member of a pattern instance.  获取组件是否是模式实例的成员。
IsRootGets whether this component is the root component.  获取此组件是否为根组件。
IsSmartComponentGets whether this component is a Smart Component.  获取此组件是否为智能组件。
IsSuppressedGets whether this component is suppressed.  获取此组件是否被压缩。
ListExternalFileReferences2Gets the names and statuses of the external file references on the component.  获取组件上外部文件引用的名称和状态。
ListExternalFileReferencesCountGets the number of external references on the component.  获取组件上的外部引用数。
MakeVirtual2Makes this component and optionally its child components virtual by saving them in the current assembly.  通过将其保存在当前程序集中,使该组件及其子组件(可选)成为虚拟组件。
RemoveMaterialProperty2Removes the appearance from the component.  从组件中删除外观。
RemovePresentationTransformRemoves the presentation transform from this component.  从此组件中删除表示转换。
RemoveTextureRemoves the texture from this component in the specified configuration.  在指定的配置中从此组件中移除纹理。
RemoveTextureByDisplayStateRemoves the texture applied to this component in the specified display state.  移除在指定显示状态下应用于此组件的纹理。
ResetPropertyExtensionClears all of the values stored in the property extension.  清除存储在属性扩展中的所有值。
SaveVirtualComponentSaves a virtual component to an external file.  将虚拟零部件保存到外部文件。
Select4Selects the component.  选择组件。
SetCosmosWorksMaterialAssigns the material to use during analysis to this component.  将分析期间要使用的材料分配给该组件。
SetExcludeFromBOM2Sets whether to exclude this component from the bills of materials (BOMs) in the specified configurations.  设置是否从指定配置的物料清单 (BOM) 中排除此组件。
SetMaterialIdNameSets the material name for this component.  设置此组件的材料名称。
SetMaterialPropertyValues2Sets the material properties for this component.  设置此组件的材料属性。
SetMaterialUserNameSets the material user name for this component.  设置此组件的材质用户名。
SetReferencedDisplayStatesSets the specified display state of this component to be referenced by the specified assembly display state(s).  设置此组件的指定显示状态以被指定的程序集显示状态引用。
SetSmartComponentDataSets the features, components, and feature references of a Smart Component.  设置智能零部件的特征、零部件和特征参考。
SetSuppression2Sets the suppression state of this component.  设置该组件的压缩状态。
SetTextureApplies texture to this component in the specified configuration.  将纹理应用于指定配置中的此组件。
SetTextureByDisplayStateSets the texture applied to this component in the specified display state.  在指定的显示状态下设置应用于此组件的纹理。
SetTransformAndSolve3Sets the transform and solves for the mates for this component.  设置变换并求解此零部件的配合。
SetVisibilitySets the visibility state for this component.  设置此组件的可见性状态。
SetVisibilityInAsmDisplayStatesSets the visibility of this component in the specified assembly display state(s).  设置此零部件在指定装配显示状态中的可见性。
UpdateExternalFileReferencesUpdates the external file references of this model.  更新此模型的外部文件参考。

System.object GetBodies3( System.int BodyType,out System.object BodiesInfo)

//This example shows how to get the number of normal and user bodies in the components in //an assembly. 

//-----------------------------------------------------
// Preconditions:
// 1. Verify that the specified assembly document
//    to open exists.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Gets and prints each component's name, number of
//    solid bodies, body names, and body types
//    to the Immediate window.
// 2. Right-click filterholder<1> in the FeatureManager
//    design tree and click the Open Part button.
//    Notice that there are no screw holes in the part.
// 3. Close the part and examine the filterholder<1>
//    component, which is the orange, flat, circular
//    component located on the front of the assembly
//    in the graphics area. There are screw
//    holes in the component.
// 4. Examine the filterholder<1>'s information in the
//    Immediate window. Because the component was
//    modified in the assembly, its body is identified
//    as a user body.
//
// NOTE: Because this assembly document is used by
// elsewhere, do not save changes.
//-----------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Diagnostics;
using System.Collections;
namespace GetBodies3Component2CSharp.csproj
{
    partial class SolidWorksMacro
    {
        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            AssemblyDoc swAssembly = default(AssemblyDoc);
            object[] vComponents = null;
            Component2 oneComponent = default(Component2);
            Body2 swBody = default(Body2);
            object[] vBodies = null;
            object vBodyInfo;
            int[] BodiesInfo = null;
            int BodyType = 0;
            int errors = 0;
            int warnings = 0;
            int i = 0;
            int j = 0;
 
            // Open this assembly  
            swModel = (ModelDoc2)swApp.OpenDoc6("C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\toolbox\\lens_mount.sldasm", (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
            swAssembly = (AssemblyDoc)swModel;
 
            // Get the components in the assembly 
            vComponents = (object[])swAssembly.GetComponents(true);
            for (i = 0; i <= vComponents.Length - 1; i++)
            {
                oneComponent = (Component2)vComponents[i];
                Debug.Print(" ");
                Debug.Print("Component name: " + oneComponent.Name2);
 
                // Get the solid bodies in the component 
                vBodies = (object[])oneComponent.GetBodies3((int)swBodyType_e.swSolidBody, out (object)vBodyInfo);
                BodiesInfo = (int[])vBodyInfo;
                Debug.Print(" Number of solid bodies: " + (vBodies.Length + 1));
                for (j = 0; j <= vBodies.Length - 1; j++)
                {
                    Debug.Print(" Body number: " + (j + 1));
                    swBody = (Body2)vBodies[j];
                    Debug.Print(" Body name: " + swBody.Name);
 
                    // Print the type of body 
                    BodyType = (int)BodiesInfo[j];
                    switch (BodyType)
                    {
                        case 0:
                            Debug.Print(" Body type: user");
                            break;
                        case 1:
                            Debug.Print(" Body type: normal");
                            break;
                    }
                }
            }
        }
 
        /// <summary> 
        /// The SldWorks swApp variable is pre-assigned for you. 
        /// </summary> 
        public SldWorks swApp;
 
    }
}

System.object GetBody()

//This example shows how to display a temporary body.

//-------------------------------------------------
// Preconditions:
// 1. Verify that the specified assembly document to
//    open exists.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Opens the specified assembly document.
// 2. Selects a component for the temporary body.
// 3. Displays the temporary body.
// 4. Examine the graphics area and 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 Part = default(ModelDoc2);
            Body2 Body = default(Body2);
            Body2 BodyCopy = default(Body2);
            bool status = false;
            Component2 Component = default(Component2);
            MathUtility MathUtility = default(MathUtility);
            MathTransform MathXform = default(MathTransform);
            SelectionMgr SelMgr = default(SelectionMgr);
            double[] Xform = new double[16];
            object vXform = null;
            int retval = 0;
            string fileName = null;
            int errors = 0;
            int warnings = 0;
 
            Xform[0] = 1.0;
            Xform[1] = 0.0;
            Xform[2] = 0.0;
            Xform[3] = 0.0;
            Xform[4] = 1.0;
            Xform[5] = 0.0;
            Xform[6] = 0.0;
            Xform[7] = 0.0;
            Xform[8] = 1.0;
            Xform[9] = 0.15;
            Xform[10] = 0.0;
            Xform[11] = 0.0;
            Xform[12] = 1.0;
            Xform[13] = 0.0;
            Xform[14] = 0.0;
            Xform[15] = 0.0;
            vXform = Xform;
 
            MathUtility = (MathUtility)swApp.GetMathUtility();
            MathXform = (MathTransform)MathUtility.CreateTransform(vXform);
 
            //Open assembly
            fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\assem1.sldasm";
            Part = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
 
            //Select component and create temporary body
            status = Part.Extension.SelectByID2("TestPart1-1@assem1", "COMPONENT", 0, 0, 0, false, 0, null, 0);
            SelMgr = (SelectionMgr)Part.SelectionManager;
            Component = (Component2)SelMgr.GetSelectedObjectsComponent3(1, 0);
            Body = (Body2)Component.GetBody();
            BodyCopy = (Body2)Body.Copy();
            BodyCopy.ApplyTransform(MathXform);
 
            //Display temporary body
            retval = BodyCopy.Display3(Component, 255, (int)swTempBodySelectOptions_e.swTempBodySelectable);
            Debug.Print("Temporary body displayed (0 = success)? " + retval);
 
            Part.ViewZoomtofit2();
 
        }
 
        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}

System.object GetCorresponding( System.object InputObject)

//This example shows how to get the corresponding sketch contour, sketch segments, and //annotation for a component in the context of the assembly.

//------------------------------------------------------------------
// Preconditions:
// 1. Verify that:
//    * specified part and assembly templates
//    * C:\test
//    exist.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Opens a new part and creates a sketch containing
//    a sketch arc, sketch line, and a note.
// 2. Saves the part as C:\test\part1.sldprt.
// 3. Makes an assembly using the part document and saves
//    the assembly as C:\test\assem1.sldasm.
// 4. Activates the part.
//    a. Gets the persistent reference IDs of the sketch segments
//       in the sketch contour.
//    b. Gets the object ID of the note annotation.
// 5. Activates the assembly.
//    a. Gets the persistent reference IDs of the sketch
//       segments in the sketch contour in the context 
//       of the assembly.
//    b. Gets the object ID of the note annotation in the context 
//       of the assembly.
// 6. Examine the Immediate window.
//------------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
 
namespace Macro1CSharp.csproj
{
    public partial class SolidWorksMacro
    { 
 
        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            AssemblyDoc swAssembly = default(AssemblyDoc);
            Component2 swComponent = default(Component2);
            SketchManager swSketchManager = default(SketchManager);
            SketchSegment swSketchSegment = default(SketchSegment);
            Note swNote = default(Note);
            Annotation swAnnotation = default(Annotation);
            TextFormat swTextFormat = default(TextFormat);
            ModelDocExtension swModelDocExt = default(ModelDocExtension);
            Feature swFeature = default(Feature);
            Sketch swSketch = default(Sketch);
            SketchContour swSketchContour = null;
            SelectionMgr swSelectionMgr = default(SelectionMgr);
            object swObject = null;
            object[] sketchSegments = null;
            object[] sketchContours = null;
            int nbrSketchContours = 0;
            int nbrSketchSegments = 0;
            int[] sketchSegmentIDs = null;
            int sketchSegmentType = 0;
            int annotationID = 0;
            int annotationType = 0;
            bool status = false;
            int errors = 0;
            int warnings = 0;
            int i = 0;
            int j = 0;
 
            //Create sketch containing a sketch arc,
            //sketch line, and annotation
            swModel = (ModelDoc2)swApp.NewDocument("C:\\ProgramData\\SolidWorks\\SolidWorks 2016\\templates\\Part.prtdot", 0, 0, 0);
            swSketchManager = (SketchManager)swModel.SketchManager;
            swSketchSegment = (SketchSegment)swSketchManager.CreateArc(-0.0756, 0.0, 0.0, -0.020568, 0.0, 0.0, -0.130614, 0.001423, 0.0, 1);
            swSketchSegment = (SketchSegment)swSketchManager.CreateLine(-0.130614, 0.001423, 0.0, -0.0756, -0.047042, 0.0);
            swNote = (Note)swModel.InsertNote("This is a sketch segment");
            if ((swNote != null))
            {
                swNote.LockPosition = false;
                swNote.Angle = 0;
                status = swNote.SetBalloon(0, 0);
                swAnnotation = (Annotation)swNote.GetAnnotation();
                if ((swAnnotation != null))
                {
                    errors = swAnnotation.SetLeader3((int)swLeaderStyle_e.swUNDERLINED, 0, true, false, false, false);
                    status = swAnnotation.SetPosition2(-0.002501468059071, 0.0826874163970699, 0);
                    swTextFormat = null;
                    status = swAnnotation.SetTextFormat(0, true, swTextFormat);
                }
            }
            swModel.ClearSelection2(true);
            swModel.WindowRedraw();
            swSketchManager.InsertSketch(true);
            swModelDocExt = swModel.Extension;
            status = swModelDocExt.SaveAs("C:\\test\\part1.sldprt", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
 
            //Save part as assembly
            swAssembly = (AssemblyDoc)swApp.NewDocument("C:\\ProgramData\\SolidWorks\\SolidWorks 2016\\templates\\Assembly.asmdot", 0, 0, 0);
            swComponent = (Component2)swAssembly.AddComponent5("C:\\test\\part1.SLDPRT", (int)swAddComponentConfigOptions_e.swAddComponentConfigOptions_CurrentSelectedConfig, "", false, "", -1.60609059776107E-05, 0, 8.47512097834624E-06);
            swModel = (ModelDoc2)swAssembly;
            swModelDocExt = (ModelDocExtension)swModel.Extension;
            status = swModelDocExt.SaveAs("C:\\test\\Assem1.SLDASM", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
 
            //Get persistent reference IDs of sketch segments in sketch contour in part
            swModel = (ModelDoc2)swApp.ActivateDoc3("Part1.SLDPRT", false, (int)swRebuildOnActivation_e.swRebuildActiveDoc, ref errors);
            swModelDocExt = (ModelDocExtension)swModel.Extension;
            status = swModelDocExt.SelectByID2("Sketch1", "SKETCH", 0.0, 0.0, 0.0, false, 0, null, 0);
            swSelectionMgr = (SelectionMgr)swModel.SelectionManager;
            swFeature = (Feature)swSelectionMgr.GetSelectedObject6(1, -1);
            swSketch = (Sketch)swFeature.GetSpecificFeature2();
            Debug.Print(swModel.GetPathName());
            Debug.Print("");
            if ((swSketch != null))
            {
                sketchContours = (object[])swSketch.GetSketchContours();
                nbrSketchContours = sketchContours.Length;
                Debug.Print("  Number of sketch contours in " + swFeature.Name + " = " + nbrSketchContours);
                for (i = 0; i < sketchContours.Length; i++)
                {
                    swSketchContour = (SketchContour)sketchContours[i];
                    if ((swSketchContour != null))
                    {
                        status = swSketchContour.Select2(false, null);
                    }
                    sketchSegments = (object[])swSketchContour.GetSketchSegments();
                    nbrSketchSegments = sketchSegments.Length;
                    for (j = 0; j < sketchSegments.Length; j++)
                    {
                        swSketchSegment = (SketchSegment)sketchSegments[j];
                        if ((swSketchSegment != null))
                        {
                            sketchSegmentIDs = (int[])swSketchSegment.GetID();
                            sketchSegmentType = swSketchSegment.GetType();
                            Debug.Print("  Persistent IDs = [" + sketchSegmentIDs[0] + ", " + sketchSegmentIDs[1] + "] and type = " + sketchSegmentType + " (0 = line; 1 = arc)");
                        }
                    }
                }
            }
 
            //Get object ID of note annotation in part
            status = swModelDocExt.SelectByID2("DetailItem1@Annotations", "NOTE", -0.00650517330771608, 0.0568327787544409, -0.035178659814812, false, 0, null, 0);
            swNote = (Note)swSelectionMgr.GetSelectedObject6(1, -1);
            swAnnotation = (Annotation)swNote.GetAnnotation();
            annotationType = swAnnotation.GetType();
            annotationID = swModelDocExt.GetObjectId(swAnnotation);
            Debug.Print("");
            Debug.Print("  Annotation ID = " + annotationID + " and type = " + annotationType + " (6 = note)");
 
            //Activate the assembly
            swModel = (ModelDoc2)swApp.ActivateDoc3("Assem1.SLDASM", false, (int)swRebuildOnActivation_e.swRebuildActiveDoc, ref errors);
            swModelDocExt = (ModelDocExtension)swModel.Extension;
            status = swModelDocExt.SelectByID2("Part1-1@Assem1", "COMPONENT", 0, 0, 0, false, 0, null, 0);
            swSelectionMgr = (SelectionMgr)swModel.SelectionManager;
            swComponent = (Component2)swSelectionMgr.GetSelectedObject6(1, -1);
            Debug.Print("");
            Debug.Print(swModel.GetPathName());
            Debug.Print("");
 
            //Get corresponding sketch contour and sketch segments
            //and their persistent reference IDs in component
            swObject = (object)swComponent.GetCorresponding(swSketchContour);
            swSketchContour = null;
            swSketchContour = (SketchContour)swObject;
            if ((swSketchContour != null))
            {
                status = swSketchContour.Select2(false, null);
            }
            sketchSegments = (object[])swSketchContour.GetSketchSegments();
            Debug.Print("  Number of sketch contours in " + swFeature.Name + " = " + nbrSketchContours);
            nbrSketchSegments = sketchSegments.Length;
            for (j = 0; j < sketchSegments.Length; j++)
            {
                swSketchSegment = (SketchSegment)sketchSegments[j];
                if ((swSketchSegment != null))
                {
                    sketchSegmentIDs = (int[])swSketchSegment.GetID();
                    sketchSegmentType = swSketchSegment.GetType();
                    Debug.Print("  Persistent IDs = [" + sketchSegmentIDs[0] + ", " + sketchSegmentIDs[1] + "] and type = " + sketchSegmentType + " (0 = line; 1 = arc)");
                }
            }
 
            //Get object ID of corresponding note annotation in component
            swObject = (object)swComponent.GetCorresponding(swNote);
            swNote = null;
            swNote = (Note)swObject;
            if ((swNote != null))
            {
                swAnnotation = (Annotation)swNote.GetAnnotation();
                annotationType = swAnnotation.GetType();
                annotationID = swModelDocExt.GetObjectId(swAnnotation);
                Debug.Print("");
                Debug.Print("  Annotation ID = " + annotationID + " and type = " + annotationType + " (6 = note)");
            }
        }
 
        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}

System.int GetID()

//This example shows how to get the component IDs of the components in an assembly and //subassemblies.

//--------------------------------------------------------------------------
// Preconditions:
// 1. Open an assembly document containing nested subassemblies.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Traverses the assembly and subassemblies.
// 2. Gets the name and component ID of each component in the assembly and
//    subassemblies.
// 3. Examine the Immediate window.
//---------------------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
 
namespace Macro1CSharp.csproj
{
    public partial class SolidWorksMacro
    {
 
        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            ConfigurationManager swConfMgr = default(ConfigurationManager);
            Configuration swConf = default(Configuration);
            Component2 swRootComp = default(Component2);
 
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swConfMgr = (ConfigurationManager)swModel.ConfigurationManager;
            swConf = (Configuration)swConfMgr.ActiveConfiguration;
            swRootComp = (Component2)swConf.GetRootComponent3(true);
            Debug.Print("File = " + swModel.GetPathName());
            if (swModel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY)
            {
                TraverseComponent(swRootComp, 1);
            }
 
        }
 
        public void TraverseComponent(Component2 swComp, int nLevel)
        {
            object[] vChildComp = null;
            Component2 swChildComp = default(Component2);
            string sPadStr = "";
            int i = 0;
 
            for (i = 0; i <= nLevel - 1; i++)
            {
                sPadStr = sPadStr + "  ";
            }
            vChildComp = (object[])swComp.GetChildren();
            for (i = 0; i <= vChildComp.Length - 1; i++)
            {
                swChildComp = (Component2)vChildComp[i];
                Debug.Print(sPadStr + "Component name: " + swChildComp.Name2 + ", Component ID: " + swChildComp.GetID());
                TraverseComponent(swChildComp, nLevel + 1);
            }
        }
 
        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}

System.string GetPathName()

//This example shows how to keep SOLIDWORKS invisible while activating SOLIDWORKS //documents, including assembly component files, and saving those documents as PDF files. 

//------------------------------------------------------
// Preconditions:
// 1. Verify that the specified assembly file exists.
// 2. Verify that c:\temp exists.
// 3. Open the Immediate window.
//
// Postconditions:
// 1. Saves the specified assembly file and its
//    component files as PDF files to the c:\temp.
// 2. Examine the Immediate window and c:\temp.
//--------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Diagnostics;
using System.IO;

namespace Macro1CSharp.csproj
{
    public 
 partial class SolidWorksMacro
    {
        public 
 ModelDoc2 swModel;
        public ModelDocExtension swExtension;

        public void Main()
        {
            Frame pFrame;
            string Document = null;
            string Output = null;
            try
            {
                // Allow SOLIDWORKS to run in the background
                // and be invisible
                swApp.UserControl = false;


                // If the following property is true, then the 
                // SOLIDWORKS frame will be visible on a call to 
                // ISldWorks::ActivateDoc2; so, set it to false 
                swApp.Visible = false;


                // Keep SOLIDWORKS frame invisible when 
                // ISldWorks::ActivateDoc2 is called 
                pFrame = (Frame)swApp.Frame();
                pFrame.KeepInvisible = true;


                Document = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\advdrawings\\blade shaft.sldasm";
                Output = "c:\\temp\\";
                Debug.Print("--- Save files as PDF ---");
                SaveToPDF(Document, Output);
                swApp.CloseAllDocuments(true);
                Debug.Print("--- Done ---");


                // Show SOLIDWORKS frame and SOLIDWORKS 
                pFrame.KeepInvisible = false;
                swApp.Visible = true;
            }
            catch 
            {
                Debug.Print("Execution failed.");
            }
        }


        private void SaveToPDF(string docFileName, string outputpath)
        {
            AssemblyDoc swAssembly = default(AssemblyDoc);

            int doctype = 0;
            int errors = 0;
            int warnings = 0;
            string modelpath = "";
            string modelFileName = "";
            string convFileName = "";
            bool Success = false;
            object[] vComponents = null;
            long i = 0;


            // Determine the type of SOLIDWORKS file based on 
            // its filename extension 
            string extension = "";
            extension = Path.GetExtension(docFileName);
            if (extension == ".sldprt")
            {
                doctype = (int)swDocumentTypes_e.swDocPART;
            }
            else if (extension == ".SLDPRT")
            {
                doctype = (int)swDocumentTypes_e.swDocPART;
            }

            else if (extension == ".sldasm")
            {
                doctype = (int)swDocumentTypes_e.swDocASSEMBLY;
            }
            else if (extension == ".SDLASM")
            {
                doctype = (int)swDocumentTypes_e.swDocASSEMBLY;
            }
            else if (extension == ".slddrw")
            {
                doctype = (int)swDocumentTypes_e.swDocDRAWING;
            }
            else if (extension == ".SLDDRW")
            {
                doctype = (int)swDocumentTypes_e.swDocDRAWING;
            }
            else
            {
                doctype = (int)swDocumentTypes_e.swDocNONE;
            }


            //Open document
            swModel = (ModelDoc2)swApp.OpenDoc6(docFileName, doctype, (int)swOpenDocOptions_e.swOpenDocOptions_Silent | (int)swOpenDocOptions_e.swOpenDocOptions_ReadOnly, "", ref errors, ref warnings);
            if (swModel == null)
            {
                Debug.Print("Failed to open document " + modelpath + ". Errors: " + errors);
            }
            // Activate the document, which should remain invisible 
            // due to earlier call to IFrame::KeepInvisible 
            swModel = (ModelDoc2)swApp.ActivateDoc2(docFileName, true, ref errors);


            // Build destination filename 
            modelpath = swModel.GetPathName();
            modelFileName = Path.GetFileNameWithoutExtension(modelpath);
            convFileName = outputpath + modelFileName + ".pdf";
            swExtension = (ModelDocExtension)swModel.Extension;


            // Save document as PDF
            Success = swExtension.SaveAs(convFileName, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors,
ref warnings);
            if (Success)
            {
                Debug.Print("Document, " + modelpath + ", saved as " + convFileName + ". ");
            }
            else
            {
                Debug.Print("Document not saved: ");
                Debug.Print(" Errors: " + errors + modelpath + " as " + convFileName + ". ");
            }
            // Process all components 
            if (doctype == (int)swDocumentTypes_e.swDocASSEMBLY)
            {
                swAssembly = (AssemblyDoc)swModel;
                vComponents = (object[])swAssembly.GetComponents(true);
                for (i = 0; i < vComponents.Length; i++)
                {
                    Component2 swComponent = default(Component2);
                    swComponent = (Component2)vComponents[i];
                    SaveToPDF(swComponent.GetPathName(), outputpath);
                }
            }
        }


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

System.object GetSpecificTransform( System.bool IgnoreExplode)

//This example shows how to get the collapsed transform of a component in an exploded view.

//----------------------------------------------------------------------------
// Preconditions:
// 1. Open public_documents\samples\tutorial\pdmworks\speaker.sldasm.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Gets the name of the active configuration.
// 2. Creates five exploded views for the active configuration.
// 3. Gets the name of each exploded view for the active configuration
//    and shows each exploded view.
// 4. Gets the name of the exploded view shown in the model.
// 5. Selects a component and get its collapsed transform.
// 6. 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);
            ModelDocExtension swModelDocExt = default(ModelDocExtension);
            AssemblyDoc swAssembly = default(AssemblyDoc);
            ConfigurationManager swConfigMgr = default(ConfigurationManager);
            Configuration swConfig = default(Configuration);
            Component2 swComponent = default(Component2);
            SelectionMgr swSelectionMgr = default(SelectionMgr);
            MathTransform swTransform = default(MathTransform);
            string activeConfigName = null;
            string[] viewNames = null;
            string viewName = null;
            int i = 0;
            double[] transformArrayData = null;
 
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swAssembly = (AssemblyDoc)swModel;
 
            //Get active configuration name
            swConfigMgr = (ConfigurationManager)swModel.ConfigurationManager;
            swConfig = (Configuration)swConfigMgr.ActiveConfiguration;
            activeConfigName = swConfig.Name;
 
            //Create five exploded views in the active configuration
            for (i = 0; i <= 4; i++)
            {
                swAssembly.CreateExplodedView();
            }
 
            //Get the name of each exploded view in the active configuration
            //and show each exploded view
            viewNames = (string[])swAssembly.GetExplodedViewNames2(activeConfigName);
            for (i = 0; i < viewNames.Length; i++)
            {
                viewName = viewNames[i];
                swAssembly.ShowExploded2(true, viewName);
            }
 
            //Get the name of exploded view shown in model
            viewName = "";
            swModelDocExt = swModel.Extension;
            swModelDocExt.IsExploded(out viewName);
            Debug.Print("Name of exploded view shown in model: " + viewName);
 
            //Select a component and get its collapsed transform 
            swModelDocExt.SelectByID2("speaker_frame-1@speaker", "COMPONENT", 0, 0, 0, false, 0, null, 0);
            swSelectionMgr = (SelectionMgr)swModel.SelectionManager;
            swComponent = (Component2)swSelectionMgr.GetSelectedObjectsComponent4(1, -1);
            Debug.Print("  Name of component whose collapsed transform to get in the exploded view: " + swComponent.Name2);
            swTransform = (MathTransform)swComponent.GetSpecificTransform(true);
            transformArrayData = (double[])swTransform.ArrayData;
            Debug.Print("    Transform:");
            Debug.Print("      Rotate     = (" + transformArrayData[0].ToString("###0.0#####") + ", " + transformArrayData[1].ToString("###0.0#####") + ", " + transformArrayData[2].ToString("###0.0#####") + ")");
            Debug.Print("                 = (" + transformArrayData[3].ToString("###0.0#####") + " " + transformArrayData[4].ToString("###0.0#####") + " " + transformArrayData[5].ToString("###0.0#####") + ")");
            Debug.Print("                 = (" + transformArrayData[6].ToString("###0.0#####") + " " + transformArrayData[7].ToString("###0.0#####") + " " + transformArrayData[8].ToString("###0.0#####") + ")");
            Debug.Print("      Translate  = (" + transformArrayData[9].ToString("###0.0#####") + " " + transformArrayData[10].ToString("###0.0#####") + " " + transformArrayData[11].ToString("###0.0#####") + ")");
 
        }
 
        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}

System.bool IsLoaded()

//This example gets whether the components in an assembly document are loaded. 

//---------------------------------------
// Preconditions: 
// 1. Verify that the specified assembly document exists. 
// 2. Open the Immediate window.
// 
// Postconditions: 
// 1. Loads the Magnet-1 component. 
// 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 IsLoadedComponent2CSharp.csproj
{
    public partial class SolidWorksMacro
    {
        public void Main()
        {
        ModelDoc2 swModel; 
        DocumentSpecification swDocSpecification; 
        string[] sComponents = new string[1]; 
        object[] Components; 
        Component2 swComponent = default(Component2);
        string sName; 
        AssemblyDoc swAssembly; 
        int longstatus; 
        int longwarnings; 
        int i; 
        ConfigurationManager swConfigMgr;
        Configuration swConfig;        

        // Selectively open speaker.sldasm
        // Load only Magnet-1 
        swDocSpecification = (DocumentSpecification)swApp.GetOpenDocSpec("C:\\Users\\Public\\Documents\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\pdmworks\\speaker.sldasm"); 
        sComponents[0] = "Magnet-1@speaker"; 
        Components = (object[])sComponents; 
        swDocSpecification.ComponentList = Components; 
        swDocSpecification.Selective = true; 
        sName = swDocSpecification.FileName; 
        swDocSpecification.DocumentType = (int)swDocumentTypes_e.swDocASSEMBLY; 
        swDocSpecification.DisplayState = "Default_Display State-1"; 
        swDocSpecification.UseLightWeightDefault = true; 
        swDocSpecification.LightWeight = true; 
        swDocSpecification.Silent = true; 
        swDocSpecification.IgnoreHiddenComponents = true; 
        swModel = (ModelDoc2)swApp.OpenDoc7(swDocSpecification); 
        longstatus = swDocSpecification.Error; 
        longwarnings = swDocSpecification.Warning;         

        // Get whether the components in the 
        // assembly document are loaded and suppressed; only 
        // Magnet-1 should be loaded and not suppressed
        swAssembly = (AssemblyDoc)swModel; 
        swConfigMgr = (ConfigurationManager)swModel.ConfigurationManager;
        swConfig = (Configuration)swConfigMgr.ActiveConfiguration;
        Components = (object[])swAssembly.GetComponents(true);
        for (i = 0; i < Components.Length; i++)
        {
            swComponent = (Component2)Components[i];
            if ((swComponent.IsLoaded()))
            {
                Debug.Print("Component: " + swComponent.Name + " is loaded.");
            }
            else
            {
                Debug.Print("Component: " + swComponent.Name + " is not loaded.");
            } 

            Debug.Print ("  Suppressed: " + swConfig.GetComponentSuppressionState(swComponent.Name));
            Debug.Print ("");
        }
        }         

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

System.bool IsSmartComponent()

//This example shows how to activate a Smart Feature in an assembly.

//----------------------------------------------------------------------------
// Preconditions: Open public_documents\samples\tutorial\api\testSmartAssembly.sldasm.
//
// Postconditions:
// 1. Activates Smart Feature holecube-1 and creates two extruded cuts
//    for the selected reference entity.
// 2. Displays Smart Feature holecube-1 in the FeatureManager design tree.
// 3. Creates Smart-Feature1 in component testpart100.
// 4. Expand and examine testpart100 and holecube-1 in the FeatureManager
//    design tree.
//
// NOTE: Because the model is used elsewhere, do not save changes.
//---------------------------------------------------------------------------
	using Microsoft.VisualBasic;
	using System;
	using System.Collections;
	using System.Collections.Generic;
	using System.Data;
	using System.Diagnostics;
	using SolidWorks.Interop.sldworks;
	using SolidWorks.Interop.swconst;
	using System.Runtime.InteropServices;
	namespace ActivateSmartFeature_CSharp.csproj
	{
	    partial class SolidWorksMacro
	    {
	        Component2 comp;
	        object comps;
	        Object[] compsArray;
	        SelectionMgr selMgr;
	        object features;
	        object featuresSelected;
	        Boolean[] featuresSelectedArray;
	        object components;
	        object componentsSelected;
	        Boolean[] componentsSelectedArray;
	        object references;
	        Object[] referenceArray;
	        Face2 face;
	        AssemblyDoc swAss;
	        ModelDoc2 doc;
	        bool boolstatus;
	        int i;
	        int j;
	        public void Main()
	        {
	            swAss = (AssemblyDoc)swApp.ActiveDoc;
	            comps = swAss.GetComponents(true);
	            compsArray = (Object[])comps;
	            doc = (ModelDoc2)swAss;
	            selMgr = (SelectionMgr)doc.SelectionManager;
	            for (i = 0; i <= compsArray.GetUpperBound(0); i++)
	            {
	                comp = (Component2)compsArray[i];
	                if (comp.IsSmartComponent())
	                {
	                    if (comp.GetSmartComponentData(out features, out featuresSelected, out components, out componentsSelected, out references))
	                    {
	                        if ((featuresSelected == null) 
	== false)
	                        {
	                            featuresSelectedArray = (Boolean[])featuresSelected;
	                            for (j = 0; j <= featuresSelectedArray.GetUpperBound(0); j++)
	                            {
	                                if (featuresSelectedArray[j] == false)
	                                {
	                                    featuresSelectedArray[j] = true;
	                                }
	                            }
	                        }
	                        if ((componentsSelected == null) 
	== false)
	                        {
	                            componentsSelectedArray = (Boolean[])componentsSelected;
	                            for (j = 0; j <= componentsSelectedArray.GetUpperBound(0); j++)
	                            {
	                                if (componentsSelectedArray[j] == false)
	                                {
	                                    componentsSelectedArray[j - 1] = true;
	                                }
	                            }
	                        }
	                        boolstatus = doc.Extension.SelectByID2("", "FACE", 
	-0.1054255613309, -0.008376708432593, 0.03086069829328, false, 0, null, 0);
	                        face = (Face2)selMgr.GetSelectedObject6(1, 
	-1);
	                        referenceArray = (Object[])references;
	                        referenceArray[0] = face;
	                        DispatchWrapper[] arrRefsIn = new DispatchWrapper[1];
	                        arrRefsIn[0] = new DispatchWrapper(referenceArray[0]);
	                        boolstatus = comp.SetSmartComponentData(featuresSelected, componentsSelected, (arrRefsIn));
	                    }
	                    Debug.Print(comp.Name);
	                }
	            }
	        }
	        public SldWorks swApp;
	    }
	} 

System.bool Select4( System.bool Append,   SelectData Data,System.bool ShowPopup)

//This example shows how to fire notifications when you:

//are about to rename a component. 
//rename a component. 
//---------------------------------------------------
// Preconditions:
// 1. Verify that these documents exist in public_documents\samples\tutorial\api:
//    * beam_boltconnection.sldasm
//    * beam with holes.sldprt
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Open public_documents\samples\tutorial\api\beam_boltconnection.sldasm.
// 2. Fires pre-notification before appending
//    123 to each assembly component's name.
// 3. Fires notification when appending 123 to
//    each assembly component's name.
// 4. Examine the FeatureManager design tree and 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;
using System.Collections;
 
namespace Macro1CSharp.csproj
{
    public partial class SolidWorksMacro
    {
        public AssemblyDoc swAssy;
 
        public void Main()
        {
 
            ModelDoc2 swModel = default(ModelDoc2);
            ConfigurationManager swConfigMgr = default(ConfigurationManager);
            Configuration swConfig = default(Configuration);
            Component2 swRootComp = default(Component2);
            object[] Children = null;
            Component2 swChild = default(Component2);
            SelectionMgr swSelMgr = default(SelectionMgr);
            SelectData swSelData = default(SelectData);
            int ChildCount = 0;
            string oldName = null;
            string newName = null;
            bool bOldSetting = false;
            bool bRet = false;
            int i = 0;
            Hashtable openAssem = default(Hashtable);
 
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swAssy = (AssemblyDoc)swModel;
 
            // Set up event
            swAssy = (AssemblyDoc)swModel;
            openAssem = new Hashtable();
            AttachEventHandlers();
 
            swConfigMgr = swModel.ConfigurationManager;
            swConfig = swConfigMgr.ActiveConfiguration;
            swRootComp = swConfig.GetRootComponent3(true);
            bOldSetting = swApp.GetUserPreferenceToggle((int)swUserPreferenceToggle_e.swExtRefUpdateCompNames);
            swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swExtRefUpdateCompNames, false);
            Children = (object[])swRootComp.GetChildren();
            ChildCount = Children.Length;
            swSelMgr = (SelectionMgr)swModel.SelectionManager;
            swSelData = (SelectData)swSelMgr.CreateSelectData();
            for (i = 0; i <= ChildCount - 1; i++)
            {
                swChild = (Component2)Children[i];
                // Changing component name requires component to be selected
                bRet = swChild.Select4(false, swSelData, false);
                oldName = swChild.Name2;
                newName = oldName + " 123";
                swChild.Name2 = newName;
            }
            swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swExtRefUpdateCompNames, bOldSetting);
 
 
        }
 
        public void AttachEventHandlers()
        {
            AttachSWEvents();
        }
 
        public void AttachSWEvents()
        {
            swAssy.PreRenameItemNotify += this.swAssy_PreRenameItemNotify;
            swAssy.RenameItemNotify += this.swAssy_RenameItemNotify;
        }
 
        private int swAssy_PreRenameItemNotify(int EntityType, string oldName, string newName)
        {
            Debug.Print("PRE-NOTIFICATION - about to rename component: " + oldName);
            return 0;
        }
        private int swAssy_RenameItemNotify(int EntityType, string oldName, string newName)
        {
            Debug.Print("NOTIFICATION - rename component: " + newName);
            return 0;
        }
 
 
        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值