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

C# SolidWorks 二次开发 API — 把零件中的坐标点转换到总装配中

C# SolidWorks 二次开发 API — 把零件中的坐标点转换到总装配中

今天我们来看下solidworks中的坐标矩阵转换,这个例子是把子零件中的一个基准轴的两个端点读出来,并转换到总装配的坐标系中,得到在总装配体坐标系的位置,可以进一步判断轴的真实安装方向。

直接上代码:

 private void btn_Transform_PartToAsm_Click(object sender, EventArgs e)
        {
            //连接到Solidworks

            //这个例子是把零件中的一个基准轴 的两个点的坐标转换到装配体中

            //请打开装配体,并在某个零件下选择一下基准轴

            ISldWorks swApp = Utility.ConnectToSolidWorks();

            ModelDoc2 swModel = (ModelDoc2)swApp.ActiveDoc;

            SelectionMgr swSelMgr = swModel.ISelectionManager;

            Feature swFeat = (Feature)swSelMgr.GetSelectedObject6(1, 0);

            String sAxisName = swFeat.Name;

            RefAxis RefAxis = swFeat.GetSpecificFeature2();

            var vParam = RefAxis.GetRefAxisParams();

            Component2 inletPart = swSelMgr.GetSelectedObjectsComponent4(1, 0);

            double[] nPt = new double[3];
            double[] nPt2 = new double[3];

            object vPt;
            object vPt2;

            nPt[0] = vParam[0]; nPt[1] = vParam[1]; nPt[2] = vParam[2];
            nPt2[0] = vParam[3]; nPt2[1] = vParam[4]; nPt2[2] = vParam[5];

            vPt = nPt;
            vPt2 = nPt2;

            MathUtility swMathUtil = (MathUtility)swApp.GetMathUtility();

            MathTransform mathTransform = inletPart.Transform2;

            MathTransform swXform = (MathTransform)mathTransform;

            MathPoint swMathPt = (MathPoint)swMathUtil.CreatePoint((vPt));

            MathPoint swMathPt2 = (MathPoint)swMathUtil.CreatePoint((vPt2));

            //swXform.Inverse(); 反转的话就是把装配体中的点坐标转到零件对应的坐标系统中

            swMathPt = (MathPoint)swMathPt.MultiplyTransform(swXform);

            swMathPt2 = (MathPoint)swMathPt2.MultiplyTransform(swXform);

            var x = swMathPt.ArrayData[0];
            var y = swMathPt.ArrayData[1];
            var z = swMathPt.ArrayData[2];
            var x2 = swMathPt2.ArrayData[0];
            var y2 = swMathPt2.ArrayData[1];
            var z2 = swMathPt2.ArrayData[2];

            var v1 = x2 - x;
            var v2 = y2 - y;
            var v3 = z2 - z;

            if (Math.Round(v3, 4) != 0 && Math.Round(v1, 4) == 0 && Math.Round(v2, 4) == 0)
            {
                MessageBox.Show("此轴在Z方向上");
            }

          
        }

比较全的关于矩阵转换的一篇文章:

https://cadbooster.com/complete-overview-of-matrix-transformations-in-the-solidworks-api/#available-transformations-solidworks

 

 

posted @
2019-12-31 10:12 
painezeng  阅读(
233)  评论(
0
编辑 
收藏 
举报

C# SolidWorks 二次开发 API — 实例:屏幕上1:1显示零件

C# SolidWorks 二次开发 API — 实例:屏幕上1:1显示零件

这个功能很多年前就有人提过,这只是其中一个: https://forum.solidworks.com/message/878652

因为现在的屏幕越来越大,设计好的零件可能 需要按照料模型实际尺寸,投影到屏幕上。

做这个功能是很早之前有人有这种需求,问我能不能做到,因为他们需要在一个超大的电视上显示实际的产品大小,用来介绍产品,经过我的研究,solidworks中显示有个内置比例,并且当solidworks窗口大小不一样的时候,要想1:1显示也是要调整的,而不是一次性的。

解决这个问题的思路:先得到屏幕的实际物理尺寸,然后利用solidworks中的设计尺寸,与在屏幕外用卡尺测量出来的实际尺寸之前的比例关系,可以得到当前状态下solidworks显示模型在1:1时的比例关系。

我们要的效果就是如下:

      测量尺寸和零件的实体尺寸是一致的:

 先点击自动校准,然后点右侧的1:1就可以实物显示了。 在不改窗口大小的情况,不需要再次校准。

 

 

代码就不贴了,自已去下载吧。

posted @
2019-12-18 16:53 
painezeng  阅读(
141)  评论(
0
编辑 
收藏 
举报

C# SolidWorks 二次开发 API — 实例:多实体零件导出

C# SolidWorks 二次开发 API — 实例:多实体零件导出

这一篇文章来谈一下如何快速导出一个零件中的多实体,每个实体以单独零件名,并且会简单的得到它的包围盒信息,

最终生成一个装配体。

 

 下面是零件: 以多实体进行的设计,实体并且设定了材质。

 程序会在同目录下生成相同的文件夹和装配体信息, 有了装配体,后面就方便生成BOM了(同时程序中对程序的复制 阵列做了)处理.

 

 获取实体关键代码:

 private void ListBodies()
        {
            ModelDoc2 swModel = null;
            PartDoc swPart = null;
            object vBody;
            bool bRet;

            swModel = (ModelDoc2)iswApp.ActiveDoc;
            swModel.ClearSelection2(true);
            Debug.Print("File = " + swModel.GetPathName());

            txtPath.Text = swModel.GetPathName();

            this.Text = System.IO.Path.GetFileName(txtPath.Text);

            switch (swModel.GetType())
            {
                case (int)swDocumentTypes_e.swDocPART:
                    swPart = (PartDoc)swModel;
                    // Solid bodies
                    object[] vBodyArr = null;
                    Body2 swBody = default(Body2);

                    MathTransform swMathTrans = null;
                    vBodyArr = (object[])swPart.GetBodies2((int)swBodyType_e.swSolidBody, true);

                    if ((vBodyArr != null))
                    {
                        // Debug.Print("  Number of solid bodies: " + vBodyArr.Length);

                        foreach (object vBody_loopVariable in vBodyArr)
                        {
                            vBody = vBody_loopVariable;
                            swBody = (Body2)vBody;

                            string[] vConfigName = null;
                            vConfigName = (string[])swModel.GetConfigurationNames();
                            string sMatDB = "";
                            string sMatName = swBody.GetMaterialPropertyName("", out sMatDB);

                            //bRet = swBody.RemoveMaterialProperty((int)swInConfigurationOpts_e.swAllConfiguration, (vConfigName));

                            // Debug.Print("Body--> " + swBody.Name + " " + "");

                            FeatureType Ftype = 0;

                            var childFeature = swBody.GetFeatures();

                            foreach (var item in childFeature)
                            {
                                Feature f = (Feature)item;

                                Debug.Print(swBody.Name + "-->" + f.GetTypeName());

                                if (f.GetTypeName() == "MoveCopyBody")
                                {
                                    Ftype = FeatureType.Copy;
                                }
                                if (f.GetTypeName() == "MirrorSolid")
                                {
                                    Ftype = FeatureType.Mirror;
                                }
                            }

                            Body2 swOriBody = null;

                            string swOriBodyName = "";
                            string swOriBodyBox = "";

                            if (Ftype != 0)
                            {
                                try
                                {
                                    swOriBody = swBody.GetOriginalPatternedBody(out swMathTrans);

                                    swOriBodyName = swOriBody.Name;

                                    swOriBodyBox = GetBodyBox(swOriBody);
                                }
                                catch (Exception)
                                {
                                }
                            }

                            string bbox = GetBodyBox(swBody);

                            BodyModel tempBodyM = new BodyModel(swBody.Name, sMatName, swOriBodyName, Ftype, bbox);

                            if (bbox == swOriBodyBox && swBody.Name.ToString().Contains(swOriBodyName.ToString()) == false)
                            {
                                if ((int)tempBodyM.featureT == 0)
                                {
                                    listBodies_Normally.Items.Add(tempBodyM.name);
                                }
                                else if ((int)tempBodyM.featureT == 1 && tempBodyM.name.Contains("镜向") == true) //mirror
                                {
                                    listBodies_MirrorCopy.Items.Add(tempBodyM.name + "<--M--" + tempBodyM.refBodyname);
                                    tempBodyM.comment = "镜向-" + tempBodyM.refBodyname;
                                    //tempBodyM.name = "镜像-" + tempBodyM.refBodyname + "-" ;
                                }
                                else if ((int)tempBodyM.featureT == 2 && (tempBodyM.name.Contains("复制") == true || tempBodyM.name.Contains("阵列") == true))  //copy
                                {
                                    listBodies_MirrorCopy.Items.Add(tempBodyM.name + "<--C--" + tempBodyM.refBodyname);

                                    tempBodyM.comment = "复制-" + tempBodyM.refBodyname;
                                }
                            }
                            else
                            {
                                listBodies_Normally.Items.Add(tempBodyM.name);
                            }

                            bodyModels.Add(tempBodyM);
                        }
                    }
                    break;

                case (int)swDocumentTypes_e.swDocASSEMBLY:
                    //ProcessAssembly(swApp, swModel);
                    break;

                default:
                    return;
                    break;
            }

            Debug.Print(bodyModels.Count.ToString());
        }

生成新的装配体代码:

    private void CreateNewAssembly(string assemblyName, List<string> partsname)
        {
            string assemblyDefaultPath = iswApp.GetDocumentTemplate(2, "", 0, 0, 0);

            var part = iswApp.NewDocument(assemblyDefaultPath, 0, 0, 0);

            if (part != null)
            {
                AssemblyDoc assemblyDoc = part as AssemblyDoc;

                ModelDoc2 modelDoc2 = assemblyDoc as ModelDoc2;

                ModelDocExtension swModExt = default(ModelDocExtension);

                int errors = 0;
                int warnings = 0;

                swModExt = (ModelDocExtension)modelDoc2.Extension;

                swModExt.SaveAs(assemblyName,
                    (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, errors, warnings);

                modelDoc2 = iswApp.ActiveDoc;

                int i = 0;
                int tempV = ProgressBar.Value;
                foreach (var partN in partsname)
                {
                    labStatus.Text = "正在装配-->" + Path.GetFileNameWithoutExtension(partN);

                    ProgressBar.Value = tempV + i;

                    iswApp.OpenDoc6(partN.ToString(), 1, 32, "", ref errors, ref warnings);

                    assemblyDoc = (AssemblyDoc)iswApp.ActivateDoc3(System.IO.Path.GetFileNameWithoutExtension(assemblyName) + ".sldasm", true, 0, errors);

                    Component2 swInsertedComponent = default(Component2);

                    swInsertedComponent = assemblyDoc.AddComponent5(partN, 0, "", false, "", 0, 0, 0);

                    modelDoc2 = iswApp.ActiveDoc;
                    modelDoc2.ClearSelection2(true);

                    modelDoc2.Extension.SelectByID2(swInsertedComponent.GetSelectByIDString(), "COMPONENT", 0, 0, 0, false, 0, null, 0);

                    assemblyDoc.UnfixComponent();

                    modelDoc2.ClearSelection2(true);

                    modelDoc2.Extension.SelectByID2("Point1@Origin@" + swInsertedComponent.GetSelectByIDString(), "EXTSKETCHPOINT", 0, 0, 0, false, 0, null, 0);

                    modelDoc2.Extension.SelectByID2("Point1@Origin", "EXTSKETCHPOINT", 0, 0, 0, true, 0, null, 0);

                    Mate2 mate2 = default(Mate2);

                    mate2 = assemblyDoc.AddMate5(20, -1, false, 0, 0, 0, 0, 0.001, 0, 0, 0, false, false, 0, out int warings);
                    modelDoc2.ClearSelection2(true);
                    modelDoc2.EditRebuild3();

                    iswApp.CloseDoc(partN);

                    i = i + 1;
                }

                iswApp.ActivateDoc3(System.IO.Path.GetFileNameWithoutExtension(assemblyName) + ".sldasm", true, 0, errors);
                modelDoc2 = iswApp.ActiveDoc;
                modelDoc2.ShowNamedView2("*等轴测", 7);
                modelDoc2.ViewZoomtofit2();
                modelDoc2.Save();
            }

            ProgressBar.Value = ProgressBar.Maximum;
        }

完整代码请去码云或者github.

https://gitee.com/painezeng/CSharpAndSolidWorks

https://github.com/painezeng/CSharpAndSolidWorks

posted @
2019-12-16 13:10 
painezeng  阅读(
501)  评论(
0
编辑 
收藏 
举报