在此基础上学习
属性
Name | Description | 备注 |
ActiveCommandTab | Gets and sets the active SOLIDWORKS CommandManager tab. | 获取和设置活动的 SOLIDWORKS CommandManager 选项卡。 |
ActiveCommandTabIndex | Gets and sets the index of the active SOLIDWORKS CommandManager tab. | 获取和设置活动 SOLIDWORKS CommandManager 选项卡的索引。 |
AnnotationViewCount | Gets the number of annotation views in this part or assembly document. | 获取此零件或装配体文档中的注释视图数。 |
AnnotationViews | Gets the annotation views in this part or assembly document. | 获取此零件或装配体文档中的注释视图。 |
AppPageSetup | Gets the SOLIDWORKS application page setup interface for this document. | 获取此文档的 SOLIDWORKS 应用程序页面设置界面。 |
CommandTabVisible | Gets and sets the visibility of the specified SOLIDWORKS CommandManager tab. | 获取和设置指定 SOLIDWORKS CommandManager 选项卡的可见性。 |
CustomPropertyBuilderTemplate | Gets or sets the custom property builder template for this part. | 获取或设置此部件的自定义属性生成器模板。 |
CustomPropertyManager | Gets the custom properties for this document or configuration. | 获取此文档或配置的自定义属性。 |
DimXpertManager | Gets the DimXpert schema for this configuration. | 获取此配置的 DimXpert 架构。 |
DisplayMode | Gets and sets the display modes for the specified display state setting. | 获取和设置指定显示状态设置的显示模式。 |
DisplayStateSpecMaterialPropertyValues | Gets and sets the appearance settings for the specified display state setting. | 获取和设置指定显示状态设置的外观设置。 |
Document | Gets the model document. | 获取模型文档。 |
FeatureManagerFilterString | Gets or sets the string in the FeatureManager design tree filter. | 获取或设置 FeatureManager 设计树过滤器中的字符串。 |
FlyoutFeatureTreeVisibility | Gets or sets the state of the flyout FeatureManager design tree. | 获取或设置弹出 FeatureManager 设计树的状态。 |
IncludeMassPropertiesOfHiddenBodies | Gets or sets whether to include the mass properties of hidden components in the assembly. | 获取或设置是否在装配中包含隐藏组件的质量属性。 |
LinkedDisplayState | Gets or sets whether a display state is linked in this part. | 获取或设置此部件中是否链接显示状态。 |
NeedsRebuild2 | Gets whether the model document needs to be rebuilt. | 获取模型文档是否需要重建。 |
ShowPartRebuildIndicators | Gets or sets whether to display rebuild indicators on parts that have out-of-date frozen features. | 获取或设置是否在具有过期冻结特征的零件上显示重建指示器。 |
SunLightInformation | Gets the specified sunlight information. | 获取指定的阳光信息。 |
ToolboxPartType | Gets and sets whether this part is a SOLIDWORKS Toolbox part. | 获取并设置此零件是否为 SOLIDWORKS Toolbox 零件。 |
Transparency | Gets and sets the transparency states for the specified display state setting. | 获取和设置指定显示状态设置的透明度状态。 |
UsePageSetup | Gets or sets whether this document uses its own page setup values, SOLIDWORKS application page setup values, or setup values on individual drawing sheets. | 获取或设置此文档是使用其自己的页面设置值、SOLIDWORKS 应用程序页面设置值还是单个工程图图纸上的设置值。 |
ViewDisplayRealView | Gets or sets the RealView Graphics setting. | 获取或设置 RealView 图形设置。 |
Visibility | Gets and sets the visibility states for the specified display state setting. | 获取和设置指定显示状态设置的可见性状态。 |
AnnotationViewCount
AnnotationViews
private void SW_Clear(object sender, RoutedEventArgs e)
{
//打开软件,打开文档
ModelDoc2 model = ((ModelDoc2)(sld4Handler.SwApp.ActiveDoc));
ModelDocExtension modelDoc = model.Extension;
object[] swAnnViews =(object[])modelDoc.AnnotationViews;
AnnotationView annotation = default(AnnotationView);
Feature swFeat = default(Feature);
for (int i = 0; i < modelDoc.AnnotationViewCount; i++)
{
annotation = (AnnotationView)swAnnViews[i];
swFeat = (Feature)annotation;
MessageBox.Show(swFeat.Name);
}
}
//This example shows how to move all annotations to the Notes Area annotation view.
//----------------------------------------------
// Preconditions:
// 1. Open public_documents\samples\tutorial\api\button.sldprt.
// 2. Add a note to the *Top annotation view by double-clicking
// *Top in the Annotations folder in the FeatureManager design
// tree and clicking Insert > Annotations > Note. If prompted
// to turn on feature dimensions display, click No.
// 3. Repeat step 2 to add a note to the *Front annotation view.
// 4. Double-click the Unassigned Items annotation view in the
// Annotations folder in the FeatureManager design tree.
// 5. Open the Immediate window.
//
// Postconditions:
// 1. Examine the Immediate window.
// 2. Double-click each annotation view in the FeatureManager
// design tree to verify that all annotations were moved
// from *Front and *Top to Notes Area only. If prompted
// to turn on feature dimensions display, click No.
//
// NOTE: Because the part is used elsewhere,
// do not save changes when closing the document.
//----------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
namespace IAnnotationViewCSharp.csproj
{
partial class SolidWorksMacro
{
public void Main()
{
ModelDoc2 swModel = default(ModelDoc2);
ModelDocExtension swModelExt = default(ModelDocExtension);
object[] swAnnViews = null;
object[] annotations = null;
Annotation[] annToMove = new Annotation[2];
AnnotationView swAnnView = default(AnnotationView);
Annotation swAnn = default(Annotation);
Feature swFeat = default(Feature);
MathTransform swMathTransform = default(MathTransform);
int i = 0;
int j = 0;
int k = 0;
int l = 0;
double[] planeArray = null;
int nbrPlaneArray = 0;
bool status = false;
double[] transformArray = null;
swModel = (ModelDoc2)swApp.ActiveDoc;
swModelExt = (ModelDocExtension)swModel.Extension;
//Get the annotation views, number of annotation views,
//their names, and whether the annotation view is
//hidden (i.e., not activated)
swAnnViews = (object[])swModelExt.AnnotationViews;
Debug.Print("Number of annotation views: " + swModelExt.AnnotationViewCount);
for (i = 0; i <= swModelExt.AnnotationViewCount - 1; i++)
{
swAnnView = (AnnotationView)swAnnViews[i];
swFeat = (Feature)swAnnView;
Debug.Print(" " + swFeat.Name);
status = swAnnView.Hide();
//status dependent on whether the annotation view is activated
//Only Unassigned Items is activated
Debug.Print(" Hide: " + status);
Debug.Print(" Flat-pattern view: " + swAnnView.FlatPatternView);
}
//Iterate through each annotation view and its annotations
//Print each annotation name, its rotation matrix, whether
//it is shown in the annotation view, and whether it is assigned
//to a 3D view
//Add all annotations to an array to move them
k = 0;
l = 0;
Debug.Print("");
Debug.Print(" Name and number of annotations in annotation view: ");
for (i = 0; i <= swModelExt.AnnotationViewCount - 1; i++)
{
swAnnView = (AnnotationView)swAnnViews[i];
swAnnView.Activate();
annotations = (object[])swAnnView.GetAnnotations2(false, false);
swFeat = (Feature)swAnnView;
Debug.Print("");
Debug.Print(" " + swFeat.Name + " = " + swAnnView.AnnotationCount);
if ((annotations != null))
{
for (j = 0; j <= swAnnView.AnnotationCount - 1; j++)
{
swAnn = (Annotation)annotations[j];
if (k >= 0)
{
annToMove[k] = (Annotation)swAnn;
k = k + 1;
}
planeArray = (double[])swAnn.GetPlane();
nbrPlaneArray = planeArray.GetLength(0);
Debug.Print(" Rotation matrix of the annotation relative to the X-Y plane of the model: ");
while (l < nbrPlaneArray)
{
Debug.Print(" " + planeArray[l] + " " + planeArray[l + 1] + " " + planeArray[l + 2]);
l = l + 3;
}
l = 0;
swMathTransform = (MathTransform)swAnn.GetFlipPlaneTransform();
transformArray = (double[])swMathTransform.ArrayData;
if (transformArray != null)
{
Debug.Print(" Rotation matrix if annotation plane flipped:");
Debug.Print(" " + transformArray[0] + " " + transformArray[1] + " " + transformArray[2]);
Debug.Print(" " + transformArray[3] + " " + transformArray[4] + " " + transformArray[5]);
Debug.Print(" " + transformArray[6] + " " + transformArray[7] + " " + transformArray[8]);
Debug.Print(" Translation component if annotation plane flipped:");
Debug.Print(" " + transformArray[9] + " " + transformArray[10] + " " + transformArray[11]);
Debug.Print("");
}
Debug.Print(" Annotation names:");
Debug.Print(" " + swAnn.GetName());
status = swAnnView.IsShown();
Debug.Print(" Shown in this annotation view: " + status);
status = swAnnView.UnassignedView;
Debug.Print(" Assigned to a 3D View: " + status);
}
}
}
//Move all annotations to the Notes Area annotation view
Debug.Print("");
Debug.Print("Move all annotations to Notes Area annotation view:");
for (i = 0; i <= swModelExt.AnnotationViewCount - 1; i++)
{
swAnnView = (AnnotationView)swAnnViews[i];
swAnnView.Activate();
swFeat = (Feature)swAnnView;
if (swFeat.Name == "Notes Area")
{
status = swAnnView.MoveAnnotations(annToMove);
Debug.Print(" Annotations moved: " + status);
status = swAnnView.Show();
//status should be false because annotation was activated
Debug.Print(" Show: " + status);
}
}
}
/// <summary>
/// The SldWorks swApp variable is pre-assigned for you.
/// </summary>
public SldWorks swApp;
}
}
CustomPropertyManager
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Diagnostics;
namespace Get4CustomPropertyManagerCSharp.csproj
{
partial class SolidWorksMacro
{
public void Main()
{
ModelDoc2 swModel = default(ModelDoc2);
ModelDocExtension swModelDocExt = default(ModelDocExtension);
CustomPropertyManager swCustProp = default(CustomPropertyManager);
string val = "";
string valout = "";
bool status;
swModel = (ModelDoc2)swApp.ActiveDoc;
swModelDocExt = swModel.Extension;
// Get the custom property data
swCustProp = swModelDocExt.get_CustomPropertyManager("");
status = swCustProp.Get4("Property_Name", false, out val, out valout);
Debug.Print("Value: " + val);
Debug.Print("Evaluated value: " + valout);
Debug.Print("Up-to-date data: " + status);
}
/// <summary>
/// The SldWorks swApp variable is pre-assigned for you.
/// </summary>
public SldWorks swApp;
}
}
DisplayMode
//This example shows how to get display modes, transparency states, and visibility states of components.
//------------------------------------------------------------------------------
// Preconditions: Open an assembly that contains a minimum of three top-level
// components and two display states, "DS_1" and "DS_2".
//
// Postconditions: Inspect the Immediate Window for the display modes,
// transparency states, and visibility states of all three components
// in both DS_1 and DS_2.
//-----------------------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Diagnostics;
namespace GetDisplayMode.csproj
{
public partial class SolidWorksMacro
{
ModelDoc2 swDoc = null;
ModelDocExtension swExt = null;
DisplayStateSetting swDSS = null;
object varStatus;
object varTStatus;
object varVStatus;
Array statusArray;
Array statusTArray;
Array statusVArray;
const int maxEntMode = 3;
public void Main()
{
swDoc = (ModelDoc2)(swApp.ActiveDoc);
swExt = swDoc.Extension;
int docType = swDoc.GetType();
if (docType == (int)swDocumentTypes_e.swDocASSEMBLY)
{
CreateDisplayStateSetting();
varStatus = swExt.get_DisplayMode(swDSS);
statusArray = (Array)varStatus;
varTStatus = swExt.get_Transparency(swDSS);
statusTArray = (Array)varTStatus;
varVStatus = swExt.get_Visibility(swDSS);
statusVArray = (Array)varVStatus;
WriteOutput();
}
}
public void CreateDisplayStateSetting()
{
swDSS = swExt.GetDisplayStateSetting((int)swDisplayStateOpts_e.swThisDisplayState);
swDSS.Option = (int)swDisplayStateOpts_e.swSpecifyDisplayState;
string[] specDSNames = new string[2];
specDSNames[0] = "DS_1";
specDSNames[1] = "DS_2";
object varSpecDSNames = specDSNames;
swDSS.Names = varSpecDSNames;
AssemblyDoc swADoc;
swADoc = (AssemblyDoc)swDoc;
int compCnt = swADoc.GetComponentCount(true);
Component2[] listComp = new Component2[maxEntMode];
if (compCnt >= maxEntMode)
{
object[] varComp = (object[])(swADoc.GetComponents(true));
listComp[0] = (Component2)varComp[0];
listComp[1] = (Component2)varComp[1];
listComp[2] = (Component2)varComp[2];
swDSS.Entities = listComp;
}
}
public void WriteOutput()
{
int entCount = swDSS.GetEntityCount();
object[] listComp = (object[])swDSS.Entities;
int allCtr = 0;
for (int entctr = 0; entctr < entCount; ++entctr)
{
Component2 swComp = (Component2)listComp[entctr];
Debug.Print(swComp.Name2);
int dsNameCount = swDSS.GetNameCount();
object[] dsNames = (object[])swDSS.Names;
for (int namectr = 0; namectr < dsNameCount; ++namectr)
{
Debug.Print(" " + (string)dsNames[namectr]);
int status = (int)statusArray.GetValue(allCtr);
int statusT = (int)statusTArray.GetValue(allCtr);
int statusV = (int)statusVArray.GetValue(allCtr);
WriteMode(status);
WriteTransparency(statusT);
WriteVisibility(statusV);
++allCtr;
}
}
}
public void WriteMode(int status)
{
switch (status)
{
case (int)swDisplayMode_e.swDisplayModeDEFAULT:
Debug.Print(" swDisplayModeDEFAULT");
break;
case (int)swDisplayMode_e.swHIDDEN:
Debug.Print(" swHIDDEN");
break;
case (int)swDisplayMode_e.swHIDDEN_GREYED:
Debug.Print(" swHIDDEN_GREYED");
break;
case (int)swDisplayMode_e.swSHADED:
Debug.Print(" swSHADED");
break;
case (int)swDisplayMode_e.swSHADED_EDGES:
Debug.Print(" swSHADED_EDGES");
break;
case (int)swDisplayMode_e.swWIREFRAME:
Debug.Print(" swWIREFRAME");
break;
case (int)swDisplayMode_e.swDisplayModeUNKNOWN:
Debug.Print(" Error:swDisplayModeUNKNOWN");
break;
Case CInt(swDisplayMode_e.swFACETED_WIREFRAME)
Debug.Print (" swFACETED_WIREFRAME")
break;
Case CInt(swDisplayMode_e.swFACETED_HIDDEN_GREYED)
Debug.Print (" swFACETED_HIDDEN_GREYED")
break;
Case CInt(swDisplayMode_e.swFACETED_HIDDEN)
Debug.Print (" swFACETED_HIDDEN")
break;
}
}
public void WriteTransparency(int status)
{
switch (status)
{
case (int)swTransparencyState_e.swTransparencyStateTransparent:
Debug.Print(" swTransparencyStateTransparent");
break;
case (int)swTransparencyState_e.swTransparencyStateNonTransparent:
Debug.Print(" swTransparencyStateNonTransparent");
break;
case (int)swTransparencyState_e.swTransparencyStateUnknown:
Debug.Print(" ERROR : swTransparencyStateUnknown");
break;
}
}
public void WriteVisibility(int status)
{
switch (status)
{
case (int)swVisibilityState_e.swVisibilityStateHide:
Debug.Print(" swVisibilityStateHide");
break;
case (int)swVisibilityState_e.swVisibilityStateShown:
Debug.Print(" swVisibilityStateShown");
break;
case (int)swVisibilityState_e.swVisibilityStateUnknown:
Debug.Print(" ERROR : swVisibilityStateUnknown");
break;
}
}
public SldWorks swApp;
}
}
Document
private void SW_Clear(object sender, RoutedEventArgs e)
{
ModelDoc2 model = ((ModelDoc2)(sld4Handler.SwApp.ActiveDoc));
ModelDocExtension modelDocExtension = model.Extension;
ModelDoc2 modelDoc = modelDocExtension.Document;
}
IncludeMassPropertiesOfHiddenBodies
//This example shows how to get the mass properties for:
//visible and hidden components in an assembly.
//only the visible components in an assembly.
//----------------------------------------------------------------------------------
// Preconditions:
// 1. Open public_documents\samples\tutorial\routing-pipes\ball valve with flanges.sldasm.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Gets the mass properties of all components.
// 2. Hides the slip on weld flange<1> component.
// 3. Gets the mass properties of the visible components only.
// 4. Examine the Immediate window.
//
// NOTE: Because this assembly is used elsewhere, do not save changes.
//---------------------------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Diagnostics;
namespace IncludeMassPropertiesOfHiddenBodiesModelDocExtCSharp.csproj
{
partial class SolidWorksMacro
{
public void Main()
{
ModelDoc2 swModel;
ModelDocExtension swModelDocExt;
int massStatus = 0;
double[] massProperties;
bool boolstatus;
swModel = (ModelDoc2)swApp.ActiveDoc;
swModelDocExt = swModel.Extension;
Debug.Print("-------------------------------");
Debug.Print("Mass properties of visible and hidden components:");
massProperties = (double[])swModelDocExt.GetMassProperties(1, ref massStatus);
if ((massProperties != null))
{
Debug.Print(" CenterOfMassX = " + massProperties[0]);
Debug.Print(" CenterOfMassY = " + massProperties[1]);
Debug.Print(" CenterOfMassZ = " + massProperties[2]);
Debug.Print(" Volume = " + massProperties[3]);
Debug.Print(" Area = " + massProperties[4]);
Debug.Print(" Mass = " + massProperties[5]);
Debug.Print(" MomXX = " + massProperties[6]);
Debug.Print(" MomYY = " + massProperties[7]);
Debug.Print(" MomZZ = " + massProperties[8]);
Debug.Print(" MomXY = " + massProperties[9]);
Debug.Print(" MomZX = " + massProperties[10]);
Debug.Print(" MomYZ = " + massProperties[11]);
}
Debug.Print("-------------------------------");
// Now hide another component
boolstatus = swModelDocExt.SelectByID2("slip on weld flange-1@ball valve with flanges", "COMPONENT", 0, 0, 0, false, 0, null, 0);
swModel.HideComponent2();
Debug.Print("Mass properties of visible components only:");
swModelDocExt.IncludeMassPropertiesOfHiddenBodies = false;
massProperties = (double[])swModelDocExt.GetMassProperties(1, ref massStatus);
if ((massProperties != null))
{
Debug.Print(" CenterOfMassX = " + massProperties[0]);
Debug.Print(" CenterOfMassY = " + massProperties[1]);
Debug.Print(" CenterOfMassZ = " + massProperties[2]);
Debug.Print(" Volume = " + massProperties[3]);
Debug.Print(" Area = " + massProperties[4]);
Debug.Print(" Mass = " + massProperties[5]);
Debug.Print(" MomXX = " + massProperties[6]);
Debug.Print(" MomYY = " + massProperties[7]);
Debug.Print(" MomZZ = " + massProperties[8]);
Debug.Print(" MomXY = " + massProperties[9]);
Debug.Print(" MomZX = " + massProperties[10]);
Debug.Print(" MomYZ = " + massProperties[11]);
}
Debug.Print("-------------------------------");
}
/// <summary>
/// The SldWorks swApp variable is pre-assigned for you.
/// </summary>
public SldWorks swApp;
}
}
ToolboxPartType
This example shows how to test whether a part is a Toolbox part.
//----------------------------------------------------------------------------
// Preconditions: Open public_documents\samples\tutorial\api\bagel.sldprt.
//
// Postconditions: Inspect the Immediate window for the Toolbox part type.
//
// NOTE: Because the model is used elsewhere,
// do not save changes when closing it.
// ---------------------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
namespace ToolboxPartType_CSharp.csproj
{
partial class SolidWorksMacro
{
ModelDoc2 part;
ModelDocExtension modelDocExt;
int ret;
public void Main()
{
part = (ModelDoc2)swApp.ActiveDoc;
modelDocExt = part.Extension;
ret = modelDocExt.ToolboxPartType;
Debug.Print("Toolbox part type as defined in swToolBoxPartType_e? " + ret);
}
public SldWorks swApp;
}
}
ViewDisplayRealView
This example shows how to get the file name of the first appearance applied to a model.
//----------------------------------------------------------------
// Preconditions:
// 1. Verify that the specified model document exists.
// 2. Verify that the specified materials file exists.
// 3. Open the Immediate window.
//
// Postconditions:
// 1. Opens the specified model document.
// 2. Applies the specified appearance to the selected face.
// 3. Gets the material IDs.
// 4. Gets the file name of the first appearance applied to the model.
// 5. Examine the graphics area and the Immediate window.
//
// NOTE: Because the model is used elsewhere, do not save changes.
//----------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
namespace FileNameCSharp.csproj
{
public partial class SolidWorksMacro
{
public void Main()
{
ModelDoc2 swModel = default(ModelDoc2);
ModelDocExtension swModelDocExt = default(ModelDocExtension);
SelectionMgr swSelectionMgr = default(SelectionMgr);
Face2 swFace = default(Face2);
Configuration swConfiguration = default(Configuration);
RenderMaterial swRenderMaterial = default(RenderMaterial);
int nbrRenderMaterials = 0;
string fileName = null;
int warnings = 0;
int errors = 0;
bool status = false;
string materialName = null;
string[] displayStateNames = null;
int materialID1 = 0;
int materialID2 = 0;
//Open part document
fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\cover_plate.sldprt";
swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
//Create material for the appearance
materialName = "C:\\Program Files\\SolidWorks Corp\\SolidWorks\\data\\graphics\\Materials\\plastic\\low gloss\\blue low gloss plastic.p2m";
swModelDocExt = (ModelDocExtension)swModel.Extension;
swRenderMaterial = (RenderMaterial)swModelDocExt.CreateRenderMaterial(materialName);
//Verify that RealView Graphics is set
Debug.Print("RealView Graphics set? " + swModelDocExt.ViewDisplayRealView);
//Select a face and add an appearance
status = swModelDocExt.SelectByID2("", "FACE", 0.0417924256550464, 0.0796803314056547, 0, false, 0, null, 0);
swSelectionMgr = (SelectionMgr)swModel.SelectionManager;
swFace = (Face2)swSelectionMgr.GetSelectedObject6(1, -1);
status = swRenderMaterial.AddEntity(swFace);
Debug.Print("Appearance added to selected face? " + status);
swModel.ClearSelection2(true);
//Get the names of display states
//Add the appearance to all display states
swConfiguration = (Configuration)swModel.GetActiveConfiguration();
displayStateNames = (string[])swConfiguration.GetDisplayStates();
status = swModelDocExt.AddDisplayStateSpecificRenderMaterial(swRenderMaterial, (int)swDisplayStateOpts_e.swAllDisplayState, displayStateNames, out materialID1, out materialID2);
Debug.Print("Material IDs returned by IModelDocExtension::AddDisplayStateSpecificRenderMaterial: ");
Debug.Print(" ID1: " + materialID1);
Debug.Print(" ID2: " + materialID2);
//Get the number of appearances
nbrRenderMaterials = swModelDocExt.GetRenderMaterialsCount2((int)swDisplayStateOpts_e.swAllDisplayState, displayStateNames);
//If one or more appearances are applied to the model,
//then get the file name of the first appearance applied
if (nbrRenderMaterials > 0)
{
swRenderMaterial.GetMaterialIds(out materialID1, out materialID2);
Debug.Print("Material IDs returned by IModelDocExtension::GetMaterialIds: ");
Debug.Print(" ID1: " + materialID1);
Debug.Print(" ID2: " + materialID2);
Debug.Print("First appearance's file name: " + swRenderMaterial.FileName);
}
else
{
Debug.Print("No appearances applied to this model.");
}
}
/// <summary>
/// The SldWorks swApp variable is pre-assigned for you.
/// </summary>
public SldWorks swApp;
}
}
Visibility
This example shows how to get display modes, transparency states, and visibility states of components.
//------------------------------------------------------------------------------
// Preconditions: Open an assembly that contains a minimum of three top-level
// components and two display states, "DS_1" and "DS_2".
//
// Postconditions: Inspect the Immediate Window for the display modes,
// transparency states, and visibility states of all three components
// in both DS_1 and DS_2.
//-----------------------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Diagnostics;
namespace GetDisplayMode.csproj
{
public partial class SolidWorksMacro
{
ModelDoc2 swDoc = null;
ModelDocExtension swExt = null;
DisplayStateSetting swDSS = null;
object varStatus;
object varTStatus;
object varVStatus;
Array statusArray;
Array statusTArray;
Array statusVArray;
const int maxEntMode = 3;
public void Main()
{
swDoc = (ModelDoc2)(swApp.ActiveDoc);
swExt = swDoc.Extension;
int docType = swDoc.GetType();
if (docType == (int)swDocumentTypes_e.swDocASSEMBLY)
{
CreateDisplayStateSetting();
varStatus = swExt.get_DisplayMode(swDSS);
statusArray = (Array)varStatus;
varTStatus = swExt.get_Transparency(swDSS);
statusTArray = (Array)varTStatus;
varVStatus = swExt.get_Visibility(swDSS);
statusVArray = (Array)varVStatus;
WriteOutput();
}
}
public void CreateDisplayStateSetting()
{
swDSS = swExt.GetDisplayStateSetting((int)swDisplayStateOpts_e.swThisDisplayState);
swDSS.Option = (int)swDisplayStateOpts_e.swSpecifyDisplayState;
string[] specDSNames = new string[2];
specDSNames[0] = "DS_1";
specDSNames[1] = "DS_2";
object varSpecDSNames = specDSNames;
swDSS.Names = varSpecDSNames;
AssemblyDoc swADoc;
swADoc = (AssemblyDoc)swDoc;
int compCnt = swADoc.GetComponentCount(true);
Component2[] listComp = new Component2[maxEntMode];
if (compCnt >= maxEntMode)
{
object[] varComp = (object[])(swADoc.GetComponents(true));
listComp[0] = (Component2)varComp[0];
listComp[1] = (Component2)varComp[1];
listComp[2] = (Component2)varComp[2];
swDSS.Entities = listComp;
}
}
public void WriteOutput()
{
int entCount = swDSS.GetEntityCount();
object[] listComp = (object[])swDSS.Entities;
int allCtr = 0;
for (int entctr = 0; entctr < entCount; ++entctr)
{
Component2 swComp = (Component2)listComp[entctr];
Debug.Print(swComp.Name2);
int dsNameCount = swDSS.GetNameCount();
object[] dsNames = (object[])swDSS.Names;
for (int namectr = 0; namectr < dsNameCount; ++namectr)
{
Debug.Print(" " + (string)dsNames[namectr]);
int status = (int)statusArray.GetValue(allCtr);
int statusT = (int)statusTArray.GetValue(allCtr);
int statusV = (int)statusVArray.GetValue(allCtr);
WriteMode(status);
WriteTransparency(statusT);
WriteVisibility(statusV);
++allCtr;
}
}
}
public void WriteMode(int status)
{
switch (status)
{
case (int)swDisplayMode_e.swDisplayModeDEFAULT:
Debug.Print(" swDisplayModeDEFAULT");
break;
case (int)swDisplayMode_e.swHIDDEN:
Debug.Print(" swHIDDEN");
break;
case (int)swDisplayMode_e.swHIDDEN_GREYED:
Debug.Print(" swHIDDEN_GREYED");
break;
case (int)swDisplayMode_e.swSHADED:
Debug.Print(" swSHADED");
break;
case (int)swDisplayMode_e.swSHADED_EDGES:
Debug.Print(" swSHADED_EDGES");
break;
case (int)swDisplayMode_e.swWIREFRAME:
Debug.Print(" swWIREFRAME");
break;
case (int)swDisplayMode_e.swDisplayModeUNKNOWN:
Debug.Print(" Error:swDisplayModeUNKNOWN");
break;
Case CInt(swDisplayMode_e.swFACETED_WIREFRAME)
Debug.Print (" swFACETED_WIREFRAME")
break;
Case CInt(swDisplayMode_e.swFACETED_HIDDEN_GREYED)
Debug.Print (" swFACETED_HIDDEN_GREYED")
break;
Case CInt(swDisplayMode_e.swFACETED_HIDDEN)
Debug.Print (" swFACETED_HIDDEN")
break;
}
}
public void WriteTransparency(int status)
{
switch (status)
{
case (int)swTransparencyState_e.swTransparencyStateTransparent:
Debug.Print(" swTransparencyStateTransparent");
break;
case (int)swTransparencyState_e.swTransparencyStateNonTransparent:
Debug.Print(" swTransparencyStateNonTransparent");
break;
case (int)swTransparencyState_e.swTransparencyStateUnknown:
Debug.Print(" ERROR : swTransparencyStateUnknown");
break;
}
}
public void WriteVisibility(int status)
{
switch (status)
{
case (int)swVisibilityState_e.swVisibilityStateHide:
Debug.Print(" swVisibilityStateHide");
break;
case (int)swVisibilityState_e.swVisibilityStateShown:
Debug.Print(" swVisibilityStateShown");
break;
case (int)swVisibilityState_e.swVisibilityStateUnknown:
Debug.Print(" ERROR : swVisibilityStateUnknown");
break;
}
}
public SldWorks swApp;
}
}
方法
Name | Description | 备注 |
AddAngularRunningDim | Adds the specified angular running dimension for selected entities. | 为选定实体添加指定的角度运行尺寸。 |
AddComment | Adds a comment to this document's Comment Folder. | 向此文档的评论文件夹添加评论。 |
AddDecal | Adds a decal to the model. | 向模型添加贴花。 |
AddDimension | Creates a display dimension at the specified location for selected entities. | 在选定实体的指定位置创建显示尺寸。 |
AddDisplayStateSpecificRenderMaterial | Adds the specified appearance to the specified display states in the active configuration and returns the IDs assigned to that appearance. | 将指定外观添加到活动配置中的指定显示状态,并返回分配给该外观的 ID。 |
AddOrdinateDimension | Inserts an ordinate dimension. | 插入纵坐标尺寸。 |
AddOrUpdateSearchData | Adds or updates the SOLIDWORKS Search, third-party, application keyword and value to the model document. | 向模型文档添加或更新 SOLIDWORKS 搜索、第三方、应用程序关键字和值。 |
AddPathLengthDim | Inserts a path length dimension at the specified coordinates for a selected path. | 在选定路径的指定坐标处插入路径长度尺寸。 |
AddSpecificDimension | Creates the specified display dimension at the specified location for selected entities. | 在指定位置为选定实体创建指定的显示维度。 |
AddSymmetricDimension | Creates a full symmetrical angular dimension at the specified location for the selected entities. | 在选定实体的指定位置创建完全对称的角度尺寸。 |
AlignDimensions | Aligns the selected dimensions in drawing documents. | 对齐工程图文档中的选定尺寸。 |
AlignRunningDimension | Aligns the extension lines of all angular dimensions to be the same distance from the center as the baseline dimension (0⁰) in the set of angular running dimensions. | 将所有角度尺寸的尺寸界线对齐到与角度运行尺寸集中的基线尺寸 (0⁰) 中心的距离相同。 |
ApplyFormatPainterToAll | Applies Format Painter to all dimensions and annotations in the active document. | 将格式刷应用于活动文档中的所有尺寸和注释。 |
BreakAllExternalFileReferences2 | Breaks all external references and allows you to insert the features of the original part, or parts, if the external references are broken. | 断开所有外部参考并允许您在外部参考断开时插入原始零件或零件的特征。 |
Capture3DView | Captures the 3D View of this part or assembly. | 捕获此零件或装配体的 3D 视图。 |
ChangeSketchPlane | Changes the plane used by a sketch by moving the selected sketch to the selected plane in the specified configurations. | 通过将选定草图移动到指定配置中的选定平面来更改草图使用的平面。 |
Compare3DPMI | Compare DimXpert annotations, reference dimensions, and other annotations between different versions of the same part document. | 在同一零件文档的不同版本之间比较 DimXpert 注释、参考尺寸和其他注释。 |
CopyDraftingStandard | Copy the current custom drafting standard. | 复制当前的自定义绘图标准。 |
Create3DBoundingBox | Creates a 3D bounding box for a cut list item in a weldment part. | 为焊件零件中的切割清单项目创建 3D 边界框。 |
CreateAdvancedHoleElementData | Creates an Advanced Hole element data object of the specified type. | 创建指定类型的高级孔元素数据对象。 |
CreateBalloonOptions | Creates an object that stores BOM balloon options. | 创建一个存储 BOM 气球选项的对象。 |
CreateCallout | Creates a callout independent of a selection. | 创建独立于选择的标注。 |
CreateDecal | Creates a decal for this model. | 为这个模型创建一个贴花。 |
CreateMassProperty | Creates a IMassProperty object. | 创建 IMassProperty 对象。 |
CreateMeasure | Creates a measure tool. | 创建测量工具。 |
CreateOLEObject | Creates an OLE object on the active document. | 在活动文档上创建一个 OLE 对象。 |
CreateRenderMaterial | Creates an appearance for this model. | 为该模型创建外观。 |
CreateStackedBalloonOptions | Creates an object that stores options for stacked balloons. | 创建一个存储堆叠气球选项的对象。 |
CreateTexture | Creates a texture. | 创建纹理。 |
DeleteAllDecals | Deletes all decals on this model. | 删除此模型上的所有贴花。 |
DeleteAttachment | Deletes the specified file in the Attachments folder in the FeatureManager design tree. | 删除 FeatureManager 设计树附件文件夹中的指定文件。 |
DeleteDecal | Removes the specified decal from this model. | 从此模型中删除指定的贴花。 |
DeleteDisplayStateSpecificRenderMaterial | Deletes the specified appearances, using the IDs of the appearances, from the active configuration. | 使用外观的 ID 从活动配置中删除指定的外观。 |
DeleteDraftingStandard | Delete the current custom drafting standard. | 删除当前的自定义绘图标准。 |
DeleteFeatureMgrViewx64 | Removes the specified tab in the FeatureManager design tree in 64-bit applications. | 在 64 位应用程序中移除 FeatureManager 设计树中的指定选项卡。 |
DeleteScene | Deletes the scene applied to this model. | 删除应用于此模型的场景。 |
DeleteSearchData | Deletes the specified SOLIDWORKS Search third-party keywords from the model document. | 从模型文档中删除指定的 SOLIDWORKS Search 第三方关键字。 |
DeleteSelection2 | Deletes the selected items, with the option to delete absorbed features, child features, or both. | 删除所选项目,可选择删除吸收的特征、子特征或两者。 |
EditBalloonProperties2 | Edits the selected balloon's properties. | 编辑选定零件序号的属性。 |
EditDimensionProperties | Edits the selected dimension. | 编辑选定的尺寸。 |
EditRebuildAll | Rebuilds only those features that need to be rebuilt in all configurations without activating each configuration. | 仅重建需要在所有配置中重建的功能,而不激活每个配置。 |
FindTrackedObjects | Finds the tracking IDs assigned to entities in this document. | 在此文档中查找分配给实体的跟踪 ID。 |
FinishRecordingUndoObject2 | Ends recording of a SOLIDWORKS Undo object with the specified name and visibility. | 结束记录具有指定名称和可见性的 SOLIDWORKS 撤消对象。 |
ForceRebuildAll | Forces a rebuild of all features in all configurations without activating each configuration. | 强制重建所有配置中的所有功能,而不激活每个配置。 |
GeodesicSketchOffset | Creates a geodesic sketch offset along the curvature of a surface. | 沿曲面的曲率创建测地线草图偏移。 |
Get3DView | Gets the 3D View with the specified name for this part or assembly. | 获取此零件或装配体具有指定名称的 3D 视图。 |
Get3DViewCount | Gets the number of 3D Views in this part or assembly. | 获取此零件或装配体中的 3D 视图数。 |
Get3DViewNames | Gets names of the 3D Views in this part or assembly. | 获取此零件或装配体中 3D 视图的名称。 |
Get3DViews | Gets the 3D Views for this part or assembly. | 获取此零件或装配体的 3D 视图。 |
GetActivePropertyManagerPage | Gets the name of the active PropertyManager page. | 获取活动 PropertyManager 页面的名称。 |
GetAdvancedSpotLightProperties | Gets the attenuation-related, advanced properties for the specified SOLIDWORKS spot light in this model. | 获取此模型中指定 SOLIDWORKS 聚光灯的衰减相关高级属性。 |
GetAnnotationCount | Gets the number of annotations on this part. | 获取此部分的注释数。 |
GetAnnotations | Gets the annotations on this part. | 获取这部分的注释。 |
GetAppearanceSetting | Gets the appearance setting for this document. | 获取此文档的外观设置。 |
GetAttachmentCount | Gets the number of attachments for this document. | 获取此文档的附件数。 |
GetAttachments | Gets the attachments for this document. | 获取此文档的附件。 |
GetCalloutVariableString | Gets the string for the specified callout variable. | 获取指定标注变量的字符串。 |
GetCameraById | Gets a camera using the specified camera ID. | 使用指定的相机 ID 获取相机。 |
GetCameraCount | Gets the number of cameras in the document. | 获取文档中的摄像机数量。 |
GetCameraDefinition | Gets a camera, but does not add the newly created camera to the model. | 获取相机,但不会将新创建的相机添加到模型中。 |
GetCommandTabs | Gets all of the SOLIDWORKS CommandManager tab names in this document. | 获取此文档中的所有 SOLIDWORKS CommandManager 选项卡名称。 |
GetCoordinateSystemTransformByName | Gets the transform of the specified coordinate system. | 获取指定坐标系的变换。 |
GetCorresponding2 | Gets the object in the underlying part or subassembly document that corresponds to the specified input object in this drawing view or assembly. | 获取底层零件或子装配体文档中与此工程图视图或装配体中的指定输入对象相对应的对象。 |
GetCorrespondingEntity2 | Gets the entity in the underlying part or subassembly that corresponds to the specified entity in this assembly or drawing view. | 获取与此装配体或工程图视图中的指定实体相对应的基础零件或子装配体中的实体。 |
GetCostingManager | Gets the entry-point interface to the SOLIDWORKS Costing API and gets the CostingManager. | 获取 SOLIDWORKS Costing API 的入口点接口并获取 CostingManager。 |
GetDecal | Gets the specified decal in this model. | 获取此模型中的指定贴花。 |
GetDecals | Gets the decals applied to the model. | 获取应用于模型的贴花。 |
GetDecalsCount | Gets the number of decals applied to this model. | 获取应用于此模型的贴花数量。 |
GetDependencies | Gets all of this model's dependencies. | 获取此模型的所有依赖项。 |
GetDisplayStateSetting | Gets the display state setting for the specified scope. | 获取指定范围的显示状态设置。 |
GetDraftingStandardNames | Get the names of all currently available drafting standards. | 获取所有当前可用的绘图标准的名称。 |
GetFlattenSheetMetalPersistReference | Gets a byte array of persistent reference IDs for the specified entity (a face, edge, or vertex) in a flattened sheet metal part. | 获取展平钣金零件中指定实体(面、边或顶点)的持久参考 ID 的字节数组。 |
GetGeneralTableAnnotation | Creates a general table annotation for SOLIDWORKS MBD 3D PDF. | 为 SOLIDWORKS MBD 3D PDF 创建通用表格注释。 |
GetKeepLightInRenderScene | Gets whether a light is kept when the scene changes. | 获取场景变化时是否保留灯光。 |
GetLastFeatureAdded | Gets the last feature added to the model. | 获取添加到模型的最后一个特征。 |
GetLicenseType | Gets the type of SOLIDWORKS license used when the model was created. | 获取创建模型时使用的 SOLIDWORKS 许可类型。 |
GetLightEnabledInRender | Gets whether a light is on in this model. | 获取此模型中的灯是否亮起。 |
GetMassProperties2 | Gets the actual mass properties of the components in the model at the specified accuracy. | 以指定的精度获取模型中组件的实际质量属性。 |
GetMaterial | Gets the appearance for the specified appearance ID in the specified configuration in this model document | 获取此模型文档中指定配置中指定外观 ID 的外观 |
GetMaterialPropertyValues | Gets the material properties for this model document. | 获取此模型文档的材料属性。 |
GetMBD3DPdfData | Gets the SOLIDWORKS MBD 3D PDF data object. | 获取 SOLIDWORKS MBD 3D PDF 数据对象。 |
GetModelBreakViewNames | Gets the names and number of the Model Break Views in the current configuration of the active model. | 获取活动模型的当前配置中模型中断视图的名称和编号。 |
GetModelViewCount | Gets the number of model views in this document. | 获取此文档中模型视图的数量。 |
GetModelViews | Gets the model views in this document. | 获取此文档中的模型视图。 |
GetMotionStudyManager | Gets the SOLIDWORKS motion study's MotionManager. | 获取 SOLIDWORKS 运动算例的 MotionManager。 |
GetNamedViewRotation | Gets the specified named view orientation matrix with respect to the Front view. | 获取相对于前视图的指定命名视图方向矩阵。 |
GetObjectByPersistReference3 | Gets the object assigned to the specified persistent reference ID. | 获取分配给指定持久引用 ID 的对象。 |
GetObjectId | Gets the object ID for the specified annotation. | 获取指定注释的对象 ID。 |
GetOLEObjectCount | Gets the number of OLE objects. | 获取 OLE 对象的数量。 |
GetOLEObjects | Get the OLE objects. | 获取 OLE 对象。 |
GetPackAndGo | Gets a Pack and Go object. | 获取打包对象。 |
GetPersistReference3 | Gets the persistent reference ID for the specified object in this model document. | 获取此模型文档中指定对象的持久引用 ID。 |
GetPersistReferenceCount3 | Gets the size of the persistent reference ID assigned to the selected object in this model document. | 获取分配给此模型文档中选定对象的持久引用 ID 的大小。 |
GetPrint3DDialog | Gets the IPrint3DDialog object. | 获取 IPrint3DDialog 对象。 |
GetPrintSpecification | Gets the IPrintSpecification object for this document. | 获取此文档的 IPrintSpecification 对象。 |
GetRenderCustomReferences | Get the custom render references for this model. | 获取此模型的自定义渲染参考。 |
GetRenderMaterials2 | Gets the appearances applied to this model document in the specified display states. | 获取在指定显示状态下应用于此模型文档的外观。 |
GetRenderMaterialsCount2 | Gets the number of appearances applied to this model document in the specified display states. | 获取在指定显示状态下应用于此模型文档的出现次数。 |
GetRenderStockReferences | Gets the SOLIDWORKS-supplied (stock) render references for this model. | 获取此模型的 SOLIDWORKS 提供的(库存)渲染参考。 |
GetRoutingComponentManager | Gets the routing component manager. | 获取路由组件管理器。 |
GetScanto3D | Gets the IScanTo3D object for this document. | 获取此文档的 IScanTo3D 对象。 |
GetSceneBkgDIBx64 | Gets the background image as DIBSECTION in 64-bit applications. | 获取 64 位应用程序中作为 DIBSECTION 的背景图像。 |
GetSearchData | Gets the SOLIDWORKS Search, third-party, application keywords from the model document. | 从模型文档中获取 SOLIDWORKS Search、第三方应用程序关键字。 |
GetSearchDataCount | Gets the number of SOLIDWORKS Search keywords for the specified third-party application previously added to this model document. | 获取先前添加到此模型文档的指定第三方应用程序的 SOLIDWORKS 搜索关键字数。 |
GetSectionProperties2 | Gets the section properties for the following types of selected items: Planar model face in any document、Face on a section plane、Crosshatch section face in a section view in a drawing a sketch、Sketch | 获取以下类型选定项的截面属性:任何文档中的平面模型面、截面平面上的面、绘图中截面视图中的剖面线截面面、草图、草图 |
GetSheetMetalObjectsByPersistReference | Gets the objects in a folded sheet metal part that correspond to the byte array of persistent reference IDs of an entity in a flattened sheet metal part. | 获取折叠钣金零件中的对象,这些对象对应于展平钣金零件中实体的持久引用 ID 的字节数组。 |
GetStream | Gets the handle for the specified stream. | 获取指定流的句柄。 |
GetSunLightAdvancedPropertyValues | Gets the specified sunlight advanced properties. | 获取指定的阳光高级属性。 |
GetSunLightSourcePropertyValues | Gets the property values for a sunlight source. | 获取阳光源的属性值。 |
GetSustainability | Gets the entry-point interface to the SOLIDWORKS Sustainability API. | 获取 SOLIDWORKS Sustainability API 的入口点接口。 |
GetTemplateSheetMetal | Gets the sheet metal folder feature from this sheet metal model created in SOLIDWORKS 2013 or later. | 从在 SOLIDWORKS 2013 或更高版本中创建的这个钣金模型获取钣金文件夹特征。 |
GetTexture | Gets the texture applied to the specified configuration. | 获取应用于指定配置的纹理。 |
GetUserPreferenceDouble | Gets document default user preference values. This method is intended for user preferences of type double. | 获取文档默认用户首选项值。此方法适用于 double 类型的用户首选项。 |
GetUserPreferenceDoubleValueRange | Gets the current document default user preference value, and the minimum and maximum valid document user preference values. | 获取当前文档默认用户首选项值,以及最小和最大有效文档用户首选项值。 |
GetUserPreferenceInteger | Sets document default user preference values. This method is intended for user preferences of type integer. | 设置文档默认用户首选项值。此方法适用于整数类型的用户首选项。 |
GetUserPreferenceString | Gets document default user preference values. This method is intended for user preferences of type string. | 获取文档默认用户首选项值。此方法适用于字符串类型的用户首选项。 |
GetUserPreferenceTextFormat | Gets document default user preference values. This method is intended for getting detailing text formats. | 获取文档默认用户首选项值。此方法用于获取详细的文本格式。 |
GetUserPreferenceToggle | Gets document default user preference values. This method is intended for user preferences that can be toggled. | 获取文档默认用户首选项值。此方法适用于可以切换的用户首选项。 |
GetVisibleBox | Gets the visible bounding box set by IModelDocExtension::SetVisibleBox for a part or an assembly. | 获取由 IModelDocExtension::SetVisibleBox 为零件或装配设置的可见边界框。 |
GetWhatsWrong | Gets the What's Wrong dialog information for this model document. | 获取此模型文档的 What's Wrong 对话框信息。 |
GetWhatsWrongCount | Gets the number of items in the What's Wrong dialog. | 获取“错误”对话框中的项目数。 |
HasDesignTable | Gets whether a document has a design table. | 获取文档是否具有设计表。 |
HasMaterialPropertyValues | Gets whether this model has an appearance. | 获取此模型是否具有外观。 |
HasRenamedDocuments | Gets whether the document has renamed files. | 获取文档是否已重命名文件。 |
HideDecal | Hides or shows the specified decal applied to this model. | 隐藏或显示应用于此模型的指定贴花。 |
HideFeatureManager | Hides or shows the Manager Pane. | 隐藏或显示管理器窗格。 |
IAddDisplayStateSpecificRenderMaterial | Adds the specified material to the specified display states in the active configuration and returns the IDs assigned to that material. | 将指定材料添加到活动配置中的指定显示状态,并返回分配给该材料的 ID。 |
IChangeSketchPlane | Changes the plane used by a sketch by moving the selected sketch to the selected plane in the specified configurations. | 通过将选定草图移动到指定配置中的选定平面来更改草图使用的平面。 |
ICreateOLEObject | Creates an OLE object on the active document. | 在活动文档上创建一个 OLE 对象。 |
IDeleteDisplayStateSpecificRenderMaterial | Deletes the specified materials, using the IDs of the materials, from the active configuration. | 使用材料的 ID 从活动配置中删除指定的材料。 |
IEditDimensionProperties | Edits the selected dimension. | 编辑选定的尺寸。 |
IGet3rdPartyStorageStore | Gets the IStorage interface to the specified storage in this model document. | 获取此模型文档中指定存储的 IStorage 接口。 |
IGetAnnotations | Gets the annotations on this model. | 获取此模型上的注释。 |
IGetAnnotationViews | Gets the annotation views in this part or assembly document. | 获取此零件或装配体文档中的注释视图。 |
IGetAttachments | Gets the attachments for this document. | 获取此文档的附件。 |
IGetDecals | Gets the decals applied to the model. | 获取应用于模型的贴花。 |
IGetFlattenSheetMetalPersistReference | Gets a byte array of persistent reference IDs for the specified entity (a face, edge, or vertex) in a flattened sheet metal part. | 获取展平钣金零件中指定实体(面、边或顶点)的持久参考 ID 的字节数组。 |
IGetMaterialPropertyValues | Gets the material properties for this model. | 获取此模型的材料属性。 |
IGetModelViews | Gets the model views in this document. | 获取此文档中的模型视图。 |
IGetNamedViewRotation | Gets the specified named view orientation matrix with respect to the Front view. | 获取相对于前视图的指定命名视图方向矩阵。 |
IGetObjectByPersistReference3 | Gets the object assigned to the specified persistent reference ID. | 获取分配给指定持久引用 ID 的对象。 |
IGetOLEObjects | Get the OLE objects. | 获取 OLE 对象。 |
IGetPersistReference3 | Gets the persistent reference ID for the specified object in this model document. | 获取此模型文档中指定对象的持久引用 ID。 |
IGetSearchData | Gets the SOLIDWORKS Search, third-party, application keywords from the model document. | 从模型文档中获取 SOLIDWORKS Search、第三方应用程序关键字。 |
IGetSectionProperties2 | Gets the section properties for the following types of selected items: Planar model face in any document、Face on a section plane、Crosshatch section face in a section view in a drawing a sketch、Sketch | 获取以下类型选定项的截面属性:任何文档中的平面模型面、截面平面上的面、绘图中截面视图中的剖面线截面面、草图、草图 |
IGetSheetMetalObjectsByPersistReference | Gets the object, or objects, in a folded sheet metal part that correspond to the byte array of persistent reference IDs of an entity in a flattened sheet metal part. | 获取折叠钣金零件中的一个或多个对象,这些对象与展平钣金零件中实体的持久引用 ID 的字节数组相对应。 |
IListExternalFileReferences | Gets the names and statuses of the external file references on this part or assembly. | 获取此零件或装配体上的外部文件参考的名称和状态。 |
InsertAnnotationFavorite | Inserts annotations from the specified favorite file at the specified location. | 在指定位置插入来自指定收藏夹文件的注释。 |
InsertAnnotationView | Inserts an annotation view in this part or assembly document. | 在此零件或装配体文档中插入注释视图。 |
InsertAttachment | Inserts a file as an Attachment to this document. | 将文件作为附件插入到此文档中。 |
InsertBOMBalloon2 | Inserts a BOM balloon for the selected item. | 为所选项目插入 BOM 气球。 |
InsertBomTable3 | Inserts a bill of materials (BOM) table in a part or assembly document. | 在零件或装配体文档中插入物料清单 (BOM) 表。 |
InsertCamera | Inserts a camera in this document. | 在此文档中插入相机。 |
InsertDatumTargetSymbol3 | Creates a datum target symbol. | 创建基准目标符号。 |
InsertDeleteFace | Inserts a DeleteFace feature. | 插入 DeleteFace 特征。 |
InsertGeneralTableAnnotation | Inserts the a general table annotation in this model document. | 在此模型文档中插入通用表格注释。 |
InsertGeneralToleranceTableAnnotation | Inserts a general tolerance table annotation in this model document. | 在此模型文档中插入通用公差表注释。 |
InsertObjectFromFile | Inserts an OLE object from a file. | 从文件中插入 OLE 对象。 |
InsertScene | Applies the specified scene to the model. | 将指定的场景应用于模型。 |
InsertStackedBalloon2 | Inserts a stack of balloons for selected items. | 为所选项目插入一叠气球。 |
InsertSurfaceFinishSymbol3 | Creates a surface-finish symbol based on the last selection. | 根据上次选择创建表面处理符号。 |
InsertTitleBlockTable | Inserts a title block table in a part or assembly document. | 在零件或装配体文档中插入标题栏表格。 |
InstallModelColorizer | Installs your implemented interface of the ISwColorContour interface. | 安装您实现的 ISwColorContour 接口。 |
IRelease3rdPartyStorageStore | Releases the third-party IStorage interface from this model document. | 从此模型文档中释放第三方 IStorage 接口。 |
IRemoveMaterialProperty | Removes material property values from this model. | 从此模型中删除材料属性值。 |
IsAbbreviatedViewActive | Gets or sets whether the abbreviated view is active. | 获取或设置缩写视图是否处于活动状态。 |
IsConverted | Gets whether the active document was converted to the current release uponing opening but has not yet been saved. | 获取活动文档在打开时是否已转换为当前版本但尚未保存。 |
ISetMaterialPropertyValues | Sets the material property values for this model document. | 设置此模型文档的材料属性值。 |
IsExploded | Gets the name of the exploded view currently shown in the model. | 获取模型中当前显示的分解视图的名称。 |
IsFutureVersion | Gets whether this document is for a future version of SOLIDWORKS. | 获取此文档是否用于 SOLIDWORKS 的未来版本。 |
IsSamePersistentID | Gets whether the two specified objects have the same persistent reference IDs. | 获取两个指定对象是否具有相同的持久引用 ID。 |
IsVirtualComponent3 | Gets the paths to parent assembly components, up to and including the first non-virtual parent, if the model is a virtual component. | 如果模型是虚拟组件,则获取父组件组件的路径,直到并包括第一个非虚拟父组件。 |
JogDimension | Gets or sets whether jog points are on or off on an interactively selected linear or ordinate dimension. | 获取或设置在交互式选择的线性或纵坐标尺寸上是打开还是关闭转折点。 |
ListExternalFileReferences | Gets the names and statuses of the external references on this part or assembly. | 获取此零件或装配体上外部参考的名称和状态。 |
ListExternalFileReferencesCount | Gets the number of external references on the part or assembly. | 获取零件或装配体上的外部参照数。 |
LoadDraftingStandard | Loads a custom drafting standard from a file. | 从文件加载自定义绘图标准。 |
MoveDecal | Moves the decal up or down in the list of decals applied to the model. | 在应用于模型的贴图列表中上下移动贴图。 |
MoveOrCopy | Moves and optionally copies the selected sketch entities or annotations. | 移动并可选择复制选定的草图实体或注解。 |
MultiSelect2 | Selects multiple objects and returns the number of objects selected in the model. | 选择多个对象并返回模型中选择的对象数。 |
PrintOut4 | Prints this document without displaying any dialogs or message boxes. | 打印此文档而不显示任何对话框或消息框。 |
PublishSTEP242File | Exports the SOLIDWORKS MBD 3D part or assembly to a STEP 242 file. | 将 SOLIDWORKS MBD 3D 零件或装配体导出为 STEP 242 文件。 |
PublishTo3DPDF | Creates a 3D PDF for SOLIDWORKS MBD. | 为 SOLIDWORKS MBD 创建 3D PDF。 |
PurgeDisplayState | Purges identical display states so that only unique display states remain. | 清除相同的显示状态,以便只保留唯一的显示状态。 |
RayIntersections | Finds the intersections between the specified set of rays and the specified set of bodies. | 查找指定的一组光线与指定的一组实体之间的交点。 |
Rebuild | Rebuilds the model in assembly and drawing documents and returns the status of the rebuild. | 在装配体和工程图文档中重建模型并返回重建状态。 |
Refresh3DViews | Updates the 3D Views of this part or assembly. | 更新此零件或装配体的 3D 视图。 |
ReJogRunningDimension | Applies jogs where extension lines overlap dimension text in an angular running dimension. | 应用折弯,其中尺寸界线与角度运行尺寸中的尺寸文本重叠。 |
ReleaseStream | Releases a previously obtained stream. | 释放先前获得的流。 |
RemoveMaterialProperty | Removes material property values from this model. | 从此模型中删除材料属性值。 |
RemoveModelColorizer | Removes your installed implemented interface of the ISwColorContour interface. | 删除已安装的 ISwColorContour 接口实现的接口。 |
RemoveTexture2 | Removes the texture from the specified configuration. | 从指定的配置中删除纹理。 |
RemoveTextureByDisplayState | Removes the texture applied to this model in the specified display state. | 移除在指定显示状态下应用于此模型的纹理。 |
RemoveVisibleBox | Removes the visible bounding box set by IModelDocExtension::SetVisibleBox and resets the size of the bounding box to the size calculated by SOLIDWORKS for a part or an assembly. | 移除由 IModelDocExtension::SetVisibleBox 设置的可见边界框,并将边界框的大小重置为 SOLIDWORKS 为零件或装配体计算的大小。 |
RenameDocument | Temporarily renames the selected component using the specified name. | 使用指定的名称临时重命名选定的组件。 |
RenameDraftingStandard | Rename the current custom drafting to the specifed name. | 将当前自定义绘图重命名为指定名称。 |
ReorderFeature | Moves the specified feature to another location in the FeatureManager design tree of this part or assembly. | 将指定特征移动到该零件或装配体的 FeatureManager 设计树中的另一个位置。 |
ResetStandardViews | Returns all standard model views to their default settings. | 将所有标准模型视图恢复为其默认设置。 |
ReverseDecalsOrder | Reverses the order of the decals on the model. | 颠倒模型上贴花的顺序。 |
RotateOrCopy | Rotates and optionally copies the selected sketch entities or annotations. | 旋转并可选择复制选定的草图实体或注解。 |
RunCommand | Runs the specified SOLIDWORKS command. | 运行指定的 SOLIDWORKS 命令。 |
SaveAs2 | Saves the active document to the specified name in the specified format. | 以指定格式将活动文档保存为指定名称。 |
SaveDeFeaturedFile | Removes all CAD data except the outer surface from a loaded part or assembly document and saves the outer surface as a part. | 从加载的零件或装配体文档中删除除外表面之外的所有 CAD 数据,并将外表面另存为零件。 |
SaveDraftingStandard | Saves the current custom drafting standard to a file. | 将当前自定义绘图标准保存到文件中。 |
SavePackAndGo | Saves the files designated for Pack and Go to either a folder or Zip file. | 将指定用于打包的文件保存到文件夹或 Zip 文件。 |
SaveSelection | Creates a new selection set containing the selected entities. | 创建包含选定实体的新选择集。 |
ScaleOrCopy | Scales and optionally copies the selected sketch items or annotations. | 缩放并可选择复制选定的草图项目或注释。 |
SelectAll | Selects all edges in a part, all components in an assembly, or all entities (by default, sketch entities, dimensions, and annotations) in a drawing. | 选择零件中的所有边线、装配体中的所有零部件或工程图中的所有实体(默认情况下,草图实体、尺寸和注释)。 |
SelectByID2 | Selects the specified entity. | 选择指定的实体。 |
SelectByRay | Selects the first entity of the specified type that is intersected by a ray that starts at the specified point and runs parallel to the specified direction vector within the specified radius. | 选择指定类型的第一个实体,该实体与从指定点开始并在指定半径内平行于指定方向向量的射线相交。 |
SetAdvancedSpotLightProperties | Sets the attenuation-related, advanced properties for the specified SOLIDWORKS spot light in this model. | 为该模型中指定的 SOLIDWORKS 聚光灯设置与衰减相关的高级属性。 |
SetApiUndoObject | Implements an undo object for an add-in application. | 为加载项应用程序实现撤消对象。 |
SetKeepLightInRenderScene | Sets whether to keep a light when the scene changes. | 设置场景变化时是否保持灯光。 |
SetLightEnabledInRender | Sets whether a light is on in this model. | 设置此模型中是否打开灯。 |
SetMaterialPropertyValues | Sets the material property values for this model document. | 设置此模型文档的材料属性值。 |
SetSceneBkgDIBx64 | Sets the background image in 64-bit applications. | 在 64 位应用程序中设置背景图像。 |
SetSunLightAdvancedPropertyValues | Sets the specified sunlight advanced properties. | 设置指定的阳光高级属性。 |
SetSunLightSourcePropertyValues | Sets the property values for a sunlight source. | 设置阳光源的属性值。 |
SetTexture | Applies texture to the specified configuration. | 将纹理应用于指定的配置。 |
SetTextureByDisplayState | Sets the texture applied to this model in the specified display state. | 在指定的显示状态下设置应用于此模型的纹理。 |
SetTopLevelTransparency | Sets the transparency of this part or top-level assembly. | 设置此零件或顶级装配的透明度。 |
SetUserPreferenceDouble | Sets document default user preference values. This method is intended for user preferences of type double. | 设置文档默认用户首选项值。此方法适用于 double 类型的用户首选项。 |
SetUserPreferenceInteger | Sets document default user preference values. This method is intended for user preferences of type integer. | 设置文档默认用户首选项值。此方法适用于整数类型的用户首选项。 |
SetUserPreferenceString | Sets document default user preference values. This method is intended for user preferences of type string. | 设置文档默认用户首选项值。此方法适用于字符串类型的用户首选项。 |
SetUserPreferenceTextFormat | Sets document default user preference values. This method is intended for setting detailing text formats. | 设置文档默认用户首选项值。此方法用于设置详细文本格式。 |
SetUserPreferenceToggle | Sets document default user preference values. This method is intended for user preferences that can be toggled. | 设置文档默认用户首选项值。此方法适用于可以切换的用户首选项。 |
SetVisibleBox | Sets the visible bounding box for Zoom to Fit for a part or an assembly. | 为零件或装配体设置缩放以适合的可见边界框。 |
ShowModelBreakView | Gets whether to show or hide the specified Model Break View in the current configuration of the active model. | 获取是否在活动模型的当前配置中显示或隐藏指定的模型中断视图。 |
ShowSmartMessage | Displays a SOLIDWORKS-style message as a ToolTip in the graphics area and on the status bar. | 在图形区域和状态栏上显示 SOLIDWORKS 样式的消息作为工具提示。 |
SketchBoxSelect | Box selects all of the entities in a sketch within the specified coordinates of the selection box. | 框选择选择框指定坐标内的草图中的所有实体。 |
SketchOffsetOnSurface | Creates a Euclidean sketch offset from selected edges of a face or surface. | 从面或曲面的选定边创建欧几里得草图偏移。 |
StartFormatPainter | Starts the Format Painter. | 启动格式刷。 |
StartRecordingUndoObject | Starts recording the SOLIDWORKS Undo object. | 开始记录 SOLIDWORKS 撤消对象。 |
StopFormatPainter | Stops the Format Painter. | 停止格式刷。 |
Stretch | Stretch the selected entities. | 拉伸选定的实体。 |
UpdateExternalFileReferences | Updates the external files references on this model. | 更新此模型上的外部文件参考。 |
UpdateFrozenFeatures | Updates frozen features of the model. | 更新模型的冻结特征。 |
UpdateRenderMaterialsInSceneGraph | Sets whether to update the appearances in the graphics area in the model. | 设置是否更新模型图形区域的外观。 |
UpdateStandardViews | Changes the specified standard view to the current model view. | 将指定的标准视图更改为当前模型视图。 |
UpdateSunLight | Updates sunlight position, color, and background image. | 更新阳光位置、颜色和背景图像。 |
UpgradeLegacyCThreads | Upgrades cosmetic thread features in this legacy model to the latest cosmetic thread architecture. | 将此旧模型中的装饰螺纹功能升级到最新的装饰螺纹架构。 |
ViewZoomToSheet | Zooms a drawing sheet to its maximum size within the window. | 在窗口内将图纸缩放至其最大尺寸。 |
AddAngularRunningDim
//This example shows how to insert an angular running dimension and get its properties.
//----------------------------------------------------------------------------
// Preconditions:
// 1. Open public_documents\samples\tutorial\advdrawings\foodprocessor.slddrw.
// 2. Open an Immediate window.
//
// Postconditions:
// 1. The specified angular running dimension is inserted into the drawing.
// 2. Inspect the Immediate window.
//
// NOTE: Because the model is used elsewhere, do not save changes to it.
// ---------------------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
namespace AngularRunningDimensions_CSharp.csproj
{
partial class SolidWorksMacro
{
public void Main()
{
ModelDoc2 Part = default(ModelDoc2);
SelectionMgr selmgr = default(SelectionMgr);
DisplayDimension dispdim = default(DisplayDimension);
object dispdimvar;
bool boolstatus = false;
int intstatus;
Part = (ModelDoc2)swApp.ActiveDoc;
boolstatus = Part.Extension.SelectByID2("", "EDGE", 0.163726736787323, 0.199115091463415, 0.00479999999993197, true, 0, null, 0);
boolstatus = Part.Extension.SelectByID2("", "EDGE", 0.220795425811714, 0.179644597560976, 0.00479999999998881, true, 0, null, 0);
dispdimvar = Part.Extension.AddAngularRunningDim(false, true, true, 0.154288188900673, 0.0794194886913027, 0, out intstatus);
Part.Extension.ReJogRunningDimension();
Part.Extension.AlignRunningDimension();
Part.SetPickMode();
boolstatus = Part.Extension.SelectByID2("D2@Sketch31@foodprocessor.SLDDRW", "DIMENSION", 0.0408612062995185, 0.166216670731707, 0, false, 0, null, 0);
selmgr = (SelectionMgr)Part.SelectionManager;
dispdim = (DisplayDimension)selmgr.GetSelectedObject6(1, -1);
Debug.Print("Display chained angular dimensions? " + dispdim.DisplayAsChain);
Debug.Print("Run the angular dimensions bidirectionally? " + dispdim.RunBidirectionally);
Debug.Print("Extend extension lines from center of angular running dimension? " + dispdim.ExtensionLineExtendsFromCenterOfSet);
Debug.Print("Are extension lines jogged? " + dispdim.Jogged);
Debug.Print("Extension line style same as leader line style? " + dispdim.ExtensionLineSameAsLeaderStyle);
Debug.Print("Extension line uses document settings? " + dispdim.ExtensionLineUseDocumentDisplay);
}
public SldWorks swApp;
}
}
AddComment
//This example shows how to add a comment to an assembly component.
//----------------------------------------------------------------------------
// Preconditions:
// 1. Open an assembly document.
// 2. Select a component in the FeatureManager design tree.
// 3. Open an Immediate window.
//
// Postconditions: A comment about the selected component is added to the
// document's Comments folder.
// ---------------------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
namespace AddComment_C_.csproj
{
public partial class SolidWorksMacro
{
public void Main()
{
ModelDoc2 swModel;
SelectionMgr swSelMgr;
ModelDocExtension swModelDocExt;
Component2 selComp;
String selCompName;
Comment newComment;
swModel = (ModelDoc2)swApp.ActiveDoc;
swSelMgr = (SelectionMgr)swModel.SelectionManager;
swModelDocExt = swModel.Extension;
selComp = (Component2)swSelMgr.GetSelectedObjectsComponent4(1, -1);
selCompName = selComp.Name2;
newComment = swModelDocExt.AddComment("This component's name is " + selCompName);
}
public SldWorks swApp;
}
}
private void SW_Clear(object sender, RoutedEventArgs e)
{
ModelDoc2 model = ((ModelDoc2)(sld4Handler.SwApp.ActiveDoc));
ModelDocExtension modelDocExtension = model.Extension;
modelDocExtension.AddComment("Comment Demo");
}
CreateAdvancedHoleElementData
//This example shows how to create an Advanced Hole feature.
//----------------------------------------------------------------------------
// Preconditions:
// 1. Verify that the specified part document exists.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Selects near and far side faces of the Advanced Hole.
// 2. Defines an Advanced Hole at a sketch point on the edge of the block
// with the following:
// * Countersink near side element
// * Straight tap near side element
// * Counterbore far side element
// * Straight hole far side element
// 3. Gets some near and far side element data for the Advanced Hole.
// 4. Modifies the near side element array to contain a tapered tap element.
// 5. Deletes the Advanced Hole's defining sketch point on the edge of the block.
// 6. Adds two sketch points and creates two Advanced Holes at those locations
// using the previously defined Advanced Hole.
// 7. Inspect the Immediate window and graphics area.
//
// NOTE: Because the model is used elsewhere, do not save changes.
//----------------------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace CreateAdvancedHole_CSharp
{
public partial class SolidWorksMacro
{
public void Main()
{
ModelDoc2 swModel = default(ModelDoc2);
Feature feat = default(Feature);
bool boolstatus = false;
AdvancedHoleElementData swAdvHole_Near_1 = default(AdvancedHoleElementData);
AdvancedHoleElementData swAdvHole_Near_2 = default(AdvancedHoleElementData);
AdvancedHoleElementData swAdvHole_Near_3 = default(AdvancedHoleElementData);
AdvancedHoleElementData swAdvHole_Far_1 = default(AdvancedHoleElementData);
AdvancedHoleElementData swAdvHole_Far_2 = default(AdvancedHoleElementData);
CountersinkElementData swCounterSinkNear = default(CountersinkElementData);
CounterboreElementData swCounterBoreFar = default(CounterboreElementData);
StraightElementData swStraightHoleFar = default(StraightElementData);
StraightTapElementData swStraightTapNear = default(StraightTapElementData);
TaperedTapElementData swTaperedTapNear = default(TaperedTapElementData);
FeatureManager swFeatureMgr = default(FeatureManager);
double ConvFactorLength = 0;
AdvancedHoleElementData[] advHoleNearArr = new AdvancedHoleElementData[2];
AdvancedHoleElementData[] advHoleFarArr = new AdvancedHoleElementData[2];
AdvancedHoleFeatureData featdata = default(AdvancedHoleFeatureData);
AdvancedHoleElementData[] newNearArr = new AdvancedHoleElementData[2];
AdvancedHoleElementData[] newFarArr = new AdvancedHoleElementData[2];
Feature swSketchFeature = default(Feature);
SelectionMgr swSelectionManager = default(SelectionMgr);
Sketch swSketch = default(Sketch);
object[] swSketchPointArray = null;
int swMaxPointNumber = 0;
object skPoint = null;
object swSketchPoint = null;
int swCurrentPointNumber = 0;
int errors = 0;
int warnings = 0;
object ResultArray = null;
string CalloutString = null;
string StrDiam = null;
string strDepth = null;
object[] nearSide = null;
object[] farSide = null;
bool retval = false;
swModel = swApp.OpenDoc6("C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\block20.sldprt", (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
swFeatureMgr = swModel.FeatureManager;
//Conversion from inches to meters
ConvFactorLength = 25.4 / 1000;
//Select two faces for the near side and far side hole elements
boolstatus = swModel.Extension.SelectByRay(-0.0589202612791269, 0.0260626824463657, 0.0560000000000969, -0.400036026779312, -0.515038074910024, -0.758094294050284, 0.000722831189342222, 2, false, 256,
0);
//Near side
boolstatus = swModel.Extension.SelectByRay(-0.0110716643645077, 0.0211784489308116, -0.0639370439421896, 0.18261953966356, -0.612697461661826, 0.76892907618728, 0.000936301020408163, 2, false, 512,
0);
//Far side
//Define near and far side hole elements
//Near side countersink
swAdvHole_Near_1 = (AdvancedHoleElementData)swModel.Extension.CreateAdvancedHoleElementData((int)swAdvWzdGeneralHoleTypes_e.swAdvWzdCounterSink);
swAdvHole_Near_1.Orientation = (int)swHoleElementOrientation_e.swHoleElementOrientation_Nearside;
swAdvHole_Near_1.Size = "#4";
swAdvHole_Near_1.Standard = 0;
swAdvHole_Near_1.FastenerType = (int)swWzdHoleStandardFastenerTypes_e.swStandardAnsiInchFlatHead100;
swAdvHole_Near_1.Diameter = ConvFactorLength * 0.225;
swAdvHole_Near_1.BlindDepth = 0.02055794 * ConvFactorLength;
swAdvHole_Near_1.EndCondition = (int)swEndConditions_e.swEndCondBlind;
swCounterSinkNear = (CountersinkElementData)swAdvHole_Near_1;
swCounterSinkNear.EndConditionOverride = true;
swCounterSinkNear.AngleOverride = false;
//Near side straight tap
swAdvHole_Near_2 = (AdvancedHoleElementData)swModel.Extension.CreateAdvancedHoleElementData((int)swAdvWzdGeneralHoleTypes_e.swAdvWzdStraightTap);
swAdvHole_Near_2.Size = "#4-40";
swAdvHole_Near_2.Standard = (int)swWzdHoleStandards_e.swStandardAnsiInch;
swAdvHole_Near_2.FastenerType = (int)swWzdHoleStandardFastenerTypes_e.swStandardAnsiInchBottomingTappedHole;
swAdvHole_Near_2.Diameter = ConvFactorLength * 0.089;
swAdvHole_Near_2.EndCondition = (int)swEndConditions_e.swEndCondUpToNext;
swAdvHole_Near_2.DiameterOverride = true;
swStraightTapNear = (StraightTapElementData)swAdvHole_Near_2;
swStraightTapNear.CustomSizing = (int)swStraightTapHoleCustomSizing_e.swStraightTapHoleCustomSizing_TapDrillDiameter;
swStraightTapNear.ThreadClass = (int)swStraightTapHoleThreadClass_e.swStraightTapHoleThreadClass_1B;
swStraightTapNear.ThreadClassOverride = true;
//Near side tapered tap
swAdvHole_Near_3 = (AdvancedHoleElementData)swModel.Extension.CreateAdvancedHoleElementData((int)swAdvWzdGeneralHoleTypes_e.swAdvWzdTaperTap);
swAdvHole_Near_3.Orientation = (int)swHoleElementOrientation_e.swHoleElementOrientation_Nearside;
swAdvHole_Near_3.Size = "1/16";
swAdvHole_Near_3.Standard = (int)swWzdHoleStandards_e.swStandardAnsiInch;
swAdvHole_Near_3.FastenerType = (int)swWzdHoleStandardFastenerTypes_e.swStandardAnsiInchTaperedPipeTap;
swAdvHole_Near_3.Diameter = ConvFactorLength * 0.266;
swAdvHole_Near_2.BlindDepth = 0.205 * ConvFactorLength;
swAdvHole_Near_3.EndCondition = (int)swEndConditions_e.swEndCondBlind;
swAdvHole_Near_3.DiameterOverride = true;
swTaperedTapNear = (TaperedTapElementData)swAdvHole_Near_3;
swTaperedTapNear.CustomSizing = (int)swTaperedTapCustomSizing_e.swTaperedTapCustomSizing_MinorDiameterWithCosmeticThread;
swTaperedTapNear.ThreadClass = (int)swTaperedTapThreadClass_e.swTaperedTapThreadClass_1;
swTaperedTapNear.ThreadClassOverride = true;
swTaperedTapNear.EndConditionOverride = true;
//Far side counterbore
swAdvHole_Far_1 = (AdvancedHoleElementData)swModel.Extension.CreateAdvancedHoleElementData((int)swAdvWzdGeneralHoleTypes_e.swAdvWzdCounterBore);
swAdvHole_Far_1.Orientation = (int)swHoleElementOrientation_e.swHoleElementOrientation_Farside;
swAdvHole_Far_1.Size = "#8";
swAdvHole_Far_1.Standard = (int)swWzdHoleStandards_e.swStandardAnsiInch;
swAdvHole_Far_1.FastenerType = (int)swWzdHoleStandardFastenerTypes_e.swStandardAnsiInchBinding;
swAdvHole_Far_1.Diameter = ConvFactorLength * 0.375;
swAdvHole_Far_1.BlindDepth = 0.105 * ConvFactorLength;
swAdvHole_Far_1.EndCondition = (int)swEndConditions_e.swEndCondBlind;
swAdvHole_Far_1.DiameterOverride = true;
swCounterBoreFar = (CounterboreElementData)swAdvHole_Far_1;
swCounterBoreFar.EndConditionOverride = true;
//Far side straight
swAdvHole_Far_2 = (AdvancedHoleElementData)swModel.Extension.CreateAdvancedHoleElementData((int)swAdvWzdGeneralHoleTypes_e.swAdvWzdStraight);
swAdvHole_Far_2.Size = "1/16";
swAdvHole_Far_2.Standard = 0;
swAdvHole_Far_2.FastenerType = (int)swWzdHoleStandardFastenerTypes_e.swStandardAnsiInchAllDrillSizes;
swAdvHole_Far_2.Diameter = ConvFactorLength * 0.0625;
swAdvHole_Far_2.BlindDepth = 0.2711 * ConvFactorLength;
swAdvHole_Far_2.EndCondition = (int)swEndConditions_e.swEndCondBlind;
swAdvHole_Far_2.DiameterOverride = true;
//Customize the hole callout for this straight element
StrDiam = swModel.Extension.GetCalloutVariableString((int)swCalloutVariable_e.swCalloutVariable_AH_Straight_Diameter);
strDepth = swModel.Extension.GetCalloutVariableString((int)swCalloutVariable_e.swCalloutVariable_AH_Straight_Depth);
CalloutString = "<MOD-DIAM> " + StrDiam + " " + "<HOLE-DEPTH> " + strDepth;
swAdvHole_Far_2.CalloutString = CalloutString;
swStraightHoleFar = (StraightElementData)swAdvHole_Far_2;
//Set near and far side element arrays
advHoleNearArr[0] = (AdvancedHoleElementData)swCounterSinkNear;
advHoleNearArr[1] = (AdvancedHoleElementData)swStraightTapNear;
advHoleFarArr[0] = (AdvancedHoleElementData)swCounterBoreFar;
advHoleFarArr[1] = (AdvancedHoleElementData)swStraightHoleFar;
DispatchWrapper[] dispArray = ObjectArrayToDispatchWrapperArray(new object[] { advHoleNearArr[0], advHoleNearArr[1] });
DispatchWrapper[] dispArray2 = ObjectArrayToDispatchWrapperArray(new object[] { advHoleFarArr[0], advHoleFarArr[1] });
//Create the Advanced Hole using the near and far side element arrays; specify to not use baseline dimensions; customize Hole Callouts
feat = swFeatureMgr.AdvancedHole(dispArray, dispArray2, false, true, out ResultArray);
//Get some near and far side element data
featdata = (AdvancedHoleFeatureData)feat.GetDefinition();
featdata.AccessSelections(swModel, null);
Debug.Print("Number of near side hole elements: " + featdata.NearSideElementsCount);
Debug.Print("Number of far side hole elements: " + featdata.FarSideElementsCount);
nearSide = (object[])featdata.GetNearSideElements();
swCounterSinkNear = (CountersinkElementData)nearSide[0];
farSide = (object[])featdata.GetFarSideElements();
swCounterBoreFar = (CounterboreElementData)farSide[0];
swStraightHoleFar = (StraightElementData)farSide[1];
Debug.Print("Near side countersink:");
Debug.Print(" Hole element type as defined in swAdvWzdGeneralHoleTypes_e: " + ((AdvancedHoleElementData)swCounterSinkNear).ElementType);
Debug.Print(" Size as defined on the Advanced Hole PropertyManager page: " + ((AdvancedHoleElementData)swCounterSinkNear).Size);
Debug.Print(" Standard as defined in swWzdHoleStandards_e: " + ((AdvancedHoleElementData)swCounterSinkNear).Standard);
Debug.Print(" Fastener type as defined in swWzdHoleStandardFastenerTypes_e: " + ((AdvancedHoleElementData)swCounterSinkNear).FastenerType);
Debug.Print(" Diameter in m: " + ((AdvancedHoleElementData)swCounterSinkNear).Diameter);
Debug.Print(" Blind depth in m: " + ((AdvancedHoleElementData)swCounterSinkNear).BlindDepth);
Debug.Print(" Orientation as defined in swHoleElementOrientation_e: " + ((AdvancedHoleElementData)swCounterSinkNear).Orientation);
Debug.Print(" End condition as defined in swEndConditions_e: " + ((AdvancedHoleElementData)swCounterSinkNear).EndCondition);
Debug.Print("Far side straight:");
Debug.Print(" Hole element type as defined in swAdvWzdGeneralHoleTypes_e: " + ((AdvancedHoleElementData)swStraightHoleFar).ElementType);
Debug.Print(" Size as defined on the Advanced Hole PropertyManager page: " + ((AdvancedHoleElementData)swStraightHoleFar).Size);
Debug.Print(" Standard as defined in swWzdHoleStandards_e: " + ((AdvancedHoleElementData)swStraightHoleFar).Standard);
Debug.Print(" Fastener type as defined in swWzdHoleStandardFastenerTypes_e: " + ((AdvancedHoleElementData)swStraightHoleFar).FastenerType);
Debug.Print(" Diameter in m: " + ((AdvancedHoleElementData)swStraightHoleFar).Diameter);
Debug.Print(" Diameter override? " + ((AdvancedHoleElementData)swStraightHoleFar).DiameterOverride);
Debug.Print(" Blind depth in m: " + ((AdvancedHoleElementData)swStraightHoleFar).BlindDepth);
Debug.Print(" End condition as defined in swEndConditions_e: " + ((AdvancedHoleElementData)swStraightHoleFar).EndCondition);
Debug.Print(" Customized hole callout: " + ((AdvancedHoleElementData)swStraightHoleFar).CalloutString);
//Modify the near and far side element arrays
newNearArr[0] = (AdvancedHoleElementData)swTaperedTapNear;
newNearArr[1] = (AdvancedHoleElementData)swStraightTapNear;
//newFarArr[0] = (AdvancedHoleElementData)swCounterBoreFar;
//newFarArr[1] = (AdvancedHoleElementData)swStraightHoleFar;
featdata.SetNearSideElements(newNearArr);
//featdata.SetFarSideElements(newFarArr);
feat.ModifyDefinition(featdata, swModel, null);
//Delete the first point used to define the Advanced Hole
swSketchFeature = (Feature)feat.GetFirstSubFeature();
swSketchFeature.Select2(false, 0);
swModel.EditSketch();
swSelectionManager = (SelectionMgr)swModel.SelectionManager;
swSketch = (Sketch)swSketchFeature.GetSpecificFeature2();
swSketchPointArray = (object[])swSketch.GetSketchPoints2();
swMaxPointNumber = swSketchPointArray.GetUpperBound(0);
for (swCurrentPointNumber = 0; swCurrentPointNumber <= swMaxPointNumber; swCurrentPointNumber += 1)
{
swSketchPoint = swSketchPointArray[swCurrentPointNumber];
retval = swSelectionManager.AddSelectionListObject(swSketchPoint, null);
swModel.EditDelete();
}
//Create points for multiple Advanced Hole locations
skPoint = swModel.SketchManager.CreatePoint(-0.0319158789518497, 0.0344489966898323, 0.05600000000004);
skPoint = swModel.SketchManager.CreatePoint(-0.0494104502066557, 0.0080156770060853, 0.0560000000000969);
swModel.SketchManager.InsertSketch(true);
}
public DispatchWrapper[] ObjectArrayToDispatchWrapperArray(object[] Objects)
{
int ArraySize = 0;
ArraySize = Objects.GetUpperBound(0);
DispatchWrapper[] d = new DispatchWrapper[ArraySize + 1];
int ArrayIndex = 0;
for (ArrayIndex = 0; ArrayIndex <= ArraySize; ArrayIndex++)
{;
d[ArrayIndex] = new DispatchWrapper(Objects[ArrayIndex]);
}
return d;
}
// The SldWorks swApp variable is pre-assigned for you.
public SldWorks swApp;
}
}
CreateBalloonOptions
此示例显示如何在工程图文档中插入材料明细表 (BOM) 表和零件序号。
//----------------------------------------------------------------------------
// 先决条件:
// 1. 指定的文件和模板存在。
// 2. 打开一个即时窗口。
//
// 后置条件:
// 1. 插入一个缩进的 BOM 表。
// 2. 插入 BOM 球标注释。
// 3. 检查立即窗口的 BOM 特征属性。
//
// 注意:因为该图在别处使用,所以不要保存任何更改
//---------------------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
namespace IViewInsertBomTable4CSharp.csproj
{
partial class SolidWorksMacro
{
public void Main()
{
ModelDoc2 swModel = default(ModelDoc2);//通用文档
ModelDocExtension swModelDocExt = default(ModelDocExtension);//通用文档扩展
DrawingDoc swDrawing = default(DrawingDoc);//工程图
View swView = default(View);//视图
BomTableAnnotation swBOMAnnotation = default(BomTableAnnotation);//BOM注释
BomFeature swBOMFeature = default(BomFeature);//BOM
Note swNote = default(Note);//注释
BalloonOptions BomBalloonParams = default(BalloonOptions);//气球
bool boolstatus = false;
int AnchorType = 0;
int NbrType = 0;
int BomType = 0;
int nErrors = 0;
int nWarnings = 0;
string Configuration = null;
string TableTemplate = null;
swModel = (ModelDoc2)swApp.OpenDoc6("C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\advdrawings\\foodprocessor.slddrw", (int)swDocumentTypes_e.swDocDRAWING, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref nErrors, ref nWarnings);//获取打开文档
swDrawing = (DrawingDoc)swModel;//工程图
swModelDocExt = (ModelDocExtension)swModel.Extension;//文档扩展
boolstatus = swDrawing.ActivateView("Drawing View1");//获取成功为true
swView = (View)swDrawing.ActiveDrawingView; //视图
// 插入缩进的 BOM 表
AnchorType = (int)swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_TopLeft;//表格固定类型
BomType = (int)swBomType_e.swBomType_Indented; //BOM表类型
NbrType = (int)swNumberingType_e.swNumberingType_Detailed;//编号类型
TableTemplate = "C:\\Program Files\\SOLIDWORKS Corp\\SOLIDWORKS\\lang\\english\\bom-standard.sldbomtbt";//BOM模板
Configuration = "";//配置
swBOMAnnotation = (BomTableAnnotation)swView.InsertBomTable4(false, 0.4, 0.3, AnchorType, BomType, Configuration, TableTemplate, false, NbrType, true);//BOM注解
swBOMFeature = (BomFeature)swBOMAnnotation.BomFeature;//BOM
Debug.Print("swBomType_e 中定义的 BOM 表类型: " + (int)swBOMFeature.TableType);
Debug.Print("swNumberingType_e 中定义的 BOM 表编号类型:" + (int)swBOMFeature.NumberingTypeOnIndentedBOM);
Debug.Print("当 swZeroQuantityDisplay_e 中定义的值为 0 时显示的值: " + (int)swBOMFeature.ZeroQuantityDisplay);
Debug.Print("用于 BOM 表的配置名称: " + swBOMFeature.Configuration);
Debug.Print("显示为一项? " + swBOMFeature.DisplayAsOneItem);
Debug.Print("序列起始编号: " + swBOMFeature.SequenceStartNumber);
Debug.Print("保留遗失的项目?" + swBOMFeature.KeepMissingItems);
Debug.Print("删除遗失的项目? " + swBOMFeature.StrikeoutMissingItems);
Debug.Print("替换 swKeepReplacedCompOption_e 中定义的缺失组件: " + swBOMFeature.KeepReplacedCompOption);
Debug.Print("重新排序行时保留当前项目编号?" + swBOMFeature.KeepCurrentItemNumbers);
boolstatus = swModelDocExt.SelectByID2("", "EDGE", 0.1205506330468, 0.261655309417, -0.0004000000000133, false, 0, null, 0);//选择实体
BomBalloonParams = swModelDocExt.CreateBalloonOptions();//创建气球
BomBalloonParams.Style = (int)swBalloonStyle_e.swBS_Circular;//气球样式
BomBalloonParams.Size = (int)swBalloonFit_e.swBF_2Chars;//气球内文本字数
BomBalloonParams.UpperTextContent = (int)swBalloonTextContent_e.swBalloonTextItemNumber;//气球文本内容
BomBalloonParams.ShowQuantity = true;//显示数量
BomBalloonParams.QuantityPlacement = (int)swBalloonQuantityPlacement_e.swBalloonQuantityPlacement_Right;//数量放置位置
BomBalloonParams.QuantityDenotationText = "PLACES";//Denotation
BomBalloonParams.QuantityOverride = false; //是否覆盖
BomBalloonParams.QuantityOverrideValue = "";//覆盖值
BomBalloonParams.ItemNumberStart = 1;//起始编号
BomBalloonParams.ItemNumberIncrement = 1;//增量
BomBalloonParams.ItemOrder = (int)swBalloonItemNumbersOrder_e.swBalloonItemNumbers_DoNotChangeItemNumbers;//不要更改项目编号
swNote = (Note)swModelDocExt.InsertBOMBalloon2(BomBalloonParams);//插入BOM气球编号
if (swNote.IsBomBalloon())
{
Debug.Print("Name of BOM balloon: " + swNote.GetName());
}
swDrawing.ForceRebuild();
}
public SldWorks swApp;
}
}
CreateCallout
//此示例显示如何创建独立于选择的标注。
//---------------------------------------------------------------------------
// 前提条件:
// 1. 打开一个模型文档。
// 2. 单击 .NET 选项卡上的项目 > 添加参考 > SolidWorks.interop.swpublished。
// 3. 重命名此宏的命名空间以匹配您的 C# 项目的名称。
//
// 后置条件:
// 1. 创建具有指定属性的标注。
// 2. 检查立即窗口的文本格式属性。
//--------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using SolidWorks.Interop.swpublished;
using System.Diagnostics;
namespace CreateCallout_CSharp.csproj
{
partial class SolidWorksMacro
{
ModelDoc2 swModel;//通用文档
ModelDocExtension swExt;//通用文档扩展
SelectionMgr swSelMgr;//选择管理器
MathUtility mathUtil;//数学实用程序
public void Main()
{
swModel = (ModelDoc2)swApp.ActiveDoc;//通用文档
swExt = swModel.Extension;//通用文档扩展
swSelMgr = (SelectionMgr)swModel.SelectionManager;//选择管理器
mathUtil = (MathUtility)swApp.GetMathUtility();//数学实用程序
calloutHandler handle = new calloutHandler();//标注处理程序
MathPoint mp;//点
double[] vPnt = new double[3];
vPnt[0] = 0.0;
vPnt[1] = 0.0;
vPnt[2] = 0.0;
mp = (MathPoint)mathUtil.CreatePoint(vPnt);
Callout myCallout;//创建标注
myCallout = swExt.CreateCallout(2, handle);
myCallout.set_Value(1, "");//值
myCallout.set_IgnoreValue(1, true);//忽略值
myCallout.set_Label2(1, "SldWorks API");//label
myCallout.SkipColon = true;//跳过冒号
myCallout.SetLeader(true, true);//设置Leader
myCallout.SetTargetPoint(1, 0.001, 0.001, 0);//设置目标点
myCallout.SetTargetPoint(2, -0.001, 0.001, 0);//设置目标点
myCallout.Position = mp;//位置
myCallout.set_ValueInactive(0, true);//无效值
myCallout.TextBox = false;//TextBox
myCallout.Display(true);//显示
TextFormat swTextFormat = myCallout.TextFormat;
ProcessTextFormat(swApp, swModel, swTextFormat);
}
public void ProcessTextFormat(SldWorks swApp, ModelDoc2 swModel, TextFormat swTextFormat)
{
Debug.Print(" BackWards = " + swTextFormat.BackWards);
Debug.Print(" Bold = " + swTextFormat.Bold);
Debug.Print(" CharHeight = " + swTextFormat.CharHeight);
Debug.Print(" CharHeightInPts = " + swTextFormat.CharHeightInPts);
Debug.Print(" CharSpacingFactor = " + swTextFormat.CharSpacingFactor);
Debug.Print(" Escapement = " + swTextFormat.Escapement);
Debug.Print(" IsHeightSpecifiedInPts = " + swTextFormat.IsHeightSpecifiedInPts());
Debug.Print(" Italic = " + swTextFormat.Italic);
Debug.Print(" LineLength = " + swTextFormat.LineLength);
Debug.Print(" LineSpacing = " + swTextFormat.LineSpacing);
Debug.Print(" ObliqueAngle = " + swTextFormat.ObliqueAngle);
Debug.Print(" Strikeout = " + swTextFormat.Strikeout);
Debug.Print(" TypeFaceName = " + swTextFormat.TypeFaceName);
Debug.Print(" Underline = " + swTextFormat.Underline);
Debug.Print(" UpsideDown = " + swTextFormat.UpsideDown);
Debug.Print(" Vertical = " + swTextFormat.Vertical);
Debug.Print(" WidthFactor = " + swTextFormat.WidthFactor);
Debug.Print("");
}
public SldWorks swApp;
}
[System.Runtime.InteropServices.ComVisible(true)]
public class calloutHandler : SwCalloutHandler
{
#region ISwCalloutHandler Members
bool ISwCalloutHandler.OnStringValueChanged(object pManipulator, int RowID, string Text)
{
Debug.Print("Text: " + Text);
Debug.Print("Row: " + RowID.ToString());
return true;
}
#endregion
}
}
CreateMassProperty
此示例显示如何获取和覆盖零件的某些质量属性。
//-----------------------------------------------------------------------
// 前提条件:
// 1. 确保指定的文档存在。
// 2. 打开立即窗口。
//
// 后置条件: 检查立即窗口以了解零件的质量属性。
//----------------------------------------------------------------------
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 OverrideMassProperties_CSharp.csproj
{
partial class SolidWorksMacro
{
ModelDocExtension Extn; //通用文档扩展
MassProperty MyMassProp; //质量属性
ModelDoc2 swModelDoc; //通用文档
double[] pmoi;
double[] vValue;
object com;
double[] value = new double[3];
int errors;
int warnings;
double val;
double[] @params;
public void Main()
{
swModelDoc = swApp.OpenDoc6("C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\MassPropertiesDemo.sldprt", (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);//通用文档
Extn = swModelDoc.Extension;//通用文档扩展
// 创建质量属性
MyMassProp = Extn.CreateMassProperty();
// 使用文档属性单位 (MKS)
MyMassProp.UseSystemUnits = false;
val = MyMassProp.Volume;//体积
Debug.Print("Volume: " + val);
val = MyMassProp.Density;//密度
Debug.Print("Density: " + val);
val = MyMassProp.SurfaceArea;//表面积
Debug.Print("Surface area: " + val);
Debug.Print("");
Debug.Print("覆盖质量属性设置为" + MyMassProp.OverrideMass);
Debug.Print("质量被覆盖?" + MyMassProp.SetOverrideMassValue(100.0, (int)swInConfigurationOpts_e.swThisConfiguration, null));
val = MyMassProp.Mass;
Debug.Print("Mass: " + val);
Debug.Print("");
Debug.Print("覆盖质量中心属性设置为" + MyMassProp.OverrideCenterOfMass);
value[0] = 0.09;
value[1] = 0.05;
value[2] = 0.06;
com = value;
Debug.Print("重心被覆盖?" + MyMassProp.SetOverrideCenterOfMassValue((com), "Coordinate System1", (int)swInConfigurationOpts_e.swThisConfiguration, null));
@params = (double[])MyMassProp.CenterOfMass;
Debug.Print("质心:X:" + @params[0] + ", Y: " + @params[1] + ", and Z: " + @params[2]);
Debug.Print("");
Debug.Print("惯性矩属性设置为:" + MyMassProp.OverrideMomentsOfInertia);
pmoi = (double[])MyMassProp.PrincipleMomentsOfInertia;
Debug.Print("主转动惯量 : Px: " + pmoi[0] + ", Py: " + pmoi[1] + ", and Pz: " + pmoi[2]);
pmoi[0] = 0.14;
Debug.Print("主转动惯量被覆写? " + MyMassProp.SetOverridePrincipleMomentsOfInertia((pmoi), (int)swInConfigurationOpts_e.swThisConfiguration, null));
pmoi = (double[])MyMassProp.PrincipleMomentsOfInertia;
Debug.Print("主转动惯量被覆写后: Px: " + pmoi[0] + ", Py: " + pmoi[1] + ", and Pz: " + pmoi[2]);
vValue = (double[])MyMassProp.GetMomentOfInertia(0);
Debug.Print("惯性矩被覆盖前: Lxx: " + vValue[0] + ", Lxy: " + vValue[1] + ", Lxz: " + vValue[2] + ", Lyx: " + vValue[3] + ", Lyy: " + vValue[4] + ", Lyz: " + vValue[5] + ", Lzx: " + vValue[6] + ", Lzy: " + vValue[7] + ", Lzz: " + vValue[8]);
Debug.Print("惯性矩被覆盖? " + MyMassProp.SetOverrideMomentsOfInertiaValue((int)swMomentsOfInertiaReferenceFrame_e.swMomentsOfInertiaReferenceFrame_UserCoordinateSystem, "Coordinate System1", (vValue), (int)swInConfigurationOpts_e.swThisConfiguration, null));
vValue[0] = 0.1;
Debug.Print("惯性矩被覆盖后: Lxx: " + vValue[0] + ", Lxy: " + vValue[1] + ", Lxz: " + vValue[2] + ", Lyx: " + vValue[3] + ", Lyy: " + vValue[4] + ", Lyz: " + vValue[5] + ", Lzx: " + vValue[6] + ", Lzy: " + vValue[7] + ", Lzz: " + vValue[8]);
}
public SldWorks swApp;
}
}
//此示例说明如何获取在其中创建了装配体切割拉伸特征的多体装配体零部件的质量属性。
//一个装配组件,例如一个零件或子装配,可以包含一个或多个装配级特征。 某些类型的装配特征(例如切割拉伸)会影响质量属性。 零件或子装配体中不存在装配体特征。
//返回的质量属性值相对于零部件原点,而不是装配原点。
//---------------------------------------------------------------
// 前提条件:
// 1.验证指定的多实体零件文档和装配体文档模板是否存在。
// 2. 打开立即窗口。
//
// 后置条件:
// 1. 打开指定的多实体零件文档。
// 2. 使用指定的多实体零件文档创建装配体。
// 3. 创建装配体切割拉伸特征。
// 4. 选择多实体组件。
// 5. 获取多体组件的质量属性值。
// 6. 检查立即窗口。
//
// 注意:因为零件在别处使用,所以不要保存更改。
//---------------------------------------------------------------
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);//装配体文档
ModelDocExtension swDocExt = default(ModelDocExtension);//通用文档扩展
MassProperty swMass = default(MassProperty);//质量属性
SelectionMgr swSelMgr = default(SelectionMgr);//选择管理器
Component2 swComp = default(Component2);//部件
SketchManager swSketchMgr = default(SketchManager);//草图管理器
SketchSegment swSketchSegment = default(SketchSegment);
FeatureManager swFeatMgr = default(FeatureManager);//特征管理器
Feature swFeat = default(Feature);//特征
object vBodyInfo = null;
double[] vCoM = null;
double[] vMoI = null;
double[] vPrinAoIx = null;
double[] vPrinAoIy = null;
double[] vPrinAoIz = null;
double[] vPrinMoI = null;
bool bRet = false;
int errors = 0;
int warnings = 0;
//打开多实体零件文档并创建装配体
swModel = (ModelDoc2)swApp.OpenDoc6("C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\multibody\\multi_inter.sldprt", (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);//通用文档
swModel = (ModelDoc2)swApp.NewDocument("C:\\ProgramData\\SolidWorks\\SolidWorks 2017\\templates\\Assembly.asmdot", 0, 0, 0);//通用文档
swAssembly = (AssemblyDoc)swModel;//装配体文档
swComp = (Component2)swAssembly.AddComponent5("C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\multibody\\multi_inter.sldprt", (int)swAddComponentConfigOptions_e.swAddComponentConfigOptions_CurrentSelectedConfig, "", false, "", -9.26777909171506E-05, 0, 4.8904806817518E-05);//部件
//创建装配体切割拉伸特征
swDocExt = (ModelDocExtension)swModel.Extension;//通用文档扩展
swSketchMgr = (SketchManager)swModel.SketchManager;//草图管理器
swFeatMgr = (FeatureManager)swModel.FeatureManager;//特征管理器
bRet = swDocExt.SelectByID2("", "FACE", -0.0195381300573558, 0.0449999999998454, -0.00303401890568011, false, 0, null, 0);//选择实体
swModel.ClearSelection2(true);
swSketchSegment = (SketchSegment)swSketchMgr.CreateCircle(0.0, 0.0, 0.0, 0.002956, -0.004701, 0.0);//草图段
swModel.ClearSelection2(true);
bRet = swDocExt.SelectByID2("Arc1", "SKETCHSEGMENT", 0, 0, 0, false, 0, null, 0);//实体
swFeat = (Feature)swFeatMgr.FeatureCut3(true, false, false, 0, 0, 0.5, 0.00254, false, false, false,
false, 0.0174532925199433, 0.0174532925199433, false, false, false, false, false, true, true,
true, true, false, 0, 0, false);//切除
swSelMgr = (SelectionMgr)swModel.SelectionManager;//选择管理器
swSelMgr.EnableContourSelection = false;
//选择多体组件
bRet = swDocExt.SelectByID2("multi_inter-1@Assem1", "COMPONENT", 0, 0, 0, false, 0, null, 0);//选择实体
swMass = (MassProperty)swDocExt.CreateMassProperty();//质量
swComp = (Component2)swSelMgr.GetSelectedObjectsComponent4(1, -1);
object[] vBodies = new object[1];
vBodies = (object[])swComp.GetBodies3((int)swBodyType_e.swSolidBody, out vBodyInfo);
DispatchWrapper[] dispArray = ObjectArrayToDispatchWrapperArray(vBodies);//调度包装器
bRet = swMass.AddBodies((dispArray));//添加实体
//获取所选组件主体的质量属性
vCoM = (double[])swMass.CenterOfMass;//质心
vMoI = (double[])swMass.GetMomentOfInertia((int)swMassPropertyMoment_e.swMassPropertyMomentAboutCenterOfMass);//惯性矩
vPrinAoIx = (double[])swMass.get_PrincipleAxesOfInertia(0);
vPrinAoIy = (double[])swMass.get_PrincipleAxesOfInertia(1);
vPrinAoIz = (double[])swMass.get_PrincipleAxesOfInertia(2);
vPrinMoI = (double[])swMass.PrincipleMomentsOfInertia;
Debug.Print("零件= " + swComp.Name2);
Debug.Print("配置 = " + swComp.ReferencedConfiguration);
Debug.Print("密度= " + swMass.Density + " kg/m^3");
Debug.Print("");
Debug.Print("质心= (" + vCoM[0] * 1000.0 + ", " + vCoM[1] * 1000.0 + ", " + vCoM[2] * 1000.0 + ") mm");
Debug.Print("体积= " + swMass.Volume * 1000000000.0 + " mm^3");
Debug.Print("区域= " + swMass.SurfaceArea * 1000000.0 + " mm^2");
Debug.Print("质量 = " + swMass.Mass + " kg");
Debug.Print("主轴惯量");
Debug.Print(" Ix = (" + vPrinAoIx[0] + ", " + vPrinAoIx[1] + ", " + vPrinAoIx[2] + ")");
Debug.Print(" Iy = (" + vPrinAoIy[0] + ", " + vPrinAoIy[1] + ", " + vPrinAoIy[2] + ")");
Debug.Print(" Iz = (" + vPrinAoIz[0] + ", " + vPrinAoIz[1] + ", " + vPrinAoIz[2] + ")");
Debug.Print("主惯性矩");
Debug.Print(" Px = " + vPrinMoI[0] + " kg*m^2");
Debug.Print(" Py = " + vPrinMoI[1] + " kg*m^2");
Debug.Print(" Pz = " + vPrinMoI[2] + " kg*m^2");
Debug.Print("惯性矩");
Debug.Print(" Lxx = " + vMoI[0] + " kg*m^2");
Debug.Print(" Lxy = " + vMoI[1] + " kg*m^2");
Debug.Print(" Lxz = " + vMoI[2] + " kg*m^2");
Debug.Print(" Lyx = " + vMoI[3] + " kg*m^2");
Debug.Print(" Lyy = " + vMoI[4] + " kg*m^2");
Debug.Print(" Lyz = " + vMoI[5] + " kg*m^2");
Debug.Print(" Lzx = " + vMoI[6] + " kg*m^2");
Debug.Print(" Lzy = " + vMoI[7] + " kg*m^2");
Debug.Print(" Lzz = " + vMoI[8] + " kg*m^2");
}
public DispatchWrapper[] ObjectArrayToDispatchWrapperArray(object[] Objects)
{
int ArraySize = 0;
ArraySize = Objects.GetUpperBound(0);
DispatchWrapper[] d = new DispatchWrapper[ArraySize + 1];
int ArrayIndex = 0;
for (ArrayIndex = 0; ArrayIndex <= ArraySize; ArrayIndex++)
{
d[ArrayIndex] = new DispatchWrapper(Objects[ArrayIndex]);
}
return d;
}
/// <summary>
/// SldWorks swApp 变量是为您预先分配的
/// </summary>
public SldWorks swApp;
}
}
EditBalloonProperties2
//此示例显示如何在工程图文档中编辑零件序号。
// --------------------------------------------------------------------------
// 前提条件:
// 1.打开 public_documents\samples\tutorial\advdrawings\foodprocessor.slddrw。
// 2.单击插入 > 注释 > 气球。
// 3.在任一图纸视图中单击模型边并添加气球。
// 4.关闭零件序号 PropertyManager 页面。
// 5.选择绘图中的气球。
//
// 后置条件:修改所选气球的属性。
//
// 注意:由于此工程图文档在别处使用,因此在关闭它时不要保存任何更改。
// --------------------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
namespace EditBalloonProperties_CSharp.csproj
{
partial class SolidWorksMacro
{
ModelDoc2 swModel;//文档
ModelDocExtension swModelDocExt;//文档扩展
SelectionMgr swSelMgr;//选择管理器
Note swNote;//注释
public void Main()
{
swModel = (ModelDoc2)swApp.ActiveDoc;//文档
swModelDocExt = swModel.Extension;//文档扩展
swSelMgr = (SelectionMgr)swModel.SelectionManager;//选择管理器
//获取选中的气球
swNote = (Note)swSelMgr.GetSelectedObject6(1, -1);
//编辑选定的气球
swNote = (Note)swModelDocExt.EditBalloonProperties2((int)swBalloonStyle_e.swBS_SplitCirc, (int)swBalloonFit_e.swBF_5Chars, (int)swBalloonTextContent_e.swBalloonTextCustom, "Upper", (int)swBalloonTextContent_e.swBalloonTextCustom, "Lower", 0, true, 1, "X",
0.0355);
Debug.Print("Balloon name: " + swNote.GetName());
}
public SldWorks swApp;
}
}
EditDimensionProperties
//此示例说明如何修改工程图中选定显示尺寸的属性。
//------------------------------------------------------------
// 前提条件:
// 1. 打开一个有一个或多个显示的绘图文档方面。
// 2. 选择一个显示维度。
//
// 后置条件:
// 1. 选中的显示维度的属性按指定修改。
// 2. 检查显示尺寸以进行验证。
// -----------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
namespace ModifyDimensionProperties_CSharp.csproj
{
partial class SolidWorksMacro
{
ModelDoc2 swModel;
ModelDocExtension swModelDocExt;
bool boolstatus;
public void Main()
{
swModel = (ModelDoc2)swApp.ActiveDoc;
swModelDocExt = (ModelDocExtension)swModel.Extension;
boolstatus = swModelDocExt.EditDimensionProperties((int)swTolType_e.swTolBASIC, 0, 0, "", "", true, 9, (int)swDimensionArrowsSide_e.swDimArrowsSmart, false, (int)swArrowStyle_e.swSLASH_ARROWHEAD, (int)swArrowStyle_e.swSLASH_ARROWHEAD, "", "", true, "", "", "Example of lower text", true, (int)swInConfigurationOpts_e.swThisConfiguration, "");//编辑选定的尺寸。
swModel.ClearSelection2(true);//取消选择
}
public SldWorks swApp;
}
}
GetAnnotations
此示例显示如何获取模型的注释。
//----------------------------------------------------------------------------
// 前提条件:
// 1. 打开一个带有一个或多个注释的模型。
// 2. 打开一个立即窗口
//
// 后置条件:所有注释都打印在立即窗口中。
//----------------------------------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
namespace GetAnnotations_CSharp.csproj
{
public partial class SolidWorksMacro
{
public void Main()
{
ModelDoc2 swModel;
ModelDocExtension swModelDocExt;
Annotation swAnnotation;//注释
int iAnnoCnt;
Object[] arrAnnotation;
int IAnnoType;
swModel = (ModelDoc2)swApp.ActiveDoc;
swModelDocExt = (ModelDocExtension)swModel.Extension;
iAnnoCnt = swModelDocExt.GetAnnotationCount();//注释数量
if (iAnnoCnt > 0)
{
arrAnnotation = (Object[])swModelDocExt.GetAnnotations();
for (int i = 0; i <= arrAnnotation.Length - 1; i++)
{
swAnnotation = (Annotation)arrAnnotation[i];
IAnnoType = swAnnotation.GetType();
switch (IAnnoType)
{
case 1:
Debug.Print("Annotation: Thread");
break;
case 2:
Debug.Print("Annotation: Datum Tag");
break;
case 3:
Debug.Print("Annotation: Datum Target Symbol");
break;
case 4:
Debug.Print("Annotation: Display Diamension");
break;
case 5:
Debug.Print("Annotation: Gtol");
break;
case 6:
Debug.Print("Annotation: Note");
break;
case 7:
Debug.Print("Annotation: SFS Symbol");
break;
case 8:
Debug.Print("Annotation: Weld Symbol");
break;
case 9:
Debug.Print("Annotation: Custom Symbol");
break;
case 10:
Debug.Print("Annotation: Dowel Symbol");
break;
case 11:
Debug.Print("Annotation: Leader");
break;
case 12:
Debug.Print("Annotation: Block");
break;
case 13:
Debug.Print("Annotation: Center Mark symbol");
break;
case 14:
Debug.Print("Annotation: Table Annotation");
break;
case 15:
Debug.Print("Annotation: Center Line ");
break;
case 16:
Debug.Print("Annotation: Datum Origin");
break;
}
}
}
}
public SldWorks swApp;
}
}
GetMassProperties2
此示例显示如何检索装配中选定零部件的质量属性。
//----------------------------------------------------------------------------
// 前提条件:
// 1. 打开包含一个或多个组件的装配体。
// 2. 多选要获取质量属性的组件。
// 3. 打开一个立即窗口。
//
// 后置条件:
// 1. 获取所选组件的质量属性程序集。
// 2. 检查立即窗口的质量属性选中的组件。
//----------------------------------------------------------------------------
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 GetMassProperties2_CSharp.csproj
{
partial class SolidWorksMacro
{
public void Main()
{
ModelDoc2 swModel = default(ModelDoc2);
ModelDocExtension swModelExt = default(ModelDocExtension);
SelectionMgr swSelMgr = default(SelectionMgr);
Component2 swComp = default(Component2);
int nStatus = 0;
double[] vMassProp = null;
int i = 0;
int nbrSelections = 0;
swModel = (ModelDoc2)swApp.ActiveDoc;
swModelExt = swModel.Extension;
swSelMgr = (SelectionMgr)swModel.SelectionManager;
nbrSelections = swSelMgr.GetSelectedObjectCount2(-1);//选择对象数量
if (nbrSelections == 0)
{
Debug.Print("Please select one or more components and rerun the macro.");
return;
}
nbrSelections = nbrSelections - 1;
Debug.Print("Getting mass properties for components: ");
for (i = 0; i <= nbrSelections; i++)
{
swComp = (Component2)swSelMgr.GetSelectedObject6(i + 1, -1);//选择的对象
Debug.Print(" " + swComp.Name2);
}
vMassProp = (double[])swModelExt.GetMassProperties2(1, out nStatus, true);//以指定的精度获取模型中组件的实际质量属性。
Debug.Print("swMassPropertiesStatus_e 中定义的状态 (0 = 质量属性计算成功) = " + nStatus);
if ((vMassProp != null))
{
Debug.Print("质心:");
Debug.Print(" X坐标 = " + vMassProp[0]);
Debug.Print(" Y坐标 = " + vMassProp[1]);
Debug.Print(" Z坐标= " + vMassProp[2]);
Debug.Print("体积= " + vMassProp[3]);
Debug.Print("表面积 = " + vMassProp[4]);
Debug.Print("质量 = " + vMassProp[5]);
Debug.Print("密度= " + vMassProp[5] / vMassProp[3]);
Debug.Print("在质心处获取并与输出坐标系对齐的惯性矩:");
Debug.Print(" Lxx = " + vMassProp[6]);
Debug.Print(" Lyy = " + vMassProp[7]);
Debug.Print(" Lzz = " + vMassProp[8]);
Debug.Print(" Lxy = " + vMassProp[9]);
Debug.Print(" Lzx = " + vMassProp[10]);
Debug.Print(" Lyz = " + vMassProp[11]);
}
}
/// <summary>
/// The SldWorks swApp variable is pre-assigned for you.
/// </summary>
public SldWorks swApp;
}
}
GetModelViews
//此示例显示如何获取零件文档中每个模型视图的比例因子。
//---------------------------------
// 前提条件:
// 1. 打开零件文档。
// 2. 单击窗口 > 视口 > 四视图。
// 3. 单击模型视图并旋转鼠标中键按钮前进或后退。
// 4. 打开立即窗口。
//
// 后置条件:
// 1. 获取零件文档中模型视图的数量。
// 2. 获取每个模型视图的比例因子。
// 3. 检查立即窗口。
//---------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
namespace GetModelViewScalesCSharp.csproj
{
public partial class SolidWorksMacro
{
public void Main()
{
ModelDoc2 SwModel = default(ModelDoc2);
ModelDocExtension swModelDocExt = default(ModelDocExtension);
ModelView swModView = default(ModelView);
object[] modViews = null;
long Count = 0;
SwModel = (ModelDoc2)swApp.ActiveDoc;
swModelDocExt = (ModelDocExtension)SwModel.Extension;
//获取模型视图
modViews = (object[])swModelDocExt.GetModelViews();
//获取模型视图的数量
Count = swModelDocExt.GetModelViewCount();
Debug.Print("Number of model views: " + Count);
//获取每个模型视图的比例因子
for (long i = 0; i < Count; i++)
{
swModView = (ModelView)modViews[i];
Debug.Print("此模型视图的比例因子为: " + swModView.Scale2);
}
}
/// <summary>
/// The SldWorks swApp variable is pre-assigned for you.
/// </summary>
public SldWorks swApp;
}
}
GetObjectByPersistReference3
Sub main ()
Set swApp = Application.SldWorks
Set Doc = swApp.ActiveDoc
Set SelMgr = Doc.SelectionManager
If SelMgr.GetSelectedObjectCount(-1) = 0 Then Debug.Print "No selections found.": Exit Sub
Dim persistRef As Variant
Dim selObj As Object
Set selObj = SelMgr.GetSelectedObject6(1, -1)
persistRef = Doc.Extension.GetPersistReference3(selObj)
Debug.Print UBound(persistRef)
Set selObj = Nothing
Set selObj = Doc.Extension.GetObjectByPersistReference3(persistRef, longstatus)
Debug.Print (Not selObj Is Nothing)
Dim selConfig As Configuration
Set selConfig = selObj.GetSpecificFeature2
End Sub
InsertBomTable3
//此示例说明如何在装配体文档中插入和显示 BOM 表。
//------------------------------------------------
// 前提条件:
// 1. 验证要打开的指定文件和模板是否存在。
// 2. 打开立即窗口。
//
// 后置条件:
// 1. 插入一个缩进的 BOM 表。
// 2. 在选定的面上插入一个分割圆堆叠气球,它使用 BOM 表项目编号作为其上部文本。
// 3. 检查 BOM 表、堆叠气球和立即窗口。
//
// 注意:因为这个装配文件在别处使用,
// 不保存更改。
//------------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
namespace IBomFeatureInsertBomTable3CSharp.csproj
{
partial class SolidWorksMacro
{
public void Main()
{
ModelDoc2 swModel = default(ModelDoc2);
ModelDocExtension swModelDocExt = default(ModelDocExtension);
BomTableAnnotation swBOMAnnotation = default(BomTableAnnotation);//BOM表注释
BomFeature swBOMFeature = default(BomFeature);//BOM特征
StackedBalloonOptions StackedBalloonParams = default(StackedBalloonOptions);//堆叠气球参数
Note swNote = default(Note);
bool boolstatus = false;
int BomType = 0;
int nbrType = 0;
string Configuration = null;
string TemplateName = null;
int nErrors = 0;
int nWarnings = 0;
//打开装配文件
swModel = (ModelDoc2)swApp.OpenDoc6("C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\arm2.sldasm", (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref nErrors, ref nWarnings);
swModelDocExt = (ModelDocExtension)swModel.Extension;
//插入 BOM 表
TemplateName = "C:\\Program Files\\SOLIDWORKS Corp\\SOLIDWORKS\\lang\\english\\bom-standard.sldbomtbt";
BomType = (int)swBomType_e.swBomType_Indented;
Configuration = "Default";
nbrType = (int)swNumberingType_e.swNumberingType_Detailed;
swBOMAnnotation = (BomTableAnnotation)swModelDocExt.InsertBomTable3(TemplateName, 0, 0, BomType, Configuration, false, nbrType, true);
swBOMFeature = (BomFeature)swBOMAnnotation.BomFeature;
//打印用于 BOM 表的配置名称
Debug.Print("用于BOM表的配置名称: " + swBOMFeature.Configuration);
//为所选面插入BOM球标
boolstatus = swModelDocExt.SelectByID2("", "FACE", 0.091853347996107, -0.0104709589619745, 0.00174830255600256, false, 0, null, 0);
StackedBalloonParams = (StackedBalloonOptions)swModelDocExt.CreateStackedBalloonOptions();//堆叠气球
StackedBalloonParams.BalloonsPerLine = 10;//每行气球数
StackedBalloonParams.StackDirection = (int)swStackedBalloonDirection_e.swStackedBalloonDir_Right;//堆叠方向
StackedBalloonParams.Style = (int)swBalloonStyle_e.swBS_SplitCirc;
StackedBalloonParams.LowerTextContent = (int)swBalloonTextContent_e.swBalloonTextCustom;//下文本内容行
StackedBalloonParams.LowerText = "Lower Text";//下文本内容
StackedBalloonParams.ShowQuantity = true;//显示数量
StackedBalloonParams.Size = (int)swBalloonFit_e.swBF_Tightest;//大小
StackedBalloonParams.QuantityPlacement = (int)swBalloonQuantityPlacement_e.swBalloonQuantityPlacement_Top;//数量放置
StackedBalloonParams.QuantityDenotationText = "Denotation Text";//数量表示文本
StackedBalloonParams.QuantityOverride = false;//数量覆盖
StackedBalloonParams.ItemNumberStart = 1;//项目编号开始
StackedBalloonParams.ItemNumberIncrement = 1;//项目编号增量
StackedBalloonParams.ItemOrder = (int)swBalloonItemNumbersOrder_e.swBalloonItemNumbers_DoNotChangeItemNumbers;//项目号
swNote = (Note)swModelDocExt.InsertStackedBalloon2(StackedBalloonParams);
swModel.ViewZoomtofit2();
// 获取气球是否为堆叠气球;
// 如果是,则打印气球的名称
if (swNote.IsStackedBalloon())
{
Debug.Print("堆叠气球名称: " + swNote.GetName());
}
}
/// <summary>
/// The SldWorks swApp variable is pre-assigned for you.
/// </summary>
public SldWorks swApp;
}
}
InsertGeneralTableAnnotation
在此模型文档中插入通用表格注释。
//此示例显示如何将通用表注释插入模型文档。
//------------------------------------------------ ---
// 先决条件:打开一个零件。
//
// 后置条件:
// 1. 在零件中插入一个通用表。
// 2. 检查图形区域。
//------------------------------------------------ ---
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
namespace InsertGeneralTable_CSharp.csproj
{
partial class SolidWorksMacro
{
ModelDoc2 Part;
ModelDocExtension modelDocExt;
TableAnnotation myTable;
public void Main()
{
Part = (ModelDoc2)swApp.ActiveDoc;
modelDocExt = Part.Extension;
myTable = modelDocExt.InsertGeneralTableAnnotation(true, 0, 0, (int)swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_TopLeft, "", 2, 2);
}
public SldWorks swApp;
}
}
InsertGeneralToleranceTableAnnotation
在此模型文档中插入通用公差表注释。
//此示例说明如何创建通用公差表注释。
//------------------------------------------------ -----------------------------
// 前提条件:
// 1. 打开一个零件。
// 2. 确保指定的表模板存在。
// 3. 打开立即窗口。
//
// 后置条件:
// 1. 创建通用公差表注释。
// 2. 检查立即窗口、图形区域和 FeatureManager 设计树的表文件夹。
//------------------------------------------------ -----------------------------
using SolidWorks.Interop.sldworks;
using System.Diagnostics;
namespace InsertTable_CSharp
{
public partial class SolidWorksMacro
{
public void Main()
{
ModelDoc2 Part = default(ModelDoc2);
GeneralToleranceTableAnnotation gttAnno = default(GeneralToleranceTableAnnotation);//通用公差表注解
GeneralToleranceTableFeature gttFeat = default(GeneralToleranceTableFeature);
Feature feat = default(Feature);
ModelDocExtension mde = default(ModelDocExtension);
bool boolstatus = false;
Part = (ModelDoc2)swApp.ActiveDoc;
mde = Part.Extension;
gttAnno = mde.InsertGeneralToleranceTableAnnotation("c:\\Program Files\\SOLIDWORKS Corp\\SOLIDWORKS\\lang\\english\\bom-standard.sldbomtbt", 481, 163);
gttFeat = gttAnno.GeneralToleranceTableFeature;
feat = gttFeat.GetFeature();
Debug.Print("Created " + feat.Name);
boolstatus = Part.EditRebuild3();
}
// The SldWorks swApp variable is pre-assigned for you.
public SldWorks swApp;
}
}
ListExternalFileReferences
获取此零件或装配体上外部参考的名称和状态。
//此示例显示如何获取选定组件、选定特征或文档的外部参考列表。
//------------------------------------------------ ----------
// 前提条件:
// 1. 打开装配或零件文档。
// 2. 选择:
// * 组件文档中的一个组件。
// - 或者 -
// * 装配体或零件文档中的特征。
// - 或者 -
// * 两种类型的文档中都没有。
//
// 后置条件:检查立即窗口以查看零件或装配体文档的名称以及所选零部件、特征或文档的外部参考。
//------------------------------------------------ ----------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Diagnostics;
namespace ListExternalFileReferencesCSharp.csproj
{
partial class SolidWorksMacro
{
public void Main()
{
ModelDoc2 swModel = default(ModelDoc2);//通用文档
ModelDocExtension swModDocExt = default(ModelDocExtension);//通用文档扩展
SelectionMgr swSelMgr = default(SelectionMgr);//选择管理器
Feature swFeat = default(Feature);//特征
Component2 swComp = default(Component2);//零件
object vModelPathName = null;
object vComponentPathName = null;
object vFeature = null;
object vDataType = null;
object vStatus = null;
object vRefEntity = null;
object vFeatComp = null;
int nConfigOpt = 0;
string sConfigName = null;
int nRefCount = 0;
int nSelType = 0;
int i = 0;
swModel = (ModelDoc2)swApp.ActiveDoc;
swSelMgr = (SelectionMgr)swModel.SelectionManager;
swModDocExt = (ModelDocExtension)swModel.Extension;
nSelType = swSelMgr.GetSelectedObjectType3(1, -1);
switch (nSelType)
{
//装配体文档中的选定零部件
case (int)swSelectType_e.swSelCOMPONENTS:
swComp = (Component2)swSelMgr.GetSelectedObjectsComponent3(1, -1);
nRefCount = swComp.ListExternalFileReferencesCount();
swComp.ListExternalFileReferences2(out vModelPathName, out vComponentPathName, out vFeature, out vDataType, out vStatus, out vRefEntity, out vFeatComp, out nConfigOpt, out sConfigName);
swModel = (ModelDoc2)swComp.GetModelDoc2();
break;
//零件或装配体文档中的选定特征
case (int)swSelectType_e.swSelBODYFEATURES:
case (int)swSelectType_e.swSelSKETCHES:
swFeat = (Feature)swSelMgr.GetSelectedObject6(1, -1);
nRefCount = swFeat.ListExternalFileReferencesCount();
swFeat.ListExternalFileReferences2(out vModelPathName, out vComponentPathName, out vFeature, out vDataType, out vStatus, out vRefEntity, out vFeatComp, out nConfigOpt, out sConfigName);
break;
//零件或装配体
default:
nRefCount = swModDocExt.ListExternalFileReferencesCount();
swModDocExt.ListExternalFileReferences(out vModelPathName, out vComponentPathName, out vFeature, out vDataType, out vStatus, out vRefEntity, out vFeatComp, out nConfigOpt, out sConfigName);
break;
}
Debug.Print("Model name = " + swModel.GetPathName());
Debug.Print(" Reference count = " + System.Convert.ToString(nRefCount));
if (nRefCount >= 1)
{
object[] ModelPathName = new object[nRefCount - 1];
object[] ComponentPathName = new object[nRefCount - 1];
object[] Feature = new object[nRefCount - 1];
object[] DataType = new object[nRefCount - 1];
int[] Status = new int[nRefCount - 1];
object[] RefEntity = new object[nRefCount - 1];
object[] FeatComp = new object[nRefCount - 1];
ModelPathName = (object[])vModelPathName;
ComponentPathName = (object[])vComponentPathName;
Feature = (object[])vFeature;
DataType = (object[])vDataType;
Status = (int[])vStatus;
RefEntity = (object[])vRefEntity;
FeatComp = (object[])vFeatComp;
Debug.Print("");
for (i = 0; i <= nRefCount - 1; i++)
{
Debug.Print(" Model path + name = " + ModelPathName[i]);
Debug.Print(" Component path + name = " + ComponentPathName[i]);
Debug.Print(" Feature = " + Feature[i]);
Debug.Print(" Data type = " + DataType[i]);
Debug.Print(" Status = " + System.Convert.ToString(Status[i]));
Debug.Print(" Reference entity = " + RefEntity[i]);
Debug.Print(" Feature component = " + FeatComp[i]);
Debug.Print(" Config option = " + nConfigOpt);
Debug.Print(" Config name = " + sConfigName);
Debug.Print(" ");
}
}
}
/// <summary>
/// The SldWorks swApp variable is pre-assigned for you.
/// </summary>
public SldWorks swApp;
}
}
RenameDocument
此示例显示如何重命名装配中的零部件,并在未先保存其引用的情况下尝试保存装配时返回错误。
//------------------------------------------------ --------------------
// 前提条件:
// 1. 验证指定的程序集是否存在。
// 2. 打开立即窗口。
//
// 后置条件:
// 1. 打开指定的程序集。
// 2. 选择一个组件。
// 3. 重命名所选组件和其他同名组件。
// 4. 尝试保存程序集。
// 5. 获取程序集是否已重命名组件。
// 6. 检查立即窗口。
//
// 注意:因为程序集在别处使用,所以不要保存更改。
//------------------------------------------------ --------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
Namespace Macro1CSharp.csproj
{
Partial Public Class SolidWorksMacro
{
public void Main()
{
ModelDoc2 swModel = default(ModelDoc2);
ModelDocExtension swModelDocExt = default(ModelDocExtension);
bool status = false;
int errors = 0;
int warnings = 0;
string fileName = null;
int errorsRename = 0;
int errorsSave = 0;
fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\beam_boltconnection.sldasm";//文件路径和名称
swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);//通用文档
swModelDocExt = (ModelDocExtension)swModel.Extension;//文档扩展
status = swModelDocExt.SelectByID2("beam with holes-2@beam_boltconnection", "COMPONENT", 0, 0, 0, false, 0, null, 0);//选择实体
errorsRename = swModelDocExt.RenameDocument("Renamed_beam_with_holes");
Debug.Print("重命名文档错误: " + errorsRename);
status = swModel.Save3((int)swSaveAsOptions_e.swSaveAsOptions_Silent, ref errorsSave, ref warnings);//保存
if (status == false)
{
Debug.Print("保存错误(8192 = 保存具有重命名零部件的装配体需要保存参考): " + errorsSave);
}
status = swModelDocExt.HasRenamedDocuments();
Debug.Print("装配文件已重命名零部件: " + status);
swModel.ClearSelection2(true);
}
/// <summary>
/// The SldWorks swApp variable is pre-assigned for you.
/// </summary>
public SldWorks swApp;
}
}
//此示例显示如何重命名组件并更新其引用。
//------------------------------------------------ ---------------
// 前提条件:
// 1.将public_documents\samples\tutorial\EDraw\claw复制到c:\test\claw。
// 2.打开c:\test\claw\claw-mechanism.sldasm,将文件另存为 claw-mechanism-copy.sldasm
// 3.关闭claw-mechanism-copy.sldasm并重新打开claw-mechanism.sldasm。
// 4.打开立即窗口。
//
// 后置条件:
// 1. 将中心组件重命名为 centerXXX。
// 2. 触发 RenameItemNotify 事件。
// 3. 保存装配体。
// 4. 触发 RenamedDocumentNotify 事件。
// 5. 更新引用。
// 6. 检查 FeatureManager 设计树和立即窗口。
// 7. 关闭claw-mechanism.sldasm,打开c:\test\claw\claw-mechanism-copy.sldasm,验证中心组件是否重命名为centerXXX。
//------------------------------------------------ ---------------------
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 assy;
public void Main()
{
ModelDoc2 swModel = default(ModelDoc2);
ModelDocExtension swModelDocExt = default(ModelDocExtension);
AssemblyDoc swAssy = default(AssemblyDoc);
Hashtable openAssembly = default(Hashtable);
int errors = 0;
int warnings = 0;
bool status = false;
swAssy = (AssemblyDoc)swApp.ActiveDoc;
//设置事件
assy = (AssemblyDoc)swAssy;
openAssembly = new Hashtable();
AttachEventHandlers();
swModel = (ModelDoc2)swAssy;
swModelDocExt = (ModelDocExtension)swModel.Extension;
status = swModelDocExt.SelectByID2("center-1@claw-mechanism", "COMPONENT", 0, 0, 0, false, 0, null, 0);
errors = swModelDocExt.RenameDocument("centerXXX");
swModelDocExt.Rebuild((int)swRebuildOptions_e.swRebuildAll);
status = swModel.Save3((int)swSaveAsOptions_e.swSaveAsOptions_Silent + (int)swSaveAsOptions_e.swSaveAsOptions_SaveReferenced, ref errors, ref warnings);
}
public void AttachEventHandlers()
{
AttachSWEvents();
}
public void AttachSWEvents()
{
if ((assy != null))
{
assy.RenameItemNotify += this.assy_RenameItemNotify;
assy.RenamedDocumentNotify += this.assy_RenamedDocumentNotify;
}
}
//重命名项目时触发通知
public int assy_RenameItemNotify(int entType, string oldName, string newName)
{
Debug.Print("RenameItemNotify fired");
return 0;
}
//重命名文档对话框的火灾通知
public int assy_RenamedDocumentNotify(ref object swObj)
{
RenamedDocumentReferences swRenamedDocumentReferences = default(RenamedDocumentReferences);
object[] searchPaths = null;
object[] pathNames = null;
int i = 0;
int nbr = 0;
swRenamedDocumentReferences = (RenamedDocumentReferences)swObj;
swRenamedDocumentReferences.UpdateWhereUsedReferences = true;
swRenamedDocumentReferences.IncludeFileLocations = true;
searchPaths = (object[])swRenamedDocumentReferences.GetSearchPath();
nbr = searchPaths.Length - 1;
Debug.Print("Search paths:");
for (i = 0; i <= nbr; i++)
{
Debug.Print(" " + searchPaths[i]);
}
swRenamedDocumentReferences.Search();
pathNames = (object[])swRenamedDocumentReferences.ReferencesArray();
nbr = pathNames.Length - 1;
Debug.Print("参考:");
for (i = 0; i <= nbr; i++)
{
Debug.Print(" " + pathNames[i]);
}
swRenamedDocumentReferences.CompletionAction = (int)swRenamedDocumentFinalAction_e.swRenamedDocumentFinalAction_Ok;
Debug.Print("重命名文档通知被触发");
return 0;
}
/// <summary>
/// The SldWorks swApp variable is pre-assigned for you.
/// </summary>
public SldWorks swApp;
}
}
ReorderFeature
//此示例显示如何将特征移动到零件的 FeatureManager 设计树中的另一个位置。
//------------------------------------------------ ---------------------------
// 前提条件:
// 1. 打开public_documents\samples\tutorial\api\clamp2.sldprt。
// 2. 打开一个立即窗口。
//
// 后置条件:
// 1. Fillet5 移动到 FeatureManager 设计树的末尾。
// 2. 检查立即窗口。
//
// 注意:由于装配体文档被别处使用,关闭文档时不要保存任何更改。
//---------------------------------------------------------------------------
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 ReorderFeature_CSharp.csproj
{
partial class SolidWorksMacro
{
ModelDoc2 modelDoc2;
ModelDocExtension modelDocExt;
bool retVal;
public void Main()
{
modelDoc2 = (ModelDoc2)swApp.ActiveDoc;
modelDocExt = modelDoc2.Extension;
retVal = modelDocExt.ReorderFeature("Fillet5", "", (int)swMoveLocation_e.swMoveToEnd);
Debug.Print("Fillet5 移至 FeatureManager 设计树的末尾? " + retVal);
}
public SldWorks swApp;
}
}
RunCommand
//此示例显示如何获取 SOLIDWORKS 命令 ID、PropertyManager 标题以及用户界面是否处于活动状态。在 PropertyManager 页面打开之前和取消时触发事件。
//-----------------------------------------
// 前提条件:
// 1. 验证要打开的部分是否存在。
// 2. 添加对 SolidWorks.Interop.swcommands.dll 的引用。
// 3. 打开立即窗口。
// 4.清除工具>选项>宏退出时停止VSTA调试器,如果它被选中。
//
// 后置条件:
// 1. 打开零件。
// 2. 触发 CommandOpenPreNotify 事件;单击“确定”关闭消息框。
// 3. 打开圆角 PropertyManager 页面。
// 4. 获取PropertyManager 页面的标题、用户界面是否处于活动状态以及命令ID 是否为圆角。
// 5. 单击圆角 PropertyManager 页面上的 X 将其取消。
// 6. 触发 CommandCloseNotify 事件;单击“确定”关闭消息框。
// 7. 检查立即窗口。
// 8. 在 IDE 中单击停止调试。
// 9. 选择工具 > 选项 > 在宏退出时停止 VSTA 调试器,如果您在前提条件步骤 4 中清除了它。
//--------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Diagnostics;
using SolidWorks.Interop.swcommands;
using System.Windows.Forms;
namespace GetRunningCommandInfoSldWorksCSharp.csproj
{
partial class SolidWorksMacro
{
public SldWorks swAppSW;
public void Main()
{
ModelDoc2 swModel;
ModelDocExtension swModelDocExt;
string modelName = null;
int errors = 0;
int warnings = 0;
int commandID = 0;
string pmpTitle = null;
bool isUIActive = false;
//设置事件
swAppSW = (SldWorks)swApp;
AttachEventHandlers();
//打开模型
modelName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\fillets\\knob.sldprt";
swModel = (ModelDoc2)swApp.OpenDoc6(modelName, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
swModelDocExt = (ModelDocExtension)swModel.Extension;
//打开圆角 PropertyManager 页面,这会导致 CommandOpenPreNotify 事件触发
swModelDocExt.RunCommand((int)swCommands_e.swCommands_Fillet, "Fillet");
// 如果命令是圆角,则获取命令 ID,如果处于活动状态,则获取 PropertyManager 页面标题,并获取用户界面是否处于活动状态
swApp.GetRunningCommandInfo(out commandID, out pmpTitle, out isUIActive);
if (!string.IsNullOrEmpty(pmpTitle)) Debug.Print("Title of PropertyManager page: " + pmpTitle);
Debug.Print("用户界面是否活动? " + isUIActive);
if ((commandID == 9))
{
Debug.Print("Command ID: " + "swCommands_Fillet");
}
else
{
Debug.Print("Command ID: " + "Not a fillet.");
}
}
public void AttachEventHandlers()
{
AttachSWEvents();
}
public void AttachSWEvents()
{
swAppSW.CommandOpenPreNotify += this.swAppSW_CommandOpenPreNotify;
swAppSW.CommandCloseNotify += this.swAppSW_CommandCloseNotify;
}
private int swAppSW_CommandOpenPreNotify(int command, int userCommand)
{
//当圆角 PropertyManager 页面即将打开时发送消息
if ((command == (int)swCommands_e.swCommands_Fillet)) MessageBox.Show("Fillet PropertyManager page is about to open.");
return 0;
}
private int swAppSW_CommandCloseNotify(int command, int reason)
{
//取消圆角 PropertyManager 页面时发送消息
MessageBox.Show("Fillet PropertyManager page was canceled.");
return 0;
}
/// <summary>
/// The SldWorks swApp variable is pre-assigned for you.
/// </summary>
public SldWorks swApp;
}
}
SavePackAndGo
//此示例显示如何获取装配文档的路径和文件的名称、为名称添加前缀和后缀,以及如何使用打包界面将文件保存到不同的路径。
//------------------------------------------------ --------------------------
// 前提条件:
// 1. 指定的程序集存在。
// 2. 文件夹 c:\temp 存在。
// 3. 打开立即窗口。
// 4. 运行宏。
//
// 后置条件:
// 1. 将装配文件的当前路径名称和文件名打印到立即窗口。
// 2. 打印默认路径的名称和文件名,将装配文件保存到立即窗口。
// 3. 指定打包目标文件夹。
// 4. 指定将所有文件保存到打包目标文件夹的根目录中。
// 5. 为用户命名的文件名添加前缀和后缀。
// 6. 将用户指定路径的名称和用户命名的文件名打印到立即窗口。
// 7. 使用 Pack and Go 在用户指定的路径中创建用户命名的文件。
// 8. 检查 c:\temp 进行验证。
//------------------------------------------------ ---------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace PackAndGoCSharp.csproj
{
partial class SolidWorksMacro
{
public void Main()
{
ModelDoc2 swModelDoc = default(ModelDoc2);
ModelDocExtension swModelDocExt = default(ModelDocExtension);
PackAndGo swPackAndGo = default(PackAndGo);
string openFile = null;
bool status = false;
int warnings = 0;
int errors = 0;
int i = 0;
int namesCount = 0;
string myPath = null;
int[] statuses = null;
//打开装配
openFile = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\advdrawings\\handle.sldasm";
swModelDoc = (ModelDoc2)swApp.OpenDoc6(openFile, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
swModelDocExt = (ModelDocExtension)swModelDoc.Extension;
//获取打包对象
Debug.Print("Pack and Go");
swPackAndGo = (PackAndGo)swModelDocExt.GetPackAndGo();
//获取程序集中的文档数
namesCount = swPackAndGo.GetDocumentNamesCount();
Debug.Print(" Number of model documents: " + namesCount);
// 包括任何工程图、SOLIDWORKS Simulation 结果和 SOLIDWORKS Toolbox 组件
swPackAndGo.IncludeDrawings = true;
Debug.Print(" Include drawings: " + swPackAndGo.IncludeDrawings);
swPackAndGo.IncludeSimulationResults = true;
Debug.Print(" Include SOLIDWORKS Simulation results: " + swPackAndGo.IncludeSimulationResults);
swPackAndGo.IncludeToolboxComponents = true;
Debug.Print(" Include SOLIDWORKS Toolbox components: " + swPackAndGo.IncludeToolboxComponents);
//获取程序集文档的当前路径和文件名
object fileNames;
object[] pgFileNames = new object[namesCount - 1];
status = swPackAndGo.GetDocumentNames(out fileNames);
pgFileNames = (object[])fileNames;
Debug.Print("");
Debug.Print(" Current path and filenames: ");
if ((pgFileNames != null))
{
for (i = 0; i <= pgFileNames.GetUpperBound(0); i++)
{
Debug.Print(" The path and filename is: " + pgFileNames[i]);
}
}
//获取程序集文档的当前保存路径和文件名
object pgFileStatus;
status = swPackAndGo.GetDocumentSaveToNames(out fileNames, out pgFileStatus);
pgFileNames = (object[])fileNames;
Debug.Print("");
Debug.Print(" Current default save-to filenames: ");
if ((pgFileNames != null))
{
for (i = 0; i <= pgFileNames.GetUpperBound(0); i++)
{
Debug.Print(" The path and filename is: " + pgFileNames[i]);
}
}
//设置文件夹保存文件的位置
myPath = "C:\\temp\\";
status = swPackAndGo.SetSaveToName(true, myPath);
//扁平化打包文件夹结构; 将所有文件保存到根目录
swPackAndGo.FlattenToSingleFolder = true;
//为文件名添加前缀和后缀
swPackAndGo.AddPrefix = "SW_";
swPackAndGo.AddSuffix = "_PackAndGo";
//添加前缀和后缀后验证文档路径和文件名
object getFileNames;
object getDocumentStatus;
string[] pgGetFileNames = new string[namesCount - 1];
status = swPackAndGo.GetDocumentSaveToNames(out getFileNames, out getDocumentStatus);
pgGetFileNames = (string[])getFileNames;
Debug.Print("");
Debug.Print("添加前缀和后缀后的打包路径和文件名: ");
for (i = 0; i <= namesCount - 1; i++)
{
Debug.Print("我的路径和文件名是: " + pgGetFileNames[i]);
}
//打包带走
statuses = (int[])swModelDocExt.SavePackAndGo(swPackAndGo);
}
/// <summary>
/// The SldWorks swApp variable is pre-assigned for you.
/// </summary>
public SldWorks swApp;
}
}
//此示例显示如何将 SOLIDWORKS、渲染参考和非 SOLIDWORKS 文件添加到 Pack and Go。 此示例还展示了如何从 Pack and Go 中移除非 SOLIDWORKS 文件。
//--------------------------------------------
// 前提条件:
// 1. 验证指定的程序集是否存在。
// 2. 创建 c:\PackAndGo。
// 3. 打开立即窗口。
//
// 后置条件:
// 1. 为 Pack and Go 获取 SOLIDWORKS、渲染参考和非 SOLIDWORKS 文件的名称。
// 2. 获取要删除的非 SOLIDWORKS 文件的名称。
// 3. 打包 SOLIDWORKS、渲染参考和非 SOLIDWORKS 文件并将它们复制到 c:\PackAndGo。
// 4. 检查 c:\PackAndGo 和立即窗口。
//--------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace AddExternalDocumentsPackAndGo.csproj
{
partial class SolidWorksMacro
{
public void Main()
{
ModelDoc2 swModel = default(ModelDoc2);
ModelDocExtension swModelDocExt = default(ModelDocExtension);
PackAndGo swPackAndGo = default(PackAndGo);
string openFile = null;
int namesCount = 0;
int errors = 0;
int warnings = 0;
bool status = false;
int i = 0;
object[] renderReferences = null;
string myPath = null;
object statuses = null;
//打开装配文件
openFile = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\EDraw\\claw\\claw-mechanism.sldasm";
swModel = (ModelDoc2)swApp.OpenDoc6(openFile, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
swModelDocExt = (ModelDocExtension)swModel.Extension;
//获取打包对象
Debug.Print("打包带走");
swPackAndGo = (PackAndGo)swModelDocExt.GetPackAndGo();
//获取程序集中的文档数
namesCount = swPackAndGo.GetDocumentNamesCount();
//获取程序集文档的当前路径和文件名
object fileNames;
object[] pgFileNames = new object[namesCount - 1];
status = swPackAndGo.GetDocumentNames(out fileNames);
pgFileNames = (object[])fileNames;
Debug.Print("");
Debug.Print("添加 SOLIDWORKS 文件的路径和文件名: ");
if ((pgFileNames != null))
{
for (i = 0; i <= pgFileNames.GetUpperBound(0); i++)
{
Debug.Print("路径和文件名是: " + pgFileNames[i]);
}
}
//为 Pack and Go 设置文档路径和名称
status = swPackAndGo.SetDocumentSaveToNames(pgFileNames);
// 获取此组件中的渲染库存参考并将它们打印到立即窗口
Debug.Print(" ");
renderReferences = (object[])swModelDocExt.GetRenderStockReferences();
Debug.Print(" Add render references:");
for (i = 0; i <= renderReferences.GetUpperBound(0); i++)
{
Debug.Print("路径和文件名是: " + renderReferences[i]);
}
//将渲染库存文件添加到 Pack and Go
status = swPackAndGo.AddExternalDocuments(renderReferences);
//将其他非 SOLIDWORKS 文件添加到 Pack and Go
object[] otherFiles = new object[2];
string otherFile = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\edraw\\claw\\claw-mechanism.easm";
otherFiles[0] = (object)otherFile;
otherFile = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\edraw\\claw\\claw-mechanism.emodel_debugonly.xml";
otherFiles[1] = (object)otherFile;
Debug.Print(" ");
Debug.Print("添加非 SOLIDWORKS 文件:");
for (i = 0; i <= otherFiles.GetUpperBound(0); i++)
{
Debug.Print("路径和文件名是: " + otherFiles[i]);
}
//将非 SOLIDWORKS 文件添加到 Pack and Go
status = swPackAndGo.AddExternalDocuments(ObjectArrayToBStrWrapperArray(otherFiles));
//从 Pack and Go 中删除非 SOLIDWORKS 文件之一
object[] delOtherFiles = new object[1];
delOtherFiles[0] = (object)otherFiles[0];
Debug.Print(" ");
Debug.Print(" 删除非 SOLIDWORKS 文件:");
Debug.Print(" 路径和文件名是: " + delOtherFiles[0]);
status = swPackAndGo.RemoveExternalDocuments(ObjectArrayToBStrWrapperArray(delOtherFiles));
//覆盖保存文档的路径
myPath = "c:\\PackAndGo\\";
status = swPackAndGo.SetSaveToName(true, myPath);
//打包 SOLIDWORKS 和非 SOLIDWORKS 文件
statuses = swModelDocExt.SavePackAndGo(swPackAndGo);
}
public BStrWrapper[] ObjectArrayToBStrWrapperArray(object[] SwObjects)
{
int arraySize;
arraySize = SwObjects.GetUpperBound(0);
BStrWrapper[] dispwrap = new BStrWrapper[arraySize + 1];
int arrayIndex;
for (arrayIndex = 0; arrayIndex < arraySize + 1; arrayIndex++)
{
dispwrap[arrayIndex] = new BStrWrapper((string)(SwObjects[arrayIndex]));
}
return dispwrap;
}
/// <summary>
/// The SldWorks swApp variable is pre-assigned for you.
/// </summary>
public SldWorks swApp;
}
}
ShowSmartMessage
Option Explicit
Dim swApp As SldWorks.SldWorks
Dim swModelDocExt As SldWorks.ModelDocExtension
Dim swModel As SldWorks.ModelDoc2
Dim swSelMgr As SldWorks.SelectionMgr
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
swModel.ClearSelection2 True
Set swSelMgr = swModel.SelectionManager
Set swModelDocExt = swModel.Extension
While 1
' Loops until you select an entity in the graphics area
While swSelMgr.GetSelectedObjectCount = 0
DoEvents
Wend
swModelDocExt.ShowSmartMessage "This is the message.", 500, True, True
DoEvents
Wend
End Sub
//在下方状态栏显示
private void SW_Clear(object sender, RoutedEventArgs e)
{
ModelDoc2 model = ((ModelDoc2)(sld4Handler.SwApp.ActiveDoc));
ModelDocExtension modelDocExtension = model.Extension;
modelDocExtension.ShowSmartMessage("ShowSmartMessage",10000,true,true);
}
ViewZoomToSheet
//此示例显示如何在窗口内将工程图缩放至其最大尺寸。
//------------------------------------------------ ------
// 前提条件:验证要打开的图形是否存在。
//
// 后置条件:
// 1. 打开绘图。
// 2. 将图纸放大到窗口内的最大尺寸。
// 3. 检查图形区域。
//
// 注意:因为绘图在别处使用,所以不要保存更改。
//------------------------------------------------ -------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
namespace Macro1CSharp.csproj
{
public partial class SolidWorksMacro
{
public void Main()
{
ModelDoc2 swModel;
ModelDocExtension swModelDocExt;
string fileName;
int errors = 0;
int warnings = 0;
fileName = "C:\\Users\\Public\\Documents\\SOLIDWORKS\\SOLIDWORKS 2018\\samples\\tutorial\\api\\replaceview.slddrw";
swModel = (ModelDoc2)swApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocDRAWING, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
swModelDocExt = (ModelDocExtension)swModel.Extension;
swModelDocExt.ViewZoomToSheet();
}
/// <summary>
/// The SldWorks swApp variable is pre-assigned for you.
/// </summary>
public SldWorks swApp;
}
}