C# SolidWorks 二次开发 API —工程图尺寸信息的读取

C# SolidWorks 二次开发 API —工程图尺寸信息的读取

工程图尺寸信息的读取

前提条件: 在打开的工程图选中一个尺寸
本文目标: 通过转换选择的尺寸为一个尺寸对象,获取该尺寸的值与公差。


 private void btnGetDimensionInfo_Click(object sender, EventArgs e)
        {
            ISldWorks swApp = Utility.ConnectToSolidWorks();
            swApp.CommandInProgress = true;

            ModelDoc2 swModel = (ModelDoc2)swApp.ActiveDoc;

            SelectionMgr selectionMgr = (SelectionMgr)swModel.SelectionManager;

            //转换成尺寸显示对象
            var swDisplayDimension = (DisplayDimension)selectionMgr.GetSelectedObject6(1, 0);

            DisplayData displayData = (DisplayData)swDisplayDimension.GetDisplayData();

            //获取尺寸上的文字
            var anno = (Annotation)swDisplayDimension.GetAnnotation();

            //获取所在视图 ---如果是图纸,这里会报错。需要用OwnerType来判断
            var thisView = (View)anno.Owner;//

            var textwidth = displayData.GetTextInBoxWidthAtIndex(0);

            var textHeight = displayData.GetTextHeightAtIndex(0);

            // dat.GetLineCount 几条线
            var lineCount = displayData.GetLineCount();
            var lineAngle = displayData.GetTextAngleAtIndex(0);
            var linePoints = (double[])displayData.GetLineAtIndex(0);
            var linePoints2 = (double[])displayData.GetLineAtIndex(1);
            var textPoint = (double[])displayData.GetTextPositionAtIndex(0);

            var thisDimAng = lineAngle * 180 / Math.PI;

            //尺寸对象
            var swDimension = (Dimension)swDisplayDimension.GetDimension();

            //获取尺寸的公差
            var cruToleranceType = swDimension.GetToleranceType();
            var cruTolerance = swDimension.Tolerance;

            if (cruToleranceType == (int)swTolType_e.swTolBILAT)
            {
                cruTolerance.GetMaxValue2(out double ToleranceValueMax); //上公差

                cruTolerance.GetMinValue2(out double ToleranceValueMin);//下公差
            }

            var TextAll = swDisplayDimension.GetText((int)swDimensionTextParts_e.swDimensionTextAll);
            var TextPrefix = swDisplayDimension.GetText((int)swDimensionTextParts_e.swDimensionTextPrefix);
            var TextSuffix = swDisplayDimension.GetText((int)swDimensionTextParts_e.swDimensionTextSuffix);
            var CalloutAbove = swDisplayDimension.GetText((int)swDimensionTextParts_e.swDimensionTextCalloutAbove);
            var CalloutBelow = swDisplayDimension.GetText((int)swDimensionTextParts_e.swDimensionTextCalloutBelow);

            var relValue = Math.Round(swDimension.GetSystemValue2("") * 1000, 3).ToString();

            MessageBox.Show(relValue);
        }

上面是代码,有一些备注。

这是初学markdown写的, 源代码继续在码云或者github上拿。

posted @
2020-04-20 14:07 
painezeng  阅读(
272)  评论(
0
编辑 
收藏 
举报

C# SolidWorks 二次开发 API —Solidworks的多开操作与连接指定版本Solidworks

C# SolidWorks 二次开发 API —Solidworks的多开操作与连接指定版本Solidworks

        今天有网友问我关于如何用Exe操作多个Solidworks的问题,其实之前我看到过解决方案,是通过进程和id获取,而不是我们平时常用的 (SldWorks)Marshal.GetActiveObject(“SldWorks.Application.27”);

        所以晚上回来查了些资料,发现了有了解决方案,我精简了一下,做了个dll.大家可以试试。    

 ''' <summary>
    ''' 创建一个新的Solidworks并返回实例
    ''' </summary>
    ''' <param name="version">指定版本号,-1表示默认.</param>
    ''' <param name="suppressDialogs">True 则禁用solidworks弹出消息.</param>
    ''' <param name="requireMainWindow">True 表示运行完显示到主窗口</param>
    ''' <param name="startProcessTimeout">返回Null 如果SolidWorks在指定时间内没有打开。</param>
    ''' <param name="createWindowTimeout">返回Null 如果SolidWorks主窗口在指定时间内没有显示.</param>
    ''' <returns></returns>
    Public Shared Function RunSolidWorks(version As Integer,
                                         visible As Boolean,
                                         Optional suppressDialogs As Boolean = False,
                                         Optional requireMainWindow As Boolean = True,
                                         Optional startProcessTimeout As Integer = 30,
                                         Optional createWindowTimeout As Integer = 15) As SldWorks

        Dim executablePath As String = CTFileSystem.GetSolidWorksExecutablePath(version)

        If File.Exists(executablePath) = False Then Return Nothing

        Dim info As ProcessStartInfo = New ProcessStartInfo(executablePath)

        If suppressDialogs Then info.Arguments = "/r"

        Dim process As Process = Process.Start(info)
        Dim app As SldWorks = Nothing
        Dim t As DateTime = DateTime.Now

        While app Is Nothing
            Threading.Thread.Sleep(1000)
            If Math.Abs(DateTime.Now.Subtract(t).Seconds) > startProcessTimeout Then Return Nothing

            'If it were possible to get a GUID from a process ID then we could use GetActiveObject instead of this
            app = GetComObjectFromProcessId(process.Id)
        End While

        t = DateTime.Now
        While IsRunning(isMainWindowCreated:=True) = False
            Threading.Thread.Sleep(1000)
            If Math.Abs(DateTime.Now.Subtract(t).Seconds) > createWindowTimeout Then Return Nothing
        End While

        If visible = False Then
            Dim frame As Frame = app.Frame()
            If frame Is Nothing Then Return app
            Dim handle As IntPtr = frame.GetHWndx64()
            If ShowWindow(handle, 0) Then Return app
        End If

        Return app
    End Function

我刚刚进行了测试,用起来比较简单。我用代码新建了两个solidworks 2018窗口:


        private SldWorks sldWorks2018_1 = null;
        private SldWorks sldWorks2018_2 = null;

        private void button1_Click(object sender, EventArgs e)
        {
            sldWorks2018_1 = PStandAlone.RunSolidWorks(26, true, false, false, 30, 15);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            sldWorks2018_2 = PStandAlone.RunSolidWorks(26, true, false, false, 30, 15);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            sldWorks2018_1.SendMsgToUser("From 2018 -1");
            sldWorks2018_2.SendMsgToUser("From 2018 -2");
        }

      

源码https://gitee.com/painezeng/PSWStandalone(vb.net)

posted @
2020-04-17 10:00 
painezeng  阅读(
250)  评论(
0
编辑 
收藏 
举报

C# SolidWorks 二次开发 API—钣金零件信息提取

C# SolidWorks 二次开发 API—钣金零件信息提取

有一段时间没有发博文了,最近有人问到钣金件的相关操作,今天我们来看看钣金零件信息的读取。

Solidworks中钣金件是有一个单独的模块,里面有一些固定的文件夹结构。

最后这个文件夹中包含了展开状态时零件的信息。如长度与折弯线相关的信息都在这里面。

一般我们要找到长 宽 厚 折弯角 与距离  折弯方向 这些信息。

输出结果如下,有些小数的处理就忽略了。大家看看就行。 

粗略的写了下,输入信息在这里。很多就是API帮助里面的例子,大家可以在中文翻译中查找到。

        private void btnSheetmetal_Click(object sender, EventArgs e)
        {
            //连接到Solidworks
            ISldWorks swApp = Utility.ConnectToSolidWorks();
            swApp.CommandInProgress = true;
            ModelDoc2 swModel = (ModelDoc2)swApp.ActiveDoc;

            //钣金 变成平板模式的特征
            List<Feature> flatPatternFeatures = new List<Feature>();

            //Bounding Box草图
            List<string> boundingSketchesName = new List<string>();

            //获取当前钣金状态--这个已经过时

            //swSMBendStateFlattened  2 = 弯曲变平;该模型回滚到FlattenBends功能之后,但恰好在相应的ProcessBends功能之前
            //swSMBendStateFolded 3 = 折弯处已折叠;模型回滚到FlattenBends ProcessBends功能对之后
            //swSMBendStateNone   0 = 不是钣金零件;没有SheetMetal功能
            //swSMBendStateSharps 1 = 弯曲处处于锐利状态;零件回滚到第一个FlattenBends功能之前

            var bendState = swModel.GetBendState();

            if (bendState == 0)
            {
                swApp.SendMsgToUser("不是钣金零件!");
                return;
            }
            //  swApp.SendMsgToUser("当前状态" + bendState);
            if (bendState != 2)
            {
                //swApp.Command((int)swCommands_e.swCommands_Flatten, "");
                //设定当前钣金状态 平板 ,下面这行代码不适用现在的零件 ,只适用于很早之前的零件
                //var setStatus = swModel.SetBendState((int)swSMBendState_e.swSMBendStateFlattened);

                //新钣金均是通过获取零件
                var swFeatureManager = swModel.FeatureManager;
                var flatPatternFolder = (FlatPatternFolder)swFeatureManager.GetFlatPatternFolder();

                var featArray = (object[])flatPatternFolder.GetFlatPatterns();

                for (int i = featArray.GetLowerBound(0); i <= featArray.GetUpperBound(0); i++)
                {
                    var feat = (Feature)featArray[i];
                    Debug.Print("    " + feat.Name);

                    flatPatternFeatures.Add(feat);
                    feat.SetSuppression2((int)swFeatureSuppressionAction_e.swUnSuppressFeature, (int)swInConfigurationOpts_e.swThisConfiguration, null);

                    //解压子特征
                    var swSubFeat = (Feature)feat.GetFirstSubFeature();

                    while ((swSubFeat != null))
                    {
                        Debug.Print(swSubFeat.Name.ToString());
                        switch (swSubFeat.GetTypeName())
                        {
                            //如果是草图
                            case "ProfileFeature":

                                var sketchSpc = (Sketch)swSubFeat.GetSpecificFeature2();
                                object[] vSketchSeg = sketchSpc.GetSketchSegments();

                                for (int j = 0; j < vSketchSeg.Length; j++)
                                {
                                    SketchSegment swSketchSeg = (SketchSegment)vSketchSeg[j];

                                    //如果直线不是折弯线,说明是边界框
                                    if (swSketchSeg.IsBendLine() == false)
                                    {
                                        boundingSketchesName.Add(swSubFeat.Name);
                                    }
                                    else if (swSketchSeg.IsBendLine() == true)
                                    {
                                        Debug.Print("钣金宽度为:" + swSketchSeg.GetLength() * 1000);
                                    }
                                }

                                break;

                            default:
                                break;
                        }

                        swSubFeat = (Feature)swSubFeat.GetNextSubFeature();
                    }
                }

                swModel.EditRebuild3();
            }

            //遍历所有特征

            var swSelMgr = (SelectionMgr)swModel.SelectionManager;
            var swFeat = (Feature)swModel.FirstFeature();

            while ((swFeat != null))
            {
                //Debug.Print(swFeat.Name.ToString());
                // Process top-level sheet metal features
                switch (swFeat.GetTypeName())
                {
                    case "SMBaseFlange":
                        //var swBaseFlange = (BaseFlangeFeatureData)swFeat.GetDefinition();

                        //Debug.Print("钣金宽度为:" + swBaseFlange.D1OffsetDistance * 1000);

                        break;

                    case "SheetMetal":
                        //这里可以获取默认的厚度                        Debug.Print(swFeat.Name.ToString());
                        SheetMetalFeatureData sheetMetalFeatureData = (SheetMetalFeatureData)swFeat.GetDefinition();
                        Debug.Print("钣金默认厚度为:" + sheetMetalFeatureData.Thickness * 1000);

                        break;

                    case "SM3dBend":

                        break;

                    case "SMMiteredFlange":

                        break;
                }
                // process sheet metal sub-features
                var swSubFeat = (Feature)swFeat.GetFirstSubFeature();

                while ((swSubFeat != null))
                {
                    // Debug.Print(swSubFeat.Name.ToString());
                    switch (swSubFeat.GetTypeName())
                    {
                        case "SketchBend":

                            GetHisBendInformation(swApp, swModel, swSubFeat);
                            break;

                        case "OneBend":

                            GetHisBendInformation(swApp, swModel, swSubFeat);

                            break;

                        default:
                            break;
                            // Probably not a sheet metal feature
                    }

                    swSubFeat = (Feature)swSubFeat.GetNextSubFeature();
                }

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

            return;
        }

        private void GetHisBendInformation(ISldWorks swApp, ModelDoc2 swModel, Feature swFeat)
        {
            MathUtility swMathUtil = default(MathUtility);
            SelectionMgr swSelMgr = default(SelectionMgr);
            OneBendFeatureData swOneBend = default(OneBendFeatureData);
            Object[] vSketchSegs = null;
            SketchSegment swSketchSeg = default(SketchSegment);
            Sketch swSketch = default(Sketch);
            Feature swSketchFeat = default(Feature);
            SketchLine swSketchLine = default(SketchLine);
            SketchPoint swSkStartPt = default(SketchPoint);
            SketchPoint swSkEndPt = default(SketchPoint);
            SelectData swSelData = default(SelectData);
            double[] nPt = new double[3];
            MathPoint swStartPt = default(MathPoint);
            MathPoint swEndPt = default(MathPoint);
            MathTransform swSkXform = default(MathTransform);
            int[] vID = null;
            int i = 0;

            swMathUtil = (MathUtility)swApp.GetMathUtility();

            swSelMgr = (SelectionMgr)swModel.SelectionManager;
            //swFeat = (Feature)swSelMgr.GetSelectedObject6(1, -1);
            //swSelData = swSelMgr.CreateSelectData();
            swOneBend = (OneBendFeatureData)swFeat.GetDefinition();

            /*swBaseBend 4
            swEdgeFlangeBend 8
            swFlat3dBend 6
            swFlatBend 2
            swFreeFormBend 10 = Obsolete
            swHemBend 9
            swLoftedBend 12
            swMirrorBend 7
            swMiterBend 5
            swNoneBend 3
            swRoundBend 1
            swRuledBend 11 = Obsolete
            swSharpBend 0
            */

            Debug.Print("Type of bend (swBendType_e): " + swOneBend.GetType());
            Debug.Print("折弯次数: " + swOneBend.GetFlatPatternSketchSegmentCount2());
            Debug.Print("折弯序号: " + swOneBend.BendOrder);
            Debug.Print("折弯角度: " + swOneBend.BendAngle * 57.3 + " deg");
            Debug.Print("折弯圆角: " + swOneBend.BendRadius);

            if (swOneBend.BendDown == true)
            {
                Debug.Print("向下折弯: " + "Yes");
            }
            else
            {
                Debug.Print("向下折弯: " + " No");
            }

            vSketchSegs = (Object[])swOneBend.FlatPatternSketchSegments2;

            for (i = 0; i <= vSketchSegs.GetUpperBound(0); i++)
            {
                swSketchSeg = (SketchSegment)vSketchSegs[i];
                swSketch = swSketchSeg.GetSketch();
                swSketchLine = (SketchLine)swSketchSeg;
                swSkStartPt = (SketchPoint)swSketchLine.GetStartPoint2();
                swSkEndPt = (SketchPoint)swSketchLine.GetEndPoint2();
                vID = (int[])swSketchSeg.GetID();

                // Get sketch feature
                swSketchFeat = (Feature)swSketch;
                swSkXform = swSketch.ModelToSketchTransform;
                swSkXform = (MathTransform)swSkXform.Inverse();

                nPt[0] = swSkStartPt.X;
                nPt[1] = swSkStartPt.Y;
                nPt[2] = swSkStartPt.Z;
                swStartPt = (MathPoint)swMathUtil.CreatePoint(nPt);
                swStartPt = (MathPoint)swStartPt.MultiplyTransform(swSkXform);
                double[] swStartPtArrayData;
                swStartPtArrayData = (double[])swStartPt.ArrayData;

                nPt[0] = swSkEndPt.X;
                nPt[1] = swSkEndPt.Y;
                nPt[2] = swSkEndPt.Z;
                swEndPt = (MathPoint)swMathUtil.CreatePoint(nPt);
                swEndPt = (MathPoint)swEndPt.MultiplyTransform(swSkXform);
                double[] swEndPtArrayData;
                swEndPtArrayData = (double[])swEndPt.ArrayData;

                // Debug.Print("File = " + swModel.GetPathName());
                Debug.Print("  Feature = " + swFeat.Name + " [" + swFeat.GetTypeName2() + "]");
                Debug.Print("    Sketch             = " + swSketchFeat.Name);
                Debug.Print("    SegID              = [" + vID[0] + ", " + vID[1] + "]");
                Debug.Print("    Start with respect to sketch   = (" + swSkStartPt.X * 1000.0 + ", " + swSkStartPt.Y * 1000.0 + ", " + swSkStartPt.Z * 1000.0 + ") mm");
                Debug.Print("    End with respect to sketch   = (" + swSkEndPt.X * 1000.0 + ", " + swSkEndPt.Y * 1000.0 + ", " + swSkEndPt.Z * 1000.0 + ") mm");
                Debug.Print("    Start with respect to model    = (" + swStartPtArrayData[0] * 1000.0 + ", " + swStartPtArrayData[1] * 1000.0 + ", " + swStartPtArrayData[2] * 1000.0 + ") mm");
                Debug.Print("    End with respect to model    = (" + swEndPtArrayData[0] * 1000.0 + ", " + swEndPtArrayData[1] * 1000.0 + ", " + swEndPtArrayData[2] * 1000.0 + ") mm");
            }
        }
  

 

posted @
2020-04-15 10:53 
painezeng  阅读(
410)  评论(
0
编辑 
收藏 
举报

C# SolidWorks 二次开发 API —如何修改草图里面的直线

C# SolidWorks 二次开发 API —如何修改草图里面的直线

 昨天有网友想知道怎么修改草图的内容,今天来带着找一找如何解决。

在之前打开和创建那个命令里面我写过如下代码 :

                    //选择对应的草图基准面
                    bool boolstatus = swModel.Extension.SelectByID2("Plane1", "PLANE", 0, 0, 0, false, 0, null, 0);

                    //创建一个2d草图
                    swModel.SketchManager.InsertSketch(true);

                    //画一条线 长度100mm  (solidworks 中系统单位是米,所以这里写0.1)
                    swModel.SketchManager.CreateLine(0, 0, 0, 0, 0.1, 0);

                    //关闭草图
                    swModel.SketchManager.InsertSketch(true);

这里面知道了草图管理器是SketchManager.

我们去API帮助里面查找SketchManager.很容易就能找到这里有个官方示例。

 

这里虽然是VBA的,但是可以大概知道大体步骤,参考这个就能知道如何读取这些信息了,可以先把这个例子弄懂。再来考虑怎么修改,我也就写几行简单的代码,把之前 我在图中画的一条直线长度 和位置修改掉。

默认当前状态:

代码如下:

        private void btnCreateSketch_Click(object sender, EventArgs e)
        {
            //如果没有打开文件,请执行打开和创建的操作:
            //BtnOpenAndNew_Click(null, null);

            //连接到Solidworks
            ISldWorks swApp = Utility.ConnectToSolidWorks();

            ModelDoc2 swModel = (ModelDoc2)swApp.ActiveDoc;

            //定义草图管理器
            SketchManager sketchManager = swModel.SketchManager;

            //按名字选择草图
            bool boolstatus = swModel.Extension.SelectByID2("Sketch1", "SKETCH", 0, 0, 0, false, 0, null, 0);

            if (boolstatus == true)
            {
                //编辑草图
                sketchManager.InsertSketch(false);
                //获取当前草图,当获取草图中的Segment对象
                Sketch sketch = swModel.GetActiveSketch2();
                object[] sketchSegments = sketch.GetSketchSegments();

                if (sketchSegments != null)
                {
                    //遍历
                    foreach (var skSeg in sketchSegments)
                    {
                        SketchSegment sketchSegment = (SketchSegment)skSeg;

                        //判断是直线时执行
                        if (sketchSegment.GetType() == (int)swSketchSegments_e.swSketchLINE)
                        {
                            SketchLine sketchLine = (SketchLine)sketchSegment;
                            SketchPoint sketchPointStart = sketchLine.GetStartPoint2();
                            SketchPoint sketchPointEnd = sketchLine.GetEndPoint2();

                            //这里显示弹出坐标,单位默认是米
                            MessageBox.Show(sketchPointStart.X.ToString() + "," + sketchPointStart.Y.ToString());
                            MessageBox.Show(sketchPointEnd.X.ToString() + "," + sketchPointEnd.Y.ToString());

                            SelectionMgr swSelMgr = swModel.SelectionManager;

                            //定义选择数据
                            SelectData swSelData = swSelMgr.CreateSelectData();

                            //选择此直线

                            sketchSegment.Select4(false, swSelData);

                            //删除当前的约束关系
                            swModel.SketchConstraintsDelAll();

                            //下在我们来修改坐标
                            sketchPointStart.X = 0.05;
                            sketchPointStart.Y = 0.04;

                            sketchPointEnd.X = 0.2;
                            sketchPointEnd.Y = 0.2;
                        }
                    }
                }

                //退出草图
                sketchManager.InsertSketch(true);
            }
        }

执行过后,文件中的草图变成了:

这里讲解的就是一个思路,大家应该能看明白吧。

具体的代码可以去我的码云或者github下载,欢迎大家提问。

 

posted @
2020-03-26 15:40 
painezeng  阅读(
174)  评论(
0
编辑 
收藏 
举报

C# SolidWorks 二次开发 API — 提升exe执行效率接近DLL

C# SolidWorks 二次开发 API — 提升exe执行效率接近DLL

          最近一段时间没更新博客,原因比较多。作为湖北人,今年的班上的不容易。当然还是要感谢各地的支援。

          今天来和大家分享一下一个关于exe提升性能的选项,因为之前主要写的exe比较多,后来改成dll之后效率提升很大,但是最近发现了一个新大陆,在exe中大量读取solidworks文件的数据时,可以先通过swApp.CommandInProgress这个设置为True 来提高性能。

           先看下API帮助中的定义:

           大概意思要是先告诉SOLIDWORKS准备在进程外将进行一系列API调用,提高了进程外应用程序的性能。

         经过测试,在做一些大量读取数据的时候,性能相对于没有设定之前提高了近4倍,结果和dll的差距已经不太大了,因为DLL里面调试没有exe方便,这样设定之后可以减少调试所需的时间,提高运行效率。

本地时间测试

Type Time
exe with CommandInProgress = Ture 111s
exe with CommandInProgress = False 460s
DLL 78s
   

 

posted @
2020-03-26 10:13 
painezeng  阅读(
126)  评论(
0
编辑 
收藏 
举报

C# SolidWorks 二次开发 API — 修改全局变量的值

C# SolidWorks 二次开发 API — 修改全局变量的值

今天来简单讲一下如何修改方程式中的一些数据,有时候一些简单的模型我们就可以利用这个全局变量来控制模型.

如下图: 我设定了零件的高度方程式与全局变量h相等.

等到我们需要更新高度时,就可以直接修改这个全局变量,做到更简单的参数化方式,这个全局变量可以是上级装配体中的信息.

 下面来具体演示下如何找api:

打开api帮助文件,搜索关键字 globalvariable,就会发现右侧的实例,是一个获取信息的.

This example shows how to get the values of equations.

//-----------------------------------------
// Preconditions:
// 1. Open public_documents\samples\tutorial\api\partequations.sldprt.
// 2. Open the Immediate window.
//
// Postconditions:
// 1. Gets each equation's value and index and whether the 
//    equation is a global variable. 
// 2. Examine the Immediate window.
//------------------------------------------
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
 
namespace Macro1CSharp.csproj
{
    public partial class SolidWorksMacro
    {
        public void Main()
        {
            ModelDoc2 swModel = default(ModelDoc2);
            EquationMgr swEqnMgr = default(EquationMgr);
            int i = 0;
            int nCount = 0;
 
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swEqnMgr = (EquationMgr)swModel.GetEquationMgr();
            Debug.Print("File = " + swModel.GetPathName());
            nCount = swEqnMgr.GetCount();
            for (i = 0; i < nCount; i++)
            {
                Debug.Print("  Equation(" + i + ")  = " + swEqnMgr.get_Equation(i));
                Debug.Print("    Value = " + swEqnMgr.get_Value(i));
                Debug.Print("    Index = " + swEqnMgr.Status);
                Debug.Print("    Global variable? " + swEqnMgr.get_GlobalVariable(i));
            }
 
        }
 
        /// <summary>
        ///  The SldWorks swApp variable is pre-assigned for you.
        /// </summary>
        public SldWorks swApp;
    }
}

我们参考这段代码来完成方程式信息的读取: 增加按钮写代码.

 参照帮助文件写完的版本大概为:

运行一下:

 

下面我们来做修改:

private void butGlobalVariables_Click(object sender, EventArgs e)
        {
            //连接solidworks
            ISldWorks swApp = Utility.ConnectToSolidWorks();

            if (swApp != null)
            {
                //获取当前模型
                ModelDoc2 swModel = (ModelDoc2)swApp.ActiveDoc;
                //定义方程式管理器
                EquationMgr swEqnMgr = default(EquationMgr);

                int i = 0;
                int nCount = 0;

                if (swModel != null)
                {
                    swEqnMgr = (EquationMgr)swModel.GetEquationMgr();
                    // nCount = swEqnMgr.GetCount();
                    //for (i = 0; i < nCount; i++)
                    //{
                    //    Debug.Print("  Equation(" + i + ")  = " + swEqnMgr.get_Equation(i));
                    //    Debug.Print("    Value = " + swEqnMgr.get_Value(i));
                    //    Debug.Print("    Index = " + swEqnMgr.Status);
                    //    Debug.Print("    Global variable? " + swEqnMgr.get_GlobalVariable(i));
                    //}

                    //修改高度为60

                    if (SetEquationValue(swEqnMgr, "h", 60))
                    {
                        swModel.ForceRebuild3(true);
                    }
                    else
                    {
                        MessageBox.Show("没有找到这个值!");
                    }
                }
            }
        }

        #region 修改全局变量所用到的方法

        public bool SetEquationValue(EquationMgr eqMgr, string name, double newValue)
        {
            int index = GetEquationIndexByName(eqMgr, name);

            if (index != -1)
            {
                eqMgr.Equation[index] = "\"" + name + "\"=" + newValue;

                return true;
            }
            else
            {
                return false;
            }
        }

        //通过名字找方程式的位置
        private int GetEquationIndexByName(EquationMgr eqMgr, string name)
        {
            int i;
            for (i = 0; i <= eqMgr.GetCount() - 1; i++)
            {
                var eqName = eqMgr.Equation[i].Split('=')[0].Replace("=", "");

                eqName = eqName.Substring(1, eqName.Length - 2); // removing the "" symbols from the name

                if (eqName.ToUpper() == name.ToUpper())
                {
                    return i;
                }
            }

            return -1;
        }

        #endregion 修改全局变量所用到的方法

到此,零件高度变成了60, 这一节先讲这么多吧.

最终代码请到码云或者github上下载.

posted @
2020-02-28 18:08 
painezeng  阅读(
284)  评论(
0
编辑 
收藏 
举报