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

C# SolidWorks 二次开发 API — 在工程图中获取模型

C# SolidWorks 二次开发 API — 在工程图中获取模型

最近两周比较忙,没怎么写新的博客,昨天有网友问到如何在工程图中获取零件相关属性。今天就把步骤写下来,之前有一篇博文已经写过如何遍历视图了,其实只需要获取视图中的模型就可以,这样就可以像在零件或者装配环境中操作了。

今天我们来个简单一点的:

请打开一个工程图,并选中其中一个视图。

这后点击工具上的按钮,就会提示零件的路径。

 

 

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

            ModelDoc2 swModel = (ModelDoc2)swApp.ActiveDoc;

            // DrawingDoc dc = (DrawingDoc)swModel;

            SelectionMgr selectionMgr = (SelectionMgr)swModel.SelectionManager;

            //获取选择的视图对象
            View view = (View)selectionMgr.GetSelectedObject5(1);

            //获取视图中的引用模型
            var viewModel = view.ReferencedDocument;

            //其它读取属性请参考博文 读取零件属性 ->BtnGetPartData_Click

            MessageBox.Show(viewModel.GetPathName());
        }

 

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

C# SolidWorks 二次开发 API — 利用射线选择相对面

C# SolidWorks 二次开发 API — 利用射线选择相对面

最近的项目中需要用到一个新的功能,在用户选择了一个面的情况下,找到此面的对面那个面。用来在这两个面上创建一对特征。

如下图,需要选中红色箭头中的那个面:

通过测试,可以通过 SelectByRay这个函数来获取。

意思是在某个点,画一条射线,看哪个面与它相交。

需要注意的是,如果一个轴线上有很多个相交面它会选择最后一个.

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

            ModelDoc2 swModel = (ModelDoc2)swApp.ActiveDoc;

            Face2 swSelFace = default(Face2);
            SelectionMgr swSelMgr = (SelectionMgr)swModel.SelectionManager;

            //获取选择数据
            SelectData swSelData = default(SelectData);

            swSelData = swSelMgr.CreateSelectData();

            swSelFace = (Face2)swSelMgr.GetSelectedObject6(1, 0);

            var t = (double[])swSelFace.Normal;

            //获取屏幕鼠标选择的那个点
            var mousePoint = (double[])swSelMgr.GetSelectionPoint2(1, 0);

            swModel.ClearSelection2(true);

            //创建Ray选择

            var boolstatus = swModel.Extension.SelectByRay(mousePoint[0], mousePoint[1], mousePoint[2], t[0], t[1], t[2], 0.1, 2, false, 0, 0);

            if (boolstatus == true)
            {
                MessageBox.Show("选择完成!");
            }
        }

 

 

posted @
2019-11-25 13:53 
painezeng  阅读(
101)  评论(
0
编辑 
收藏 
举报

C# SolidWorks 二次开发 API — 实例:打包文件

C# SolidWorks 二次开发 API — 实例:打包文件

我们开发的程序使用过程中经常要使用一些做好的模板,尤其是参数化的时候,这样就难免有一些文件需要从指定的地方复制过来,或者说还要把文件名替换掉,还可以加一些前缀或者后缀。这个例子也只是一个最简单的打包方案,当然大家还可以参考API帮助文件中的Pack And Go函数来打包文件。

        /// <summary>
        /// 不打开文件,复制文件
        /// </summary>
        /// <param name="sourcefile">源文件路径</param>
        /// <param name="target">目标文件</param>
        /// <param name="ReplaceFrom">需要替换的文件</param>
        /// <param name="ReplaceTo">替换成什么</param>
        /// <param name="likeFile">是否模糊匹配</param>
        /// <param name="ReplaceFrom2">替换字符2</param>
        /// <param name="ReplaceTo2">第二次替换成什么</param>
        /// <param name="likeFile2">模糊匹配?</param>
        public void CopySolidworksFile(string sourcefile, string target, string ReplaceFrom = "", string ReplaceTo = "", bool likeFile = true, string ReplaceFrom2 = "", string ReplaceTo2 = "", bool likeFile2 = false)
        {
            ISldWorks swApp = Utility.ConnectToSolidWorks();

            target = System.IO.Path.GetDirectoryName(target) + @"\";

            int sourcecount = 0;

            string[] sourcefiles = null;

            string[] targetfiles = null;

            object[] depends;

            var sourcefileName = System.IO.Path.GetFileName(sourcefile);
            var oldSourcefiles = sourcefiles;
            sourcefiles = new string[sourcecount + 1];
            if (oldSourcefiles != null)
                Array.Copy(oldSourcefiles, sourcefiles, Math.Min(sourcecount + 1, oldSourcefiles.Length));
            var oldTargetfiles = targetfiles;
            targetfiles = new string[sourcecount + 1];
            if (oldTargetfiles != null)
                Array.Copy(oldTargetfiles, targetfiles, Math.Min(sourcecount + 1, oldTargetfiles.Length));
            sourcefiles[sourcecount] = sourcefile;
            progressBarCopy.Value = 10;
            if (ReplaceFrom != "")
            {
                if (likeFile == true)
                    targetfiles[sourcecount] = target + sourcefileName.Replace(ReplaceFrom, ReplaceTo).Replace(ReplaceFrom2, ReplaceTo2);
                else if (sourcefileName.ToUpper() == ReplaceFrom.ToUpper())
                    targetfiles[sourcecount] = target + sourcefileName.Replace(ReplaceFrom, ReplaceTo).Replace(ReplaceFrom2, ReplaceTo2);
                else
                    targetfiles[sourcecount] = target + sourcefileName.Replace(ReplaceFrom2, ReplaceTo2);
            }
            else
                targetfiles[sourcecount] = target + sourcefileName;

            if (FileSystem.Dir(targetfiles[sourcecount]) != "")
            {
                if (Interaction.MsgBox(targetfiles[sourcecount] + "已经存在,是否替换?", Constants.vbYesNo, "文件打包") == Constants.vbNo)
                {
                    progressBarCopy.Value = 0;
                    return;
                }
            }

            try
            {
                FileSystem.FileCopy(sourcefiles[sourcecount], targetfiles[sourcecount]);
            }
            catch (Exception ex)
            {
            }
            progressBarCopy.Value = 35;
            sourcecount = sourcecount + 1;

            if (FileSystem.Dir(Strings.Replace(sourcefile, ".SLDASM", ".SLDDRW")) != "")
            {
                oldSourcefiles = sourcefiles;
                sourcefiles = new string[sourcecount + 1];
                if (oldSourcefiles != null)
                    Array.Copy(oldSourcefiles, sourcefiles, Math.Min(sourcecount + 1, oldSourcefiles.Length));
                oldTargetfiles = targetfiles;
                targetfiles = new string[sourcecount + 1];
                if (oldTargetfiles != null)
                    Array.Copy(oldTargetfiles, targetfiles, Math.Min(sourcecount + 1, oldTargetfiles.Length));

                sourcefiles[sourcecount] = Strings.Replace(sourcefile, ".SLDASM", ".SLDDRW");
                sourcefileName = System.IO.Path.GetFileName(sourcefiles[sourcecount]);
                if (ReplaceFrom != "")
                {
                    if (likeFile == true)
                        targetfiles[sourcecount] = target + sourcefileName.Replace(ReplaceFrom, ReplaceTo).Replace(ReplaceFrom2, ReplaceTo2);
                    else if (sourcefileName.ToUpper() == ReplaceFrom.ToUpper())
                        targetfiles[sourcecount] = target + sourcefileName.Replace(ReplaceFrom, ReplaceTo).Replace(ReplaceFrom2, ReplaceTo2);
                    else
                        targetfiles[sourcecount] = target + sourcefileName.Replace(ReplaceFrom2, ReplaceTo2);
                }
                else
                    targetfiles[sourcecount] = target + sourcefileName;

                if (FileSystem.Dir(targetfiles[sourcecount]) != "")
                {
                    if (Interaction.MsgBox(targetfiles[sourcecount] + "已经存在,是否替换?", Constants.vbYesNo, "文件打包") == Constants.vbNo)
                        return;
                }

                try
                {
                    FileSystem.FileCopy(sourcefiles[sourcecount], targetfiles[sourcecount]);
                }
                catch (Exception ex)
                {
                }
                sourcecount = sourcecount + 1;
            }
            progressBarCopy.Value = 50;
            depends = (string[])swApp.GetDocumentDependencies2(sourcefile, true, true, false);

            if (depends == null)
                return;
            bool bRet;
            var idx = 1;

            while (idx <= Information.UBound(depends))
            {
                oldSourcefiles = sourcefiles;
                sourcefiles = new string[sourcecount + 1];
                if (oldSourcefiles != null)
                    Array.Copy(oldSourcefiles, sourcefiles, Math.Min(sourcecount + 1, oldSourcefiles.Length));
                oldTargetfiles = targetfiles;
                targetfiles = new string[sourcecount + 1];
                if (oldTargetfiles != null)
                    Array.Copy(oldTargetfiles, targetfiles, Math.Min(sourcecount + 1, oldTargetfiles.Length));

                sourcefiles[sourcecount] = depends[idx].ToString();
                sourcefileName = System.IO.Path.GetFileName(depends[idx].ToString());
                if (ReplaceFrom != "")
                {
                    if (likeFile == true)
                        targetfiles[sourcecount] = target + sourcefileName.Replace(ReplaceFrom, ReplaceTo).Replace(ReplaceFrom2, ReplaceTo2);
                    else if (sourcefileName.ToUpper() == ReplaceFrom.ToUpper())
                        targetfiles[sourcecount] = target + sourcefileName.Replace(ReplaceFrom, ReplaceTo).Replace(ReplaceFrom2, ReplaceTo2);
                    else
                        targetfiles[sourcecount] = target + sourcefileName.Replace(ReplaceFrom2, ReplaceTo2);
                }
                else
                    targetfiles[sourcecount] = target + sourcefileName;

                try
                {
                    FileSystem.FileCopy(sourcefiles[sourcecount], targetfiles[sourcecount]);
                }
                catch (Exception ex)
                {
                }

                idx = idx + 2;
                sourcecount = sourcecount + 1;
            }

            // swApp.SendMsgToUser("Done")
            progressBarCopy.Value = 80;
            for (int n = 0; n <= sourcecount - 1; n++)
            {
                var NewName = targetfiles[n];

                var RefQ = swApp.GetDocumentDependenciesCount(NewName, 1, 1) / (double)2;

                // Debug.Print(NewName & "--->参考文件有  " & RefQ)

                if (RefQ > 0)
                {
                    var q = 0;
                    for (q = 0; q <= sourcecount - 1; q++)
                    {
                        if (n == q)
                        {
                        }
                        else
                            bRet = swApp.ReplaceReferencedDocument(targetfiles[n], System.IO.Path.GetFileName(sourcefiles[q]), targetfiles[q]);
                    }
                }
            }

            progressBarCopy.Value = 95;
        }
  

 

posted @
2019-11-22 09:15 
painezeng  阅读(
214)  评论(
0
编辑 
收藏 
举报