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
编辑 
收藏 
举报

C# SolidWorks 二次开发 API —dll插件如何让 winform 类似ShowDialog,但还能操作solidworks

C# SolidWorks 二次开发 API —dll插件如何让 winform 类似ShowDialog,但还能操作solidworks

这篇文章记录一下,这次看api帮助解决到的一个问题:

          由于之前我都是先做好的exe独立开发,后来改成插件形式后遇到的问题。以前经常利用窗体的ShowDialog特性,让程序暂停,让用户进行对象的自定义选择操作,但是到了dll中出现了问题,因为dll和solidworks主进程是一个,所以当用了页面的ShowDialog之后,solidworks就再也无法操作了。这个问题之前花了一天多时间都没搞定,想了好多办法,最后利用的doevents解决的,但是效果不是特别好。

         原来solidworks的帮助文件中已经有了解决方案: 只需要使用 Application.Run(winform)就可以了,我刚才进行了测试,很好用,至于还有没有别的问题,后面再测试一下。

        

         参考链接:

http://help.solidworks.com/2018/English/api/sldworksapiprogguide/overview/Keystrokes_and_Accelerator_Keys_and_ActiveX_Modeless_Dialogs_and_PropertyManager_Pages.htm

posted @
2020-02-22 18:12 
painezeng  阅读(
131)  评论(
0
编辑 
收藏 
举报

C# SolidWorks 二次开发 API — 2018版 中文-完整版共享

C# SolidWorks 二次开发 API — 2018版 中文-完整版共享

由于还在湖北老家,暂时无法回去工作,休息期间我又把2018的api帮助文档看了一下,我把之前翻译的文件免费共享下,希望能对大家有所帮助。

https://download.csdn.net/download/zengqh0314/12170828

posted @
2020-02-19 12:56 
painezeng  阅读(
208)  评论(
0
编辑 
收藏 
举报

C# SolidWorks 二次开发 API — 实例:随机上色

C# SolidWorks 二次开发 API — 实例:随机上色

随机上色这个功能做起来不算复杂,但是要想做的比较完美也不简单。

这一篇文章我就只做随机给装配体中的零件上色。

上色前:

 上色后:

 

简单的代码:

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

            if (swApp != null)
            {
                ModelDoc2 swModel = (ModelDoc2)swApp.ActiveDoc;

                Configuration swConf = swModel.GetActiveConfiguration();

                Component2 swRootComp = swConf.GetRootComponent();

                //遍历

                Utility.TraverseCompXform(swRootComp, 0, true);

                swModel.WindowRedraw();

                swModel.EditRebuild3();
            }
        }



以下是上色代码:
 //如果要设定颜色
                    if (setcolor == true)
                    {
                        double[] matPropVals = swModel.MaterialPropertyValues;
                        var tempC = GetRadomColor(System.IO.Path.GetFileNameWithoutExtension(swModel.GetPathName()));
                        matPropVals[0] = Convert.ToDouble(tempC.R) / 255;
                        matPropVals[1] = Convert.ToDouble(tempC.G) / 255;
                        matPropVals[2] = Convert.ToDouble(tempC.B) / 255;
                        swModel.MaterialPropertyValues = matPropVals;

                        swModel.WindowRedraw();
                    }


 public static System.Drawing.Color GetRadomColor(string name)
        {
            Random rnd = new Random();

            //这里可以根据需要指定颜色。
            if (name.Contains("m1"))
            {
                return System.Drawing.Color.Red;
            }

            return System.Drawing.Color.FromArgb(
                 rnd.Next(0, 255), /*红色*/
                 rnd.Next(0, 255), /*绿色*/
                 rnd.Next(0, 255)  /*蓝色*/ );
        }

具体代码见github或者码云,链接可以在之前的博文中找到。

posted @
2020-01-14 15:58 
painezeng  阅读(
227)  评论(
0
编辑 
收藏 
举报

C# SolidWorks 二次开发 API — 插入图块和属性块

C# SolidWorks 二次开发 API — 插入图块和属性块

在还没有取消所有2D图纸时,我们难免需要在图纸中插入一些标准图块,或者像AutoCAD那个的属性块。

 

如下图: 

 

 

直接上代码:

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

            ModelDoc2 swModel = (ModelDoc2)swApp.ActiveDoc;

            DrawingDoc dc = (DrawingDoc)swModel;

            // SelectionMgr selectionMgr = (SelectionMgr)swModel.SelectionManager;

            double[] nPt = new double[3];

            nPt[0] = 0;
            nPt[1] = 0;
            nPt[2] = 0;

            MathUtility swMathUtil = swApp.GetMathUtility();

            MathPoint swMathPoint = swMathUtil.CreatePoint(nPt);

            double blockScale = 1;

            string blockPath = @"D:\09_Study\CSharpAndSolidWorks\CSharpAndSolidWorks\TemplateModel\TestBlock.SLDBLK";

            //插入图块
            var swBlockInst = InsertBlockReturnInst(swApp, swModel, swMathPoint, blockPath, blockScale);

            //  swModel.SketchManager.MakeSketchBlockFromFile(mathPoint, blockPath, false, blockScale, 0);

            //修改块的属性(如果只是普通的图块,则无需要这一步。直接使用上面的一行插入图块即可)
            swBlockInst.SetAttributeValue("Title1", "Paine");
        }

        /// <summary>
        /// 插入并返回最后一个图块实例
        /// </summary>
        /// <param name="sldWorks"></param>
        /// <param name="modelDoc2"></param>
        /// <param name="mathPoint"></param>
        /// <param name="blockPath"></param>
        /// <param name="blockScale"></param>
        /// <returns></returns>
        private SketchBlockInstance InsertBlockReturnInst(ISldWorks sldWorks, ModelDoc2 modelDoc2, MathPoint mathPoint, String blockPath, double blockScale)
        {
            SketchBlockInstance swBlockInst;
            List<String> NowBlockName = new List<String>();
            var swModel = modelDoc2;
            Boolean boolstatus = swModel.Extension.SelectByID2(System.IO.Path.GetFileNameWithoutExtension(blockPath), "SUBSKETCHDEF", 0, 0, 0, false, 0, null, 0);

            if (boolstatus == true)
            {
                Feature swFeat = swModel.SelectionManager.GetSelectedObject6(1, 0);
                var swSketchBlockDef = swFeat.GetSpecificFeature2();

                var nbrBlockInst = swSketchBlockDef.GetInstanceCount;

                if (nbrBlockInst > 0)
                {
                    var vBlockInst = swSketchBlockDef.GetInstances();

                    for (int i = 0; i < nbrBlockInst; i++)
                    {
                        swBlockInst = vBlockInst[i];

                        NowBlockName.Add(swBlockInst.Name.ToString());
                    }

                    swModel.SketchManager.MakeSketchBlockFromFile(mathPoint, blockPath, false, blockScale, 0);

                    swModel.ClearSelection2(true);

                    boolstatus = swModel.Extension.SelectByID2(System.IO.Path.GetFileNameWithoutExtension(blockPath), "SUBSKETCHDEF", 0, 0, 0, false, 0, null, 0);

                    swFeat = swModel.SelectionManager.GetSelectedObject6(1, 0);
                    swSketchBlockDef = swFeat.GetSpecificFeature2();

                    nbrBlockInst = swSketchBlockDef.GetInstanceCount;

                    if (nbrBlockInst > 0)
                    {
                        vBlockInst = swSketchBlockDef.GetInstances();

                        for (int j = 0; j < nbrBlockInst; j++)
                        {
                            swBlockInst = vBlockInst[j];
                            if (!NowBlockName.Contains(swBlockInst.Name.ToString()))
                            {
                                swModel.Extension.SelectByID2(swBlockInst.Name, "SUBSKETCHINST", 0, 0, 0, false, 0, null, 0);
                                swBlockInst = GetSketchBlockInstanceFromSelection();
                                return swBlockInst;
                            }
                        }
                    }
                    return null;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                var swSketchBlockDef = swModel.SketchManager.MakeSketchBlockFromFile(mathPoint, blockPath, false, blockScale, 0);
                swBlockInst = swSketchBlockDef.GetInstances()[0];

                return swBlockInst;
            }
        }

        private SketchBlockInstance GetSketchBlockInstanceFromSelection()
        {
            ISldWorks swApp = Utility.ConnectToSolidWorks();

            ModelDoc2 swModel;
            ModelDocExtension swModelDocExt;
            SketchBlockInstance SketchBlockInstance;

            DateTime time = DateTime.Now;

            try
            {
                swModel = swApp.ActiveDoc;
                swModelDocExt = swModel.Extension;

                SelectionMgr swSelectionMgr;
                swSelectionMgr = swModel.SelectionManager;

                string SelectByString = "";
                string ObjectType = "";
                int type;
                double x;
                double y;
                double z;

                if (swSelectionMgr.GetSelectedObjectCount2(-1) > 1)
                {
                    // Return only a SketchblockInstance when only one is selected...
                    // modify if you want return more than one (or only the first) selected Sketchblockinstance
                    return null;
                }

                swSelectionMgr.GetSelectionSpecification(1, out SelectByString, out ObjectType, out type, out x, out y, out z);
                Debug.WriteLine(SelectByString + " " + ObjectType + " " + type);

                if (type == (int)swSelectType_e.swSelSUBSKETCHINST)
                {
                    SketchBlockInstance = swSelectionMgr.GetSelectedObject6(1, -1);
                    Debug.WriteLine("Found:" + SketchBlockInstance.Name);
                    return SketchBlockInstance;
                }
                else if (type == (int)swSelectType_e.swSelSKETCHSEGS | type == (int)swSelectType_e.swSelSKETCHPOINTS)
                {
                    // Show if a sketchblockinstance has the same name
                    SketchManager SwSketchMgr;
                    SwSketchMgr = swModel.SketchManager;

                    object[] blockDefinitions = (object[])SwSketchMgr.GetSketchBlockDefinitions();
                    foreach (SketchBlockDefinition blockDef in blockDefinitions)
                    {
                        foreach (SketchBlockInstance blockInstance in blockDef.GetInstances())
                        {
                            if (SelectByString.EndsWith(blockInstance.Name))
                            {
                                Debug.WriteLine("Found:" + blockInstance.Name);
                                return blockInstance;
                            }
                        }
                    }
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                Debug.WriteLine(DateTime.Now.Subtract(time).Milliseconds);
            }

            return null;
        }
  

 

posted @
2020-01-06 13:30 
painezeng  阅读(
225)  评论(
0
编辑 
收藏 
举报