示例#1
0
 public Vis(ISldWorks _swApp, IModelDoc2 _myModel)
 {
     myModel = _myModel;
     swApp = _swApp;
     myModel = (ModelDoc2)swApp.ActiveDoc;
     myPart = (PartDoc)myModel;
     myMatVisProps = myPart.GetMaterialVisualProperties();
 }
示例#2
0
 protected virtual void DetachPartEvents(PartDoc part)
 {
 }
 protected override void UnsubscribePartEvents(PartDoc part)
 {
     part.SaveToStorageNotify -= OnWriteToStreamNotify;
 }
示例#4
0
 protected override void DetachPartEvents(PartDoc part)
 {
     part.AddItemNotify -= OnAddItemNotify;
 }
示例#5
0
        /// <summary>
        /// 天花子装配导出DXF图纸
        /// </summary>
        /// <param name="swApp"></param>
        /// <param name="tree"></param>
        /// <param name="dxfPath"></param>
        /// <param name="userId"></param>
        public void CeilingAssyToDxf(SldWorks swApp, SubAssy subAssy, string dxfPath, int userId)
        {
            swApp.CommandInProgress = true;
            List <CeilingCutList> celingCutLists = new List <CeilingCutList>();
            string assyPath = subAssy.SubAssyPath;

            if (assyPath.Length == 0)
            {
                return;
            }
            try
            {
                //打开模型
                ModelDoc2 swModel = swApp.OpenDoc6(assyPath, (int)swDocumentTypes_e.swDocASSEMBLY,
                                                   (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings) as ModelDoc2;
                if (swModel == null)
                {
                    MessageBox.Show("模型不存在,请认真检查", "模型不存在");
                    return;
                }
                string modulePath = dxfPath + @"\" + subAssy.SubAssyName;
                if (!Directory.Exists(modulePath))
                {
                    Directory.CreateDirectory(modulePath);
                }
                swModel.ForceRebuild3(true);
                AssemblyDoc swAssy = swModel as AssemblyDoc;
                //获取所有零部件集合
                var compList = swAssy.GetComponents(false);
                //遍历集合中的所有零部件对象
                foreach (var swComp in compList)
                {
                    //判断零件是否被压缩,不显示,封套,零件名称不是以sldprt或SLDPRT结尾
                    if (swComp.Visible == 1 && !swComp.IsEnvelope() && !swComp.IsSuppressed() &&
                        (swComp.GetPathName().EndsWith(".sldprt") || swComp.GetPathName().EndsWith(".SLDPRT")))
                    {
                        Component2 swParentComp = swComp.GetParent();
                        //总装没有父装配体
                        if (swParentComp == null)
                        {
                            ConfigurationManager swConfigMgr = swModel.ConfigurationManager;
                            Configuration        swConfig2   = swConfigMgr.ActiveConfiguration;
                            swParentComp = swConfig2.GetRootComponent3(true);
                        }
                        //判断父装配体是否可视,并且不封套
                        if (swParentComp.Visible == 1 && !swParentComp.IsEnvelope() && !swComp.IsSuppressed())
                        {
                            PartDoc swPart = swComp.GetModelDoc2();
                            //获取文档中的额Body对象集合
                            var bodyList = swPart.GetBodies2(0, false);
                            //遍历集合中的所有Body对象,判断是否为钣金
                            foreach (var swBody in bodyList)
                            {
                                //如果是钣金则将零件地址添加到列表中
                                if (swBody.IsSheetMetal())
                                {
                                    if (sheetMetaDic.ContainsKey(swComp.GetPathName()))
                                    {
                                        sheetMetaDic[swComp.GetPathName()] += 1;
                                    }
                                    else
                                    {
                                        sheetMetaDic.Add(swComp.GetPathName(), 1);
                                    }
                                }
                            }
                        }
                    }
                }
                //关闭装配体零件
                swApp.CloseDoc(assyPath);
                //遍历钣金零件
                foreach (var sheetMeta in sheetMetaDic)
                {
                    //打开模型
                    ModelDoc2 swPart = swApp.OpenDoc6(sheetMeta.Key, (int)swDocumentTypes_e.swDocPART,
                                                      (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings) as ModelDoc2;
                    Feature        swFeat    = (Feature)swPart.FirstFeature();
                    CeilingCutList cutRecord = new CeilingCutList()
                    {
                        SubAssyId = subAssy.SubAssyId,
                        Quantity  = sheetMeta.Value,
                        UserId    = userId
                    };
                    while (swFeat != null)
                    {
                        var suppStatus = swFeat.IsSuppressed2((int)swInConfigurationOpts_e.swThisConfiguration, null);
                        if (suppStatus[0] == false && swFeat.GetTypeName() == "SolidBodyFolder")
                        {
                            BodyFolder swBodyFolder = (BodyFolder)swFeat.GetSpecificFeature2();
                            swBodyFolder.SetAutomaticCutList(true);
                            swBodyFolder.SetAutomaticUpdate(true);
                            Feature SubFeat = swFeat.GetFirstSubFeature();
                            if (SubFeat != null)
                            {
                                Feature    ownerFeature    = SubFeat.GetOwnerFeature();
                                BodyFolder swSubBodyFolder = ownerFeature.GetSpecificFeature2();
                                swSubBodyFolder.UpdateCutList();
                                string val         = string.Empty;
                                string valout      = string.Empty;
                                bool   wasResolved = false;
                                bool   linkToProp  = false;
                                SubFeat.CustomPropertyManager.Get4("Bounding Box Length", false, out val, out valout);
                                cutRecord.Length = Convert.ToDecimal(valout);
                                SubFeat.CustomPropertyManager.Get4("Bounding Box Width", false, out val, out valout);
                                cutRecord.Width = Convert.ToDecimal(valout);
                                SubFeat.CustomPropertyManager.Get4("Sheet Metal Thickness", false, out val, out valout);
                                cutRecord.Thickness = Convert.ToDecimal(valout);
                                SubFeat.CustomPropertyManager.Get4("Material", false, out val, out valout);
                                cutRecord.Materials = valout;
                                swPart.GetActiveConfiguration().CustomPropertyManager.Get6("Description", false, out valout, out val, out wasResolved, out linkToProp);
                                cutRecord.PartDescription = valout;
                                cutRecord.PartNo          = swPart.GetTitle().Substring(0, swPart.GetTitle().Length - 7);
                                celingCutLists.Add(cutRecord);//将信息添加到集合中
                            }
                        }
                        swFeat = swFeat.GetNextFeature();
                    }
                    PartToDxf(swApp, swPart, modulePath);
                    //关闭零件
                    swApp.CloseDoc(sheetMeta.Key);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(assyPath + "导图过程发生异常,详细:" + ex.Message);
            }
            finally
            {
                sheetMetaDic.Clear();
                swApp.CloseDoc(assyPath);        //关闭,很快
                swApp.CommandInProgress = false; //及时关闭外部命令调用,否则影响SolidWorks的使用
            }
            //基于事务ceilingCutLists提交SQLServer
            if (celingCutLists.Count == 0)
            {
                return;
            }
            try
            {
                if (objCeilingCutListService.ImportCutList(celingCutLists))
                {
                    celingCutLists.Clear();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Cutlist导入数据库失败" + ex.Message);
            }
        }
示例#6
0
 protected override void UnsubscribePartEvents(PartDoc part)
 {
     part.RegenPostNotify2 -= OnRegenPostNotify;
 }
        // Set Materials
        public void ApplyMaterial(string partPath, string confName, int levelId, SldWorks swapp)
        {
            try
            {
                if (swapp == null)
                {
                    if (partPath == "")
                    {
                        swapp    = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
                        _swmodel = swapp.ActiveDoc;
                    }
                    else
                    {
                        swapp = new SldWorks {
                            Visible = true
                        };
                        swapp.OpenDoc6(partPath, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_LoadModel, confName, 0, 0);
                        _swmodel = swapp.ActivateDoc(partPath);
                        _swmodel = swapp.ActiveDoc;
                    }
                }
                else
                {
                    if (partPath == "")
                    {
                        _swmodel = swapp.ActiveDoc;
                    }
                    else
                    {
                        //swapp = new SldWorks { Visible = true };
                        swapp.OpenDoc6(partPath, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_LoadModel, confName, 0, 0);
                        _swmodel = swapp.ActivateDoc(partPath);
                        _swmodel = swapp.ActiveDoc;
                    }
                }


                // Путь к APPDATA
                var userAppData = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
                // Создаем папку SW-Complex
                var folderAppData = userAppData + "\\" + "SW-Complex";

                //if (File.Exists(folderAppData) == false)
                //{
                Directory.CreateDirectory(folderAppData);
                //}

                swapp.SetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swFileLocationsMaterialDatabases, folderAppData);     // задаем базы данных материалов
                //swapp.SetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swFileLocationsMaterialDatabases, "C:\\Program Files\\SW-Complex"); // задаем базы данных материалов

                _swPartDoc = ((PartDoc)(_swmodel));

                var dbMatName = "vents-materials.sldmat";

                var addMatXml = new ToSQL();

                if (_swmodel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY)
                {
                    _swmodel.ForceRebuild3(false);
                    Component2 comp        = _swmodel.ISelectionManager.GetSelectedObject3(1);
                    PartDoc    swPartAssem = comp.GetModelDoc();

                    //// удаляем материал
                    //swPartAssem.SetMaterialPropertyName("", "");

                    // применяем материал
                    swPartAssem.SetMaterialPropertyName2(confName, dbMatName, addMatXml.AddMaterialtoXml(levelId));
                    _swmodel.ClearSelection2(true);
                    _swmodel.ForceRebuild3(false);
                }
                else if (_swmodel.GetType() == (int)swDocumentTypes_e.swDocPART)
                {
                    // Если имя не пустое
                    if (partPath != "")
                    {
                        //// удаляем материал
                        //swPartDoc.SetMaterialPropertyName("", "");

                        // применяем материал
                        _swPartDoc.SetMaterialPropertyName2(confName, dbMatName, addMatXml.AddMaterialtoXml(levelId));

                        _swmodel.ForceRebuild3(false);
                        _swmodel.Save3((int)swSaveAsOptions_e.swSaveAsOptions_Silent, 0, 0);
                        swapp.CloseDoc(partPath);
                        swapp.ExitApp();
                        swapp = null;
                    }
                    else
                    {
                        //// удаляем материал
                        //swPartDoc.SetMaterialPropertyName(confName, "");

                        // применяем материал
                        _swPartDoc.SetMaterialPropertyName2(confName, dbMatName, addMatXml.AddMaterialtoXml(levelId));
                    }
                }
            }
            catch (Exception ex)
            {
                //swapp.SendMsgToUser(ex.Message);
                MessageBox.Show(ex.Message + ";" + ex.StackTrace);
                Error = ex.Message;
            }
        }
示例#8
0
        protected override void Command()
        {
            CreerDossierDVP();

            WindowLog.Ecrire(String.Format("Dossier :\r\n{0}", new DirectoryInfo(DossierExport).Name));

            try
            {
                eTypeCorps       Filtre        = PrendreEnCompteTole ? eTypeCorps.Barre | eTypeCorps.Tole : eTypeCorps.Barre;
                HashSet <String> HashMateriaux = new HashSet <string>(ListeMateriaux);

                var dic = MdlBase.DenombrerDossiers(ComposantsExterne,
                                                    fDossier =>
                {
                    BodyFolder swDossier = fDossier.GetSpecificFeature2();

                    if (Filtre.HasFlag(swDossier.eTypeDeDossier()) && HashMateriaux.Contains(swDossier.eGetMateriau()))
                    {
                        return(true);
                    }

                    return(false);
                }
                                                    );

                if (ListerUsinages)
                {
                    Nomenclature.TitreColonnes("Barre ref.", "Materiau", "Profil", "Lg", "Nb", "Usinage Ext 1", "Usinage Ext 2", "Détail des Usinage interne");
                }
                else
                {
                    Nomenclature.TitreColonnes("Barre ref.", "Materiau", "Profil", "Lg", "Nb");
                }

                int MdlPct = 0;
                foreach (var mdl in dic.Keys)
                {
                    mdl.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc);

                    WindowLog.SautDeLigne();
                    WindowLog.EcrireF("[{1}/{2}] {0}", mdl.eNomSansExt(), ++MdlPct, dic.Count);

                    int CfgPct = 0;
                    foreach (var NomConfigPliee in dic[mdl].Keys)
                    {
                        WindowLog.SautDeLigne();
                        WindowLog.EcrireF("  [{1}/{2}] Config : \"{0}\"", NomConfigPliee, ++CfgPct, dic[mdl].Count);
                        mdl.ShowConfiguration2(NomConfigPliee);
                        mdl.EditRebuild3();
                        PartDoc Piece = mdl.ePartDoc();

                        var ListeDossier = dic[mdl][NomConfigPliee];
                        int DrPct        = 0;
                        foreach (var t in ListeDossier)
                        {
                            var IdDossier     = t.Key;
                            var QuantiteBarre = t.Value * Quantite;

                            Feature    fDossier = Piece.FeatureById(IdDossier);
                            BodyFolder dossier  = fDossier.GetSpecificFeature2();

                            var RefDossier = dossier.eProp(CONSTANTES.REF_DOSSIER);

                            Body2 Barre = dossier.ePremierCorps();

                            String Profil   = dossier.eProp(CONSTANTES.PROFIL_NOM);
                            String Longueur = dossier.eProp(CONSTANTES.PROFIL_LONGUEUR);

                            String Materiau = Barre.eGetMateriauCorpsOuPiece(Piece, NomConfigPliee);

                            Materiau = ForcerMateriau.IsRefAndNotEmpty(Materiau);

                            String NomFichierBarre = ConstruireNomFichierBarre(RefDossier, QuantiteBarre);

                            WindowLog.SautDeLigne();
                            WindowLog.EcrireF("    - [{1}/{2}] Dossier : \"{0}\" x{3}", RefDossier, ++DrPct, ListeDossier.Count, QuantiteBarre);
                            WindowLog.EcrireF("              Profil {0}  Materiau {1}", Profil, Materiau);

                            List <String> Liste = new List <String>()
                            {
                                RefDossier, Materiau, Profil, Math.Round(Longueur.eToDouble()).ToString(), "× " + QuantiteBarre.ToString()
                            };

                            if (ListerUsinages)
                            {
                                var analyse = new AnalyseBarre(Barre, mdl);

                                Dictionary <String, Double> Dic = new Dictionary <string, double>();

                                foreach (var u in analyse.ListeFaceUsinageSection)
                                {
                                    String nom = u.ListeFaceDecoupe.Count + " face - Lg " + Math.Round(u.LgUsinage * 1000, 1);
                                    if (Dic.ContainsKey(nom))
                                    {
                                        Dic[nom] += 1;
                                    }
                                    else
                                    {
                                        Dic.Add(nom, 1);
                                    }
                                }

                                Liste.Add(Math.Round(analyse.ListeFaceUsinageExtremite[0].LgUsinage * 1000, 1).ToString());

                                if (analyse.ListeFaceUsinageExtremite.Count > 1)
                                {
                                    Liste.Add(Math.Round(analyse.ListeFaceUsinageExtremite[1].LgUsinage * 1000, 1).ToString());
                                }
                                else
                                {
                                    Liste.Add("");
                                }

                                foreach (var nom in Dic.Keys)
                                {
                                    Liste.Add(Dic[nom] + "x [ " + nom + " ]");
                                }
                            }

                            Nomenclature.AjouterLigne(Liste.ToArray());

                            if (ExporterBarres)
                            {
                                //mdl.ViewZoomtofit2();
                                //mdl.ShowNamedView2("*Isométrique", 7);
                                String    CheminFichier;
                                ModelDoc2 mdlBarre = Barre.eEnregistrerSous(Piece, DossierExport, NomFichierBarre, TypeExport, out CheminFichier);

                                if (CreerPdf3D)
                                {
                                    String CheminPDF = Path.Combine(DossierExportPDF, NomFichierBarre + eTypeFichierExport.PDF.GetEnumInfo <ExtFichier>());
                                    mdlBarre.SauverEnPdf3D(CheminPDF);
                                }

                                mdlBarre.eFermer();
                            }
                        }
                    }

                    mdl.eFermerSiDifferent(MdlBase);
                }

                WindowLog.SautDeLigne();
                WindowLog.Ecrire(Nomenclature.ListeLignes());

                CheminNomenclature = Path.Combine(DossierExport, "Nomenclature.txt");
                StreamWriter s = new StreamWriter(CheminNomenclature);
                s.Write(Nomenclature.GenererTableau());
                s.Close();
            }
            catch (Exception e) { this.LogErreur(new Object[] { e }); }
        }
示例#9
0
 protected override void UnsubscribePartEvents(PartDoc part)
 {
     part.DimensionChangeNotify -= OnDimensionChangeNotify;
 }
示例#10
0
 /// <summary>
 /// Hook up events in the part document context.
 /// </summary>
 /// <param name="md">A ModelDoc2 object.</param>
 private void ConnectPartEvents(ModelDoc2 md)
 {
     if (md.GetType() == (int)swDocumentTypes_e.swDocPART && !PartEventsAssigned) {
     pd = (PartDoc)md;
     // When the config changes, the app knows.
     pd.ActiveConfigChangePostNotify += pd_ActiveConfigChangePostNotify;
     pd.FileSavePostNotify += pd_FileSavePostNotify;
     //pd.ChangeCustomPropertyNotify += pd_ChangeCustomPropertyNotify;
     pd.DestroyNotify2 += pd_DestroyNotify2;
     //pd.RegenNotify += pd_RegenNotify;
     DisconnectDrawingEvents();
     PartEventsAssigned = true;
       }
 }
示例#11
0
        protected override void Command()
        {
            try
            {
                int NbDvp = 0;

                var dic = MdlBase.ListerComposants(false);

                int MdlPct = 0;
                foreach (var mdl in dic.Keys)
                {
                    WindowLog.SautDeLigne();
                    WindowLog.EcrireF("[{1}/{2}] {0}", mdl.eNomSansExt(), ++MdlPct, dic.Count);

                    mdl.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc);
                    var cfgActive = mdl.eNomConfigActive();

                    var ListeNomConfigs = dic[mdl];

                    if (ToutesLesConfigurations)
                    {
                        mdl.eParcourirConfiguration(
                            (String c) =>
                        {
                            if (c.eEstConfigPliee() && !ListeNomConfigs.ContainsKey(c))
                            {
                                ListeNomConfigs.Add(c, 1);
                            }

                            return(false);
                        }
                            );
                    }

                    if (MasquerEsquisses)
                    {
                        cmdMasquerEsquisses(mdl);
                    }

                    if (SupprimerLesAnciennesConfigs)
                    {
                        cmdSupprimerLesAnciennesConfigs(mdl);
                    }

                    if (!mdl.Extension.LinkedDisplayState)
                    {
                        mdl.Extension.LinkedDisplayState = true;

                        foreach (var c in mdl.eListeConfigs(eTypeConfig.Tous))
                        {
                            c.eRenommerEtatAffichage();
                        }
                    }

                    int CfgPct = 0;
                    foreach (var NomConfigPliee in ListeNomConfigs.Keys)
                    {
                        WindowLog.SautDeLigne();
                        WindowLog.EcrireF("  [{1}/{2}] Config : \"{0}\"", NomConfigPliee, ++CfgPct, ListeNomConfigs.Count);
                        mdl.ShowConfiguration2(NomConfigPliee);
                        mdl.EditRebuild3();

                        if (SupprimerFonctions)
                        {
                            cmdSupprimerFonctions(mdl, NomConfigPliee);
                        }

                        PartDoc Piece = mdl.ePartDoc();

                        var ListeDossier = Piece.eListePIDdesFonctionsDePiecesSoudees(
                            swD =>
                        {
                            BodyFolder dossier = swD.GetSpecificFeature2();
                            if (dossier.eEstExclu() || dossier.IsNull() || (dossier.GetBodyCount() == 0) || dossier.eTypeDeDossier() != eTypeCorps.Tole)
                            {
                                return(false);
                            }

                            return(true);
                        }
                            );

                        for (int noD = 0; noD < ListeDossier.Count; noD++)
                        {
                            var        f       = ListeDossier[noD];
                            BodyFolder dossier = f.GetSpecificFeature2();

                            var RefDossier = dossier.eProp(CONSTANTES.REF_DOSSIER);

                            Body2 Tole = dossier.eCorpsDeTolerie();

                            var pidTole = new SwObjectPID <Body2>(Tole, MdlBase);

                            String NomConfigDepliee = Sw.eNomConfigDepliee(NomConfigPliee, RefDossier);

                            WindowLog.EcrireF("    - [{1}/{2}] Dossier : \"{0}\" -> {3}", f.Name, noD + 1, ListeDossier.Count, NomConfigDepliee);

                            Configuration CfgDepliee = null;

                            if (ReconstuireLesConfigs)
                            {
                                CfgDepliee = MdlBase.GetConfigurationByName(NomConfigDepliee);
                            }

                            if (CfgDepliee.IsNull())
                            {
                                CfgDepliee = mdl.CreerConfigDepliee(NomConfigDepliee, NomConfigPliee);
                            }
                            else if (!ReconstuireLesConfigs)
                            {
                                continue;
                            }

                            if (CfgDepliee.IsNull())
                            {
                                WindowLog.Ecrire("       - Config non crée");
                                continue;
                            }

                            NbDvp++;

                            try
                            {
                                mdl.ShowConfiguration2(NomConfigDepliee);

                                // On ajoute le numero de la config parent aux propriétés de la configuration depliée
                                CfgDepliee.CustomPropertyManager.Add3(CONSTANTES.NO_CONFIG, (int)swCustomInfoType_e.swCustomInfoText, NomConfigPliee, (int)swCustomPropertyAddOption_e.swCustomPropertyDeleteAndAdd);

                                pidTole.Maj(ref Tole);

                                Tole.DeplierTole(mdl, NomConfigDepliee);
                            }
                            catch (Exception e)
                            {
                                DicErreur.Add(mdl.eNomSansExt() + " -> cfg : " + NomConfigPliee + " - No : " + RefDossier + " = " + NomConfigDepliee);
                                WindowLog.Ecrire("Erreur de depliage");
                                this.LogMethode(new Object[] { e });
                            }

                            try
                            {
                                mdl.ShowConfiguration2(NomConfigPliee);

                                pidTole.Maj(ref Tole);

                                Tole.PlierTole(mdl, NomConfigPliee);
                            }
                            catch (Exception e)
                            {
                                WindowLog.Ecrire("Erreur de repliage");
                                this.LogMethode(new Object[] { e });
                            }
                        }
                    }

                    mdl.ShowConfiguration2(cfgActive);
                    WindowLog.SautDeLigne();

                    mdl.eFermerSiDifferent(MdlBase);
                }

                if (DicErreur.Count > 0)
                {
                    WindowLog.SautDeLigne();

                    WindowLog.Ecrire("Liste des erreurs :");
                    foreach (var item in DicErreur)
                    {
                        WindowLog.Ecrire(" - " + item);
                    }

                    WindowLog.SautDeLigne();
                }
                else
                {
                    WindowLog.Ecrire("Pas d'erreur");
                }

                WindowLog.SautDeLigne();
                WindowLog.Ecrire("Resultat :");
                WindowLog.Ecrire("----------------");
                WindowLog.EcrireF("  {0} dvp crées", NbDvp);

                File.WriteAllText(Path.Combine(MdlBase.eDossier(), "Log_CreerConfigDvp.txt"), WindowLog.Resume);

                MdlBase.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc);
                MdlBase.ShowConfiguration2(nomConfigBase);
                MdlBase.EditRebuild3();
            }
            catch (Exception e)
            {
                this.LogErreur(new Object[] { e });
            }
        }
示例#12
0
            public ListeLgProfil Analyser()
            {
                InitTime();

                try
                {
                    listeElement = new ListeElement(LgBarre);

                    eTypeCorps       Filtre        = PrendreEnCompteTole ? eTypeCorps.Barre | eTypeCorps.Tole : eTypeCorps.Barre;
                    HashSet <String> HashMateriaux = new HashSet <string>(ListeMateriaux);

                    var dic = MdlBase.DenombrerDossiers(ComposantsExterne,
                                                        fDossier =>
                    {
                        BodyFolder swDossier = fDossier.GetSpecificFeature2();

                        if (Filtre.HasFlag(swDossier.eTypeDeDossier()) && HashMateriaux.Contains(swDossier.eGetMateriau()))
                        {
                            return(true);
                        }

                        return(false);
                    }
                                                        );

                    foreach (var mdl in dic.Keys)
                    {
                        mdl.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc);

                        foreach (var NomConfigPliee in dic[mdl].Keys)
                        {
                            mdl.ShowConfiguration2(NomConfigPliee);
                            mdl.EditRebuild3();
                            PartDoc Piece = mdl.ePartDoc();

                            var ListeDossier = dic[mdl][NomConfigPliee];
                            foreach (var t in ListeDossier)
                            {
                                var IdDossier     = t.Key;
                                var QuantiteBarre = t.Value * Quantite;

                                Feature    fDossier   = Piece.FeatureById(IdDossier);
                                BodyFolder dossier    = fDossier.GetSpecificFeature2();
                                var        RefDossier = dossier.eProp(CONSTANTES.REF_DOSSIER);

                                String Profil   = dossier.eProp(CONSTANTES.PROFIL_NOM);
                                Double Longueur = dossier.eProp(CONSTANTES.PROFIL_LONGUEUR).eToDouble();
                                Double A        = dossier.eProp(CONSTANTES.PROFIL_ANGLE1).eToDouble();
                                Double B        = dossier.eProp(CONSTANTES.PROFIL_ANGLE2).eToDouble();

                                if (String.IsNullOrWhiteSpace(Profil) || (Longueur == 0))
                                {
                                    continue;
                                }

                                if (String.IsNullOrWhiteSpace(RefDossier))
                                {
                                    WindowLog.EcrireF("{0}-{1}-{2} : Pas de reférence profil", mdl.eNomSansExt(), NomConfigPliee, fDossier.Name);
                                    continue;
                                }

                                var Materiau = dossier.ePremierCorps().eGetMateriauCorpsOuPiece(Piece, NomConfigPliee);

                                if (!HashMateriaux.Contains(Materiau))
                                {
                                    continue;
                                }

                                Materiau = ForcerMateriau.IsRefAndNotEmpty(Materiau);

                                listeElement.AjouterElement(QuantiteBarre, RefDossier, Materiau, Profil, Longueur, A, B);
                            }
                        }
                    }

                    ExecuterEn();
                    return(listeElement.ListeLgProfil);
                }
                catch (Exception e)
                {
                    this.LogErreur(new Object[] { e });
                }

                return(null);
            }
示例#13
0
        /// <summary>
        /// 当结果返回True 时 表示两个零件不一样,结果false时表示 两个零件一样
        /// </summary>
        /// <param name="sendTocustomer"></param>
        /// <param name="localModel"></param>
        /// <returns></returns>
        public bool CheckTwoParts(string sendTocustomer, string localModel)
        {
            bool different1 = false;

            bool different2 = false;

            swApp = ConnectToSolidWorks();
            // swApp = ConnectToSolidWorks();

            //加载参考关系零件
            swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swLoadExternalReferences, (int)swLoadExternalReferences_e.swLoadExternalReferences_ChangedOnly);

            //后台模式 前台不显示界面

            swApp.EnableBackgroundProcessing = true;

            //禁止记录文件路径
            swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swLockRecentDocumentsList, true);

            swApp.OpenDoc(localModel, 1);

            swApp.OpenDoc(sendTocustomer, 1);

            ModelDoc2 swModel = (ModelDoc2)swApp.ActiveDoc;

            string LocalPath = System.IO.Directory.GetParent(swModel.GetPathName()).ToString();

            string tempAssembly = swApp.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplateAssembly);

            AssemblyDoc assemblyDoc = (AssemblyDoc)swApp.NewDocument(tempAssembly, 0, 0, 0);

            Component2 insertComponentSendtoCustomer = assemblyDoc.AddComponent5(sendTocustomer, 0, "", false, "", 0, 0, 0);
            Component2 insertComponentLocal          = assemblyDoc.AddComponent5(localModel, 0, "", false, "", 0, 0, 0);

            string sendSelect  = insertComponentSendtoCustomer.GetSelectByIDString();
            string localSelect = insertComponentLocal.GetSelectByIDString();

            swModel = (ModelDoc2)swApp.ActiveDoc;

            bool b1 = swModel.Extension.SelectByID2("Point1@Origin" + "@" + sendSelect, "EXTSKETCHPOINT", 0, 0, 0, false, 0, null, 0);
            bool b2 = swModel.Extension.SelectByID2("Point1@Origin" + "@" + localSelect, "EXTSKETCHPOINT", 0, 0, 0, true, 0, null, 0);
            int  longstatus;

            Mate2 mate2 = assemblyDoc.AddMate5(20, -1, false, 0, 0.001, 0.001, 0.001, 0.001, 0, 0, 0, false, false, 0, out longstatus);

            swModel = (ModelDoc2)swApp.ActiveDoc;

            swModel.SaveAs(LocalPath + @"\TopCheck.sldasm");

            //不显示特征树
            //swModel.Extension.HideFeatureManager(true);

            swModel.ClearSelection2(true);
            //swModel.FeatureManager.ViewFeatures = false;

            //FeatureManager featureManager = swModel.FeatureManager;

            //禁用特征树
            //featureManager.EnableFeatureTree = false;

            // swModel.FeatureManager.EnableFeatureTreeWindow = false;

            #region first join

            Component2        sendToCustomerBodies     = default(Component2);
            List <Component2> sendToCustomerBodiesList = new List <Component2>();

            object swFaceOrPlane = default(object);

            assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out sendToCustomerBodies);

            sendToCustomerBodies.Select(true);

            assemblyDoc.FixComponent();
            sendToCustomerBodies.Select(true);
            assemblyDoc.EditPart();

            insertComponentSendtoCustomer.Select(false);
            insertComponentLocal.Select(true);

            assemblyDoc.InsertJoin2(false, false);

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.BreakAllExternalReferences();

            object[] splits = sendToCustomerBodies.Name2.Split('^');
            // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0];
            string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + "localBodies-1";

            ModelDoc2 compModel = default(ModelDoc2);
            compModel = (ModelDoc2)sendToCustomerBodies.GetModelDoc();

            if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART)
            {
                compName = compName + ".sldprt";
            }
            else
            {
                compName = compName + ".sldasm";
            }

            bool ret;

            ret = sendToCustomerBodies.SaveVirtualComponent(compName);

            sendToCustomerBodiesList.Add(sendToCustomerBodies);

            insertComponentSendtoCustomer.Select(false);

            swModel = (ModelDoc2)sendToCustomerBodies.GetModelDoc2();

            #region 获取所有零件中的零件,每一个实体做一次反切

            List <string> bodyNamesCustomer = new List <string>();

            PartDoc swPart = null;
            object  vBody;
            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 + " " + "");

                    bodyNamesCustomer.Add(swBody.Name);
                }
            }

            //如果实体数量大于1,则继续新建对应数量的join 实体。

            OnlyKeepNamedBody(bodyNamesCustomer[0], sendToCustomerBodies.GetSelectByIDString(), assemblyDoc, sendToCustomerBodies, insertComponentSendtoCustomer, ref different1);

            if (bodyNamesCustomer.Count > 1)
            {
                assemblyDoc.EditAssembly();

                for (int i = 0; i < bodyNamesCustomer.Count - 1; i++)
                {
                    Component2 returnpart = default(Component2);
                    var        partSelect = CreateNewJoinPart(assemblyDoc, insertComponentSendtoCustomer, insertComponentLocal, swModel, "localBodies-" + (i + 2), out returnpart);
                    sendToCustomerBodiesList.Add(returnpart);

                    OnlyKeepNamedBody(bodyNamesCustomer[i + 1], partSelect, assemblyDoc, returnpart, insertComponentSendtoCustomer, ref different1);
                }
            }
            // boolstatus = Part.Extension.SelectByID2("Join1[2]@localBodies-1@TopCheck", "SOLIDBODY", 0, 0, 0, True, 0, Nothing, 0)
            //Dim myFeature As Object
            //Set myFeature = Part.FeatureManager.InsertDeleteBody2(True)

            #endregion 获取所有零件中的零件,每一个实体做一次反切

            //assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1);
            Feature theFeature;

            //theFeature = swModel.FeatureByPositionReverse(0);

            //if (theFeature.Name.Contains("Cavity"))
            //{
            //    //theFeature.Select(true);

            //    swModel = (ModelDoc2)swApp.ActiveDoc;

            //    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

            //    swModel.BreakAllExternalReferences();
            //    different1 = true;
            //    //JoinPart1 留下的: 发给客户的没有此部分。 而本地零件中有
            //}
            //else
            //{
            //    //无法Join时表示 全切了。
            //    swModel = (ModelDoc2)swApp.ActiveDoc;

            //    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

            //    swModel.EditSuppress();
            //}
            //sendToCustomerBodies.Select(true);

            assemblyDoc.EditAssembly();

            #endregion first join

            #region sercond join2

            Component2        localBodies     = default(Component2);
            List <Component2> LocalBodiesList = new List <Component2>();
            assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out localBodies);

            localBodies.Select(true);

            assemblyDoc.FixComponent();
            localBodies.Select(true);
            assemblyDoc.EditPart();

            insertComponentSendtoCustomer.Select(false);
            insertComponentLocal.Select(true);

            assemblyDoc.InsertJoin2(false, false);

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.BreakAllExternalReferences();

            splits = localBodies.Name2.Split('^');
            // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0];
            compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + "sendToCustomerBodies-1";

            compModel = default(ModelDoc2);
            compModel = (ModelDoc2)localBodies.GetModelDoc();

            if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART)
            {
                compName = compName + ".sldprt";
            }
            else
            {
                compName = compName + ".sldasm";
            }

            ret = localBodies.SaveVirtualComponent(compName);
            LocalBodiesList.Add(localBodies);
            insertComponentLocal.Select(false);

            swModel = (ModelDoc2)localBodies.GetModelDoc2();

            #region 获取所有零件中的零件,每一个实体做一次反切

            List <string> bodyNamesLocal = new List <string>();

            PartDoc swPart2 = null;
            object  vBody2;
            swPart2 = (PartDoc)swModel;
            // Solid bodies
            object[] vBodyArr2 = null;
            Body2    swBody2   = default(Body2);

            MathTransform swMathTrans2 = null;
            vBodyArr2 = (object[])swPart2.GetBodies2((int)swBodyType_e.swSolidBody, true);

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

                foreach (object vBody_loopVariable in vBodyArr2)
                {
                    vBody2  = vBody_loopVariable;
                    swBody2 = (Body2)vBody2;

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

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

                    bodyNamesLocal.Add(swBody2.Name);
                }
            }

            //如果实体数量大于1,则继续新建对应数量的join 实体。

            OnlyKeepNamedBody(bodyNamesLocal[0], localBodies.GetSelectByIDString(), assemblyDoc, localBodies, insertComponentLocal, ref different2);

            if (bodyNamesLocal.Count > 1)
            {
                assemblyDoc.EditAssembly();

                for (int i = 0; i < bodyNamesLocal.Count - 1; i++)
                {
                    Component2 returnpart = default(Component2);
                    var        partSelect = CreateNewJoinPart(assemblyDoc, insertComponentSendtoCustomer, insertComponentLocal, swModel, "sendToCustomerBodies-" + (i + 2), out returnpart);
                    LocalBodiesList.Add(returnpart);
                    OnlyKeepNamedBody(bodyNamesLocal[i + 1], partSelect, assemblyDoc, returnpart, insertComponentLocal, ref different2);
                }
            }
            // boolstatus = Part.Extension.SelectByID2("Join1[2]@localBodies-1@TopCheck", "SOLIDBODY", 0, 0, 0, True, 0, Nothing, 0)
            //Dim myFeature As Object
            //Set myFeature = Part.FeatureManager.InsertDeleteBody2(True)

            #endregion 获取所有零件中的零件,每一个实体做一次反切

            //assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1);

            //theFeature = swModel.FeatureByPositionReverse(0);

            //swModel = (ModelDoc2)localBodies.GetModelDoc2();

            //theFeature = swModel.FeatureByPositionReverse(0);

            //if (theFeature.Name.Contains("Cavity"))
            //{
            //    //theFeature.Select(true);

            //    swModel = (ModelDoc2)swApp.ActiveDoc;

            //    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + localBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

            //    swModel.BreakAllExternalReferences();
            //    different2 = true;
            //    //JoinPart2 留下的: 发给客户的有此部分。 而本地零件中没有
            //}
            //else
            //{
            //    //无法Join时表示 全切了。
            //    swModel = (ModelDoc2)swApp.ActiveDoc;

            //    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

            //    swModel.EditSuppress();
            //}

            //localBodies.Select(true);

            //assemblyDoc.EditAssembly();

            #endregion sercond join2

            #region joinPartPublic

            Component2 publicBodies = default(Component2);

            assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out publicBodies);

            publicBodies.Select(true);

            assemblyDoc.FixComponent();
            publicBodies.Select(true);
            assemblyDoc.EditPart();

            insertComponentSendtoCustomer.Select(false);
            insertComponentLocal.Select(true);

            assemblyDoc.InsertJoin2(false, false);

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.BreakAllExternalReferences();

            splits = publicBodies.Name2.Split('^');
            // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0];
            compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + "publicBodies";

            compModel = default(ModelDoc2);
            compModel = (ModelDoc2)publicBodies.GetModelDoc();

            if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART)
            {
                compName = compName + ".sldprt";
            }
            else
            {
                compName = compName + ".sldasm";
            }

            ret = publicBodies.SaveVirtualComponent(compName);

            swModel.ClearSelection();

            foreach (var item in sendToCustomerBodiesList)
            {
                item.Select(false);

                assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1);

                theFeature = (Feature)swModel.FeatureByPositionReverse(0);

                swModel    = (ModelDoc2)publicBodies.GetModelDoc2();
                theFeature = (Feature)swModel.FeatureByPositionReverse(0);

                if (theFeature.Name.Contains("Cavity"))
                {
                    //theFeature.Select(true);

                    swModel = (ModelDoc2)swApp.ActiveDoc;

                    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + publicBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

                    swModel.BreakAllExternalReferences();

                    //joinPartPublic 留下的: 发给客户的有此部分。 而本地零件中没有
                }
                else
                {
                }
            }
            foreach (var item in LocalBodiesList)
            {
                item.Select(false);

                assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1);

                theFeature = (Feature)swModel.FeatureByPositionReverse(0);

                swModel    = (ModelDoc2)publicBodies.GetModelDoc2();
                theFeature = (Feature)swModel.FeatureByPositionReverse(0);

                if (theFeature.Name.Contains("Cavity"))
                {
                    //theFeature.Select(true);

                    swModel = (ModelDoc2)swApp.ActiveDoc;

                    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + publicBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

                    swModel.BreakAllExternalReferences();

                    //joinPartPublic 留下的: 发给客户的有此部分。 而本地零件中没有
                }
                else
                {
                }
            }

            publicBodies.Select(true);

            assemblyDoc.EditAssembly();

            #endregion joinPartPublic

            foreach (var item in sendToCustomerBodiesList)
            {
                item.Select(false);
                setColour(Color.Red);
            }
            foreach (var item in LocalBodiesList)
            {
                item.Select(false);
                setColour(Color.Blue);
            }

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.ClearSelection2(true);

            insertComponentLocal.Select(false);
            insertComponentSendtoCustomer.Select(true);
            swModel.HideComponent2();
            swModel.ClearSelection2(true);

            publicBodies.Select(false);
            assemblyDoc.SetComponentTransparent(true);
            setColour(Color.Green);
            swModel.EditRebuild3();
            swModel.Save();

            swModel.SaveAs3(LocalPath + @"\01_CheckResult.sldprt", 0, 0);

            swApp.CloseDoc("TopCheck.sldasm");
            swApp.CloseAllDocuments(true);
            swApp.OpenDoc(LocalPath + @"\01_CheckResult.sldprt", 1);
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.ShowNamedView2("*Isometric", 7);

            swModel.ViewZoomtofit2();

            swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swLockRecentDocumentsList, false);
            try
            {
                System.IO.File.Delete(LocalPath + @"\TopCheck.sldasm");
                System.IO.File.Delete(LocalPath + @"\localBodies.sldprt");
                System.IO.File.Delete(LocalPath + @"\sendToCustomerBodies.sldprt");
                System.IO.File.Delete(LocalPath + @"\publicBodies.sldprt");
            }
            catch (Exception)
            {
            }

            //第二次反向剪切

            swApp.CloseDoc(sendTocustomer);
            swApp.CloseDoc(localModel);

            swModel.FeatureManager.EnableFeatureTree = true;

            swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swLoadExternalReferences, 2);

            if (different1 == false && different2 == false)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
        /// <summary>
        /// Méthode interne.
        /// Initialiser l'objet pièce.
        /// </summary>
        /// <param name="Modele"></param>
        /// <returns></returns>
        internal Boolean Init(eModele Modele)
        {
            Log.Methode(cNOMCLASSE);

            if ((Modele != null) && Modele.EstInitialise && (Modele.TypeDuModele == TypeFichier_e.cPiece))
            {
                Log.Message(Modele.FichierSw.Chemin);

                _Modele = Modele;
                _SwPiece = Modele.SwModele as PartDoc;
                _EstInitialise = true;
            }
            else
            {
                Log.Message("!!!!! Erreur d'initialisation");
            }

            return _EstInitialise;
        }
 protected override void UnsubscribePartEvents(PartDoc part)
 {
     part.FileSaveAsNotify2 -= OnFileSaveAsNotify2;
     part.FileSaveNotify    -= OnFileSaveNotify;
 }
 protected override void UnsubscribePartEvents(PartDoc part)
 {
     part.LoadFromStorageNotify -= OnLoadFromStreamNotify;
 }
示例#17
0
 public PartEventHandler(ModelDoc2 modDoc, SwAddin addin)
     : base(modDoc, addin)
 {
     doc = (PartDoc)document;
 }
示例#18
0
 protected override void UnsubscribePartEvents(PartDoc part)
 {
     part.ClearSelectionsNotify -= OnClearSelections;
 }
示例#19
0
        private GeomVue AppliquerOptionsVue(DrawingDoc dessin, PartDoc piece, View vue)
        {
            vue.ShowSheetMetalBendNotes = AfficherNotePliage;

            MathUtility SwMath = App.Sw.GetMathUtility();

            var liste = piece.eListeFonctionsDepliee();

            if (liste.Count == 0)
            {
                return(null);
            }

            Feature FonctionDepliee = liste[0];

            GeomVue g     = null;
            var     Liste = FonctionDepliee.eListeSousFonction();

            Feature f = Liste[0];

            // Les fonctions "Lignes de pliage" et "Cube de visualisation" ne sont pas toujours correctement
            // nommées donc ont considère que la première fonction = Ligne de pliage et la deuxième = Cube de visualisation

            if (f.GetTypeName2() == FeatureType.swTnProfileFeature)
            {
                ModelDoc2 mdlBase = dessin.eModelDoc2();

                f.eSelectionnerById2Dessin(mdlBase, vue);

                if (AfficherLignePliage)
                {
                    mdlBase.UnblankSketch();
                }
                else
                {
                    mdlBase.BlankSketch();
                }

                mdlBase.eEffacerSelection();
            }

            f = Liste[1];

            if (f.GetTypeName2() == FeatureType.swTnProfileFeature)
            {
                try
                {
                    f.eModifierEtat(swFeatureSuppressionAction_e.swUnSuppressFeature);

                    Sketch Esquisse = f.GetSpecificFeature2();

                    if (OrienterDvp)
                    {
                        Double Angle = AngleCubeDeVisualisation(vue, Esquisse);

                        // On oriente la vue
                        switch (OrientationDvp)
                        {
                        case eOrientation.Portrait:
                            if (Math.Abs(Angle) != MathX.eRad90D)
                            {
                                Double a = MathX.eRad90D - Math.Abs(Angle);
                                vue.Angle = (Math.Sign(Angle) == 0 ? 1 : Math.Sign(Angle)) * a;
                            }
                            break;

                        case eOrientation.Paysage:
                            if (Math.Abs(Angle) != 0 || Math.Abs(Angle) != MathX.eRad180D)
                            {
                                Double a = MathX.eRad90D - Math.Abs(Angle);
                                vue.Angle = ((Math.Sign(Angle) == 0 ? 1 : Math.Sign(Angle)) * a) - MathX.eRad90D;
                            }
                            break;

                        default:
                            break;
                        }
                    }

                    g = new GeomVue(vue, Esquisse);
                }
                catch
                {
                    WindowLog.EcrireF("Impossible d'orienter la vue : {0}", vue.Name);
                }
            }



            //FonctionDepliee.eParcourirSousFonction(
            //    f =>
            //    {
            //        if (f.Name.StartsWith(CONSTANTES.LIGNES_DE_PLIAGE))
            //        {
            //            //String NomSelection = f.Name + "@" + vue.RootDrawingComponent.Name + "@" + vue.Name;
            //            //Dessin.Extension.SelectByID2(NomSelection, "SKETCH", 0, 0, 0, false, 0, null, 0);

            //            ModelDoc2 mdlBase = dessin.eModelDoc2();

            //            f.eSelectionnerById2Dessin(mdlBase, vue);

            //            if (AfficherLignePliage)
            //                mdlBase.UnblankSketch();
            //            else
            //                mdlBase.BlankSketch();

            //            mdlBase.eEffacerSelection();
            //        }
            //        else if (f.Name.StartsWith(CONSTANTES.CUBE_DE_VISUALISATION))
            //        {
            //            try
            //            {
            //                f.eModifierEtat(swFeatureSuppressionAction_e.swUnSuppressFeature);

            //                Sketch Esquisse = f.GetSpecificFeature2();

            //                if (OrienterDvp)
            //                {
            //                    Double Angle = AngleCubeDeVisualisation(vue, Esquisse);

            //                    // On oriente la vue
            //                    switch (OrientationDvp)
            //                    {
            //                        case eOrientation.Portrait:
            //                            if (Math.Abs(Angle) != MathX.eRad90D)
            //                            {
            //                                Double a = MathX.eRad90D - Math.Abs(Angle);
            //                                vue.Angle = (Math.Sign(Angle) == 0 ? 1 : Math.Sign(Angle)) * a;
            //                            }
            //                            break;
            //                        case eOrientation.Paysage:
            //                            if (Math.Abs(Angle) != 0 || Math.Abs(Angle) != MathX.eRad180D)
            //                            {
            //                                Double a = MathX.eRad90D - Math.Abs(Angle);
            //                                vue.Angle = ((Math.Sign(Angle) == 0 ? 1 : Math.Sign(Angle)) * a) - MathX.eRad90D;
            //                            }
            //                            break;
            //                        default:
            //                            break;
            //                    }
            //                }

            //                g = new GeomVue(vue, Esquisse);
            //            }
            //            catch
            //            {
            //                WindowLog.EcrireF("Impossible d'orienter la vue : {0}", vue.Name);
            //            }
            //            return true;
            //        }
            //        return false;
            //    }
            //    );

            return(g);
        }
示例#20
0
 public PartEventHandler(ModelDoc2 modDoc, SwAddin addin, ConnectAPI connect)
     : base(modDoc, addin, connect)
 {
     doc = (PartDoc)document;
 }
示例#21
0
 protected override void UnsubscribePartEvents(PartDoc part)
 {
     part.ConfigurationChangeNotify -= OnConfigurationChangeNotify;
 }
        public void Main()
        {
            ModelDoc2   swDoc;
            PartDoc     swPart     = null;
            DrawingDoc  swDrawing  = null;
            AssemblyDoc swAssembly = null;

            bool boolstatus = false;

            int longstatus   = 0;
            int longwarnings = 0;

            string FileLocation   = "E:\\My Douments\\MQP\\SOLIDWORKS\\Gear Creation script\\"; //directory for all parts created and modified in this code (Templates should be here)
            string Gear_Template  = "Spur gear - Metric Template.sldprt";                       //filename of the spur gear template
            string Housing        = "GEAR_HOUSING_MACRO.sldprt";                                //filename for gearbox housing
            string ASSEMBLY       = "GEARBOX_ASSEMBLY_MACRO.sldasm";                            //filename for Assembly file
            string SHAFT_TEMPLATE = "SHAFT_TEMPLATE.sldprt";
            int    i;                                                                           //number of gears to create (replace with input data later)


            //***************************CREATE GEARS***********************************

            int num_gears = 5;                              //number of gears in assembly to generate

            double[][] Gear_info = new double[num_gears][]; //array of arrays(jagged) to store data about each gear

            //raw gear data           {#teeth, width,shaft,locked to shaft, other gear to mesh with(255 indicates no output),distance from }
            //    0  1  2  3  4    5
            Gear_info[0] = new double[] { 10, 4, 0, 1, 1, 0.000 };   // #teeth, width mm, which shaft to connect to, if locked on shaft, distance between shafts
            Gear_info[1] = new double[] { 40, 4, 1, 0, 2, 0.000 };
            Gear_info[2] = new double[] { 20, 4, 2, 1, 255, 0.000 };
            Gear_info[3] = new double[] { 40, 4, 2, 1, 4, 0.004 };
            Gear_info[4] = new double[] { 20, 4, 1, 1, 255, 0.004 };

            //shaft info
            double Shaft_Diameter = 1;                   //diameter in mm (also used for bore dia. in gears)
            int    num_shafts     = 3;
            double Shaft_length   = 2 * Gear_info[0][1]; //length of shaft, make slightly larger than width of gear for now
            double Modulus        = .25;                 //gear modulus for all gears


            double[] shaft_spacing = new double[] { 4, 5, 8 }; //temporarily use this for the shaft spacing



            for (i = 0; i < num_gears; i++) //create each gear based off the template
            {
                swDoc = ((ModelDoc2)(swApp.OpenDoc6(FileLocation + Gear_Template, 1, 0, "", ref longstatus, ref longwarnings)));
                double NUM_TEETH  = Gear_info[i][0];
                Double WIDTH      = Gear_info[i][1];//      gear depth in mm
                double SHOW_TEETH = NUM_TEETH;
                //change sketch dimmensions in the reference sketch: "HoldingSke"
                ((Dimension)(swDoc.Parameter("Show_teeth@HoldingSke"))).SystemValue = SHOW_TEETH * (3.14159 / 180); //have to convert degrees to radians, num_teeth is saved as angle measurment in the sketch
                ((Dimension)(swDoc.Parameter("Num_teeth@HoldingSke"))).SystemValue  = NUM_TEETH * (3.14159 / 180);  //display all the teeth
                ((Dimension)(swDoc.Parameter("Width@HoldingSke"))).SystemValue      = WIDTH / 1000;
                ((Dimension)(swDoc.Parameter("Bore@HoldingSke"))).SystemValue       = Shaft_Diameter / 1000;
                ((Dimension)(swDoc.Parameter("Module@HoldingSke"))).SystemValue     = Modulus / 1000;
                boolstatus = swDoc.EditRebuild3();                                             //rebuild the document

                longstatus = swDoc.SaveAs3(FileLocation + "GEAR_MACRO" + i + ".sldprt", 0, 2); //save gear as gear number i in a new folder called MACRO_PARTS
            }

            //***************************CREATE SHAFTS***********************************


            for (i = 0; i < num_shafts; i++)
            {
                swDoc = ((ModelDoc2)(swApp.OpenDoc6(FileLocation + SHAFT_TEMPLATE, 1, 0, "", ref longstatus, ref longwarnings)));

                //change sketch dimmensions
                ((Dimension)(swDoc.Parameter("Diameter@Sketch1"))).SystemValue     = Shaft_Diameter / 1000;
                ((Dimension)(swDoc.Parameter("Shaft Length@Sketch1"))).SystemValue = Shaft_length / 1000;
                boolstatus = swDoc.EditRebuild3();                                              //rebuild the document

                longstatus = swDoc.SaveAs3(FileLocation + "SHAFT_MACRO" + i + ".sldprt", 0, 2); //save gear as gear number i in a new folder called MACRO_PARTS
                //code to create shafts of set diameters or something
            }



            //***************************CREATE ASSEMBLY***********************************
            //Open All components to be added

            for (i = 0; i < num_gears; i++)
            {
                swDoc = ((ModelDoc2)(swApp.OpenDoc6(FileLocation + "GEAR_MACRO" + i + ".sldprt", 1, 0, "", ref longstatus, ref longwarnings)));
                swDoc = ((ModelDoc2)(swApp.OpenDoc6(FileLocation + "SHAFT_MACRO" + i + ".sldprt", 1, 0, "", ref longstatus, ref longwarnings)));
            }


            //Open the assembly
            swDoc = ((ModelDoc2)(swApp.OpenDoc6(FileLocation + "Assembly_Template.SLDASM", 2, 0, "", ref longstatus, ref longwarnings)));
            swDoc = ((ModelDoc2)(swApp.ActiveDoc));
            swApp.ActivateDoc2("Assembly_Template.SLDASM", false, ref longstatus);
            swAssembly = ((AssemblyDoc)(swDoc));

            //add components to SW assembly
            //****** Currently Parts must already be opened seperately to add to assmebly *******



            //***************************SHAFT MATES***********************************
            //names of edges and faces in the template:  Front Edge ( circle along front)
            //                                           Surface (cylinder surface of rod)

            //make face coincident with corresponding hole on housing

            Mate2 myMate = null;

            //insert shaft
            //insert point for mate
            //align along axis
            //mate oring to point

            double[][] Shaft_coord = new double[num_shafts][]; //array of arrays(jagged) to store data about each gear

            double x; double y;  double z;

            //shaft coords                    x,    y, z
            Shaft_coord[0] = new double[] { .000, .000, .000 };
            Shaft_coord[1] = new double[] { .000, .000, .008 };
            Shaft_coord[2] = new double[] { .000, .000, .018 };
            //Shaft_coord[3] = new double[] {.019, .000, 0};



            for (i = 0; i < num_shafts; i++)
            {
                boolstatus = swAssembly.AddComponent(FileLocation + "SHAFT_Macro" + i + ".sldprt", 0, 0, 0);
                if (i == 0)
                {
                    swDoc.ClearSelection2(true);
                    boolstatus = swDoc.Extension.SelectByID2("SHAFT_MACRO" + i + "-1@Assembly_Template", "COMPONENT", 0, 0, 0, false, 0, null, 0);
                    swAssembly.UnfixComponent();
                }



                x = Shaft_coord[i][0];
                y = Shaft_coord[i][1];
                z = Shaft_coord[i][2];


                boolstatus = swDoc.Extension.SelectByID2("Shaft coords sketch", "SKETCH", 0, 0, 0, false, 0, null, 0);
                swDoc.EditSketch();
                swDoc.ClearSelection2(true);
                SketchPoint skPoint = null;
                skPoint = ((SketchPoint)(swDoc.SketchManager.CreatePoint(x, y, z))); //create a point



                //have to make point fixed!

                //make origin coincident to its sketch point
                boolstatus = swDoc.Extension.SelectByID2("Point" + (i + 11) + "@Shaft coords sketch", "EXTSKETCHPOINT", x, y, z, true, 1, null, 0);
                boolstatus = swDoc.Extension.SelectByID2("Point1@Origin@SHAFT_MACRO" + i + "-1@Assembly_Template", "EXTSKETCHPOINT", 0, 0, 0, true, 1, null, 0);
                myMate     = null;
                swAssembly = ((AssemblyDoc)(swDoc));
                myMate     = ((Mate2)(swAssembly.AddMate5(0, 0, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out longstatus)));
                swDoc.ClearSelection2(true);
                swDoc.EditRebuild3();

                //parallel to axis
                boolstatus = swDoc.Extension.SelectByID2("Center Axis@SHAFT_MACRO" + i + "-1@Assembly_Template", "AXIS", 0, 0, 0, false, 0, null, 0);
                boolstatus = swDoc.Extension.SelectByID2("Line1@Reference Direction", "EXTSKETCHSEGMENT", 0, 0, 0.0021382559642120218, true, 1, null, 0);
                myMate     = null;
                swAssembly = ((AssemblyDoc)(swDoc));
                myMate     = ((Mate2)(swAssembly.AddMate5(3, 1, false, 0.0029999999999767309, 0.001, 0.001, 0.001, 0.001, 0, 0.5235987755983, 0.5235987755983, false, false, 0, out longstatus)));
                swDoc.ClearSelection2(true);
                swDoc.EditRebuild3();
            }



            //***************************GEAR MATES***********************************
            string face_sel; //holds string with name of the face to select

            for (i = 0; i < num_gears; i++)
            {
                Double DistanceMate = Gear_info[i][5]; //      gear loacation on shaft
                boolstatus = swAssembly.AddComponent(FileLocation + "GEAR_MACRO" + i + ".sldprt", -0.5, 0, 0);

                //Distance mate from edge of shaft

                boolstatus = swDoc.Extension.SelectByID2("EDGE@GEAR_MACRO" + i + "-1@Assembly_Template", "PLANE", 0, 0, 0, true, 0, null, 0);                 //face plane of gear
                boolstatus = swDoc.Extension.SelectByID2("Right@SHAFT_MACRO" + Gear_info[i][2] + "-1@Assembly_Template", "PLANE", 0, 0, 0, true, 0, null, 0); //shaft hole in housing

                myMate = (Mate2)swAssembly.AddMate5(5, 1, false, DistanceMate, DistanceMate, DistanceMate, 0, 0, 0, 0, 0, false, false, 0, out longstatus);

                swDoc.ClearSelection2(true);



                //concentric to shaft
                boolstatus = swDoc.Extension.SelectByID2("Central Axis@GEAR_MACRO" + i + "-1@Assembly_Template", "AXIS", 0, 0, 0, true, 0, null, 0);               //axis of gear
                boolstatus = swDoc.Extension.SelectByID2("Center Axis@SHAFT_MACRO" + Gear_info[i][2] + "-1@Assembly_Template", "AXIS", 0, 0, 0, true, 0, null, 0); //axis of shaft
                myMate     = (Mate2)swAssembly.AddMate4((int)swMateType_e.swMateCOINCIDENT, (int)swMateAlign_e.swMateAlignALIGNED, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, out longstatus);
                swDoc.ClearSelection2(true);


                //lock to shaft
                if (Gear_info[i][3] == 1)                                                                                                                         //if gear locked to shaft (make two planes coincident)
                {
                    boolstatus = swDoc.Extension.SelectByID2("Plane2@GEAR_MACRO" + i + "-1@Assembly_Template", "PLANE", 0, 0, 0, true, 0, null, 0);               //face plane of shaft
                    boolstatus = swDoc.Extension.SelectByID2("Front@SHAFT_MACRO" + Gear_info[i][2] + "-1@Assembly_Template", "PLANE", 0, 0, 0, true, 0, null, 0); //shaft hole in housing
                    myMate     = (Mate2)swAssembly.AddMate4((int)swMateType_e.swMateCOINCIDENT, (int)swMateAlign_e.swMateAlignALIGNED, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, out longstatus);
                    swDoc.ClearSelection2(true);
                    swDoc.EditRebuild3();
                }
            }

            //gear mate
            for (i = 0; i < (num_gears); i++)
            {
                if (Gear_info[i][4] != 255)                                                                                                                                                                                    //if -1 that means do not make a gear mate (don't make gear mate for last gear sinc it is output, no gear to mesh to!!!!)
                {
                    boolstatus = swDoc.Extension.SelectByID2("Central Axis@GEAR_MACRO" + i + "-1@Assembly_Template", "AXIS", 0, 0, 0, true, 0, null, 0);                                                                       //axis of gear
                    boolstatus = swDoc.Extension.SelectByID2("Central Axis@GEAR_MACRO" + Gear_info[i][4] + "-1@Assembly_Template", "AXIS", 0, 0, 0, true, 0, null, 0);                                                         //axis of gear
                    myMate     = (Mate2)swAssembly.AddMate4((int)swMateType_e.swMateGEAR, (int)swMateAlign_e.swMateAlignALIGNED, false, 0, 0, 0, Gear_info[i][0], Gear_info[i + 1][0], 0, 0, 0, false, false, out longstatus); //gear mate, specify num. and denom. of gear ratio as #teeth on gear
                    swDoc.ClearSelection2(true);
                    swDoc.EditRebuild3();
                }
            }



            /*
             *
             *
             *     //     boolstatus = swDoc.Extension.SelectByID2("", "FACE", -0.00455748224163699, 0.0037205844126901866, 0.004682722786242266, false, 0, null, 0);
             *   //       boolstatus = swDoc.Extension.SelectByID2("", "FACE", 0.0018884588073433406, 0.00336302382845588, -0.00060759657679909651, true, 0, null, 1);
             *   //       swDoc.ClearSelection2(true);
             *
             *          boolstatus = swDoc.Extension.SelectByID2("Plane3@30 tooth gear-1@Assem4", "PLANE", 0, 0, 0, true, 0, null, 0);
             *          boolstatus = swDoc.Extension.SelectByID2("Plane3@50 tooth gear-1@Assem4", "PLANE", 0, 0, 0, true, 0, null, 0);
             *          //Mate2 myMate = null;
             *  //        swAssembly = ((AssemblyDoc)(swDoc));
             *
             *          //add mate to two parts (by selection)
             *      //    myMate = (Mate2)swAssembly.AddMate4((int)swMateType_e.swMateCOINCIDENT, (int)swMateAlign_e.swMateAlignALIGNED, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, out longstatus);
             *    //      swDoc.ClearSelection2(true);
             *
             *
             *          boolstatus = swDoc.Extension.SelectByID2("Bore of@50 tooth gear-1@Assem4", "PLANE", 0, 0, 0, true, 0, null, 0);
             *
             *
             *          swDoc.EditRebuild3();
             */
        }
        public override void CreatePart()
        {
            swApp = SolidWorksSingleton.GetApplication();
            DocumentManager.CreateNewPartDoc();

            swModel = (ModelDoc2)swApp.ActiveDoc;

            swFeature      = swModel.FeatureByPositionReverse(3);
            swFeature.Name = "Front";

            swModel.Extension.SelectByID2("Front", "PLANE", 0, 0, 0, false, 0, null, 0);

            swModel.InsertSketch2(true);

            swModel.CreateLine2(0, 0, 0, XLenght, 0, 0);
            //swModel.AddDimension2(0,0,0);

            swModel.CreateLine2(0, 0, 0, 0, YLenght, 0);
            //swModel.AddDimension2(0, 0, 0);

            //int markHorizontal = 2;
            //int markVertical = 4;

            //swModel.Extension.SelectByID2("Point1@Origin", "EXTSKETCHSEGMENT",0,0,0,false, markHorizontal|markVertical,null,0);

            object datumDisp = "Point1@Origin";

            swModel.SketchManager.FullyDefineSketch(true, true, (int)swSketchFullyDefineRelationType_e.swSketchFullyDefineRelationType_Vertical | (int)swSketchFullyDefineRelationType_e.swSketchFullyDefineRelationType_Horizontal, true, (int)swAutodimScheme_e.swAutodimSchemeBaseline, datumDisp, (int)swAutodimScheme_e.swAutodimSchemeBaseline, datumDisp, (int)swAutodimHorizontalPlacement_e.swAutodimHorizontalPlacementBelow, (int)swAutodimVerticalPlacement_e.swAutodimVerticalPlacementLeft);

            swModel.InsertSketch2(true);

            swFeature      = swModel.FeatureByPositionReverse(0);
            swFeature.Name = "Sketch1";

            swModel.Extension.SelectByID2("Sketch1", "SKETCH", 0, 0, 0, false, 0, null, 0);

            swModel.FeatureManager.InsertSheetMetalBaseFlange2(Thickness, false, Thickness, Width, 0, true, 0, 0, 0, null, false, 0, 0, 0, 0, false, false, false, false);

            BasicOpertations.ChangeEntityName("FACE", MateRef1, Thickness, YLenght / 2, -Width / 2);

            swModel.Extension.SelectByID2("", "FACE", XLenght / 2, Thickness, -Width / 2, false, 0, null, 0);

            swModel.InsertSketch2(true);

            swModel.CreateCircleByRadius2(XLenght - X1, X2, 0, BoltHoles);
            swModel.CreateCircleByRadius2(XLenght - X1, Width - X2, 0, BoltHoles);

            swModel.InsertSketch2(true);

            swFeature      = swModel.FeatureByPositionReverse(0);
            swFeature.Name = "BoltHoles";

            swModel.Extension.SelectByID2("BoltHoles", "SKETCH", 0, 0, 0, false, 0, null, 0);

            BasicOpertations.SimpleCut();


            swPart = (PartDoc)swApp.ActiveDoc;

            swEntity = swPart.GetEntityByName(MateRef1, (int)swSelectType_e.swSelFACES);
            swEntity.Select4(false, null);

            swModel.InsertSketch2(true);

            swModel.CreateCircleByRadius2(Width / 2, YLenght - (PipeHole * 2), 0, PipeHole);
            swModel.AddDiameterDimension(0, 0, 0);

            swModel.InsertSketch2(true);

            BasicOpertations.SimpleCut();

            BasicOpertations.ChangeEntityName("FACE", MateRefHole, Thickness / 2, YLenght - PipeHole, -Width / 2);

            swModel = (ModelDoc2)swApp.ActiveDoc;

            swModel.Extension.SelectByID2("", "EDGE", XLenght, Thickness / 2, 0, false, 0, null, 0);
            swModel.Extension.SelectByID2("", "EDGE", XLenght, Thickness / 2, -Width, true, 0, null, 0);

            BasicOpertations.SimpleFillet(Rad2);

            swModel.Extension.SelectByID2("", "EDGE", Thickness / 2, YLenght, 0, false, 0, null, 0);
            swModel.Extension.SelectByID2("", "EDGE", Thickness / 2, YLenght, -Width, true, 0, null, 0);

            BasicOpertations.SimpleFillet(Rad1);

            swModel.ClearSelection2(true);
            swModel.ViewZoomtofit2();

            DocumentManager.Save(TargetFolder, FileName, DocumentManager.sw_DocType.part);
        }
 protected override void SubscribePartEvents(PartDoc part)
 {
     part.SaveToStorageStoreNotify += OnWriteToStorageNotify;
 }
示例#25
0
        /// <summary>
        /// 零件导出dxf
        /// </summary>
        /// <param name="swApp"></param>
        /// <param name="swPart"></param>
        /// <param name="dxfPath"></param>
        public void PartToDxf(SldWorks swApp, ModelDoc2 swModel, string modulePath)
        {
            PartDoc swPart = (PartDoc)swModel;

            if (swPart == null)
            {
                return;
            }
            string swModelName = swModel.GetPathName();
            string swDxfName   = modulePath + @"\" + swModel.GetTitle().Substring(0, swModel.GetTitle().Length - 6) + "dxf";

            double[] dataAlignment = new double[12];
            dataAlignment[0]  = 0.0;
            dataAlignment[1]  = 0.0;
            dataAlignment[2]  = 0.0;
            dataAlignment[3]  = 1.0;
            dataAlignment[4]  = 0.0;
            dataAlignment[5]  = 0.0;
            dataAlignment[6]  = 0.0;
            dataAlignment[7]  = 1.0;
            dataAlignment[8]  = 0.0;
            dataAlignment[9]  = 0.0;
            dataAlignment[10] = 0.0;
            dataAlignment[11] = 1.0;
            //Array[0], Array[1], Array[2] - XYZ coordinates of new origin
            //Array[3], Array[4], Array[5] - coordinates of new x direction vector
            //Array[6], Array[7], Array[8] - coordinates of new y direction vector
            //判断XYAXIS,长边作为X轴,短的作为Y轴,用于限定拉丝方向
            bool status = false;

            if (swModel.Extension.SelectByID2("XYAXIS", "SKETCH", 0, 0, 0, false, 0, null, 0))
            {
                status = true;
            }
            else if (swModel.Extension.SelectByID2("xyaxis", "SKETCH", 0, 0, 0, false, 0, null, 0))
            {
                status = true;
            }
            else if (swModel.Extension.SelectByID2("XY", "SKETCH", 0, 0, 0, false, 0, null, 0))
            {
                status = true;
            }
            else if (swModel.Extension.SelectByID2("xy", "SKETCH", 0, 0, 0, false, 0, null, 0))
            {
                status = true;
            }
            if (status)
            {
                Feature swFeature      = swModel.SelectionManager.GetSelectedObject6(1, -1);
                Sketch  swSketch       = swFeature.GetSpecificFeature2();
                var     swSketchPoints = swSketch.GetSketchPoints2(); //获取草图中的所有点
                                                                      //用这三个点抓取直线,并判断长度,长边作为X轴,画3D草图的时候一次性画出两条线,不能分两次画出,否则会判断错误
                SketchPoint p0 = swSketchPoints[0];                   //最先画的点
                SketchPoint p1 = swSketchPoints[1];                   //作为坐标原点
                SketchPoint p2 = swSketchPoints[2];                   //最后画的点
                dataAlignment[0] = p1.X * 1000;
                dataAlignment[1] = p1.Y * 1000;
                dataAlignment[2] = p1.X * 1000;
                double l1 = Math.Sqrt(Math.Pow(p0.X - p1.X, 2) + Math.Pow(p0.Y - p1.Y, 2) + Math.Pow(p0.Z - p1.Z, 2));
                double l2 = Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2) + Math.Pow(p2.Z - p1.Z, 2));
                if (l1 > l2)
                {
                    dataAlignment[3] = p0.X * 1000 - p1.X * 1000;
                    dataAlignment[4] = p0.Y * 1000 - p1.Y * 1000;
                    dataAlignment[5] = p0.Z * 1000 - p1.Z * 1000;
                    dataAlignment[6] = p2.X * 1000 - p1.X * 1000;
                    dataAlignment[7] = p2.Y * 1000 - p1.Y * 1000;
                    dataAlignment[8] = p2.Z * 1000 - p1.Z * 1000;
                }
                else
                {
                    dataAlignment[3] = p2.X * 1000 - p1.X * 1000;
                    dataAlignment[4] = p2.Y * 1000 - p1.Y * 1000;
                    dataAlignment[5] = p2.Z * 1000 - p1.Z * 1000;
                    dataAlignment[6] = p0.X * 1000 - p1.X * 1000;
                    dataAlignment[7] = p0.Y * 1000 - p1.Y * 1000;
                    dataAlignment[8] = p0.Z * 1000 - p1.Z * 1000;
                }
            }
            object varAlignment = dataAlignment;

            //Export sheet metal to a single drawing file将钣金零件导出单个dxf文件
            //include flat-pattern geometry,倒数第二位数字1代表钣金展开,options = 1;
            try
            {
                swPart.ExportToDWG2(swDxfName, swModelName, (int)swExportToDWG_e.swExportToDWG_ExportSheetMetal, true, varAlignment, false, false, 1, null);
            }
            catch (Exception ex)
            {
                throw new Exception(swModelName + "导图过程发生异常" + ex.Message);
            }
        }
示例#26
0
 protected override void DetachPartEvents(PartDoc part)
 {
     part.FileSaveNotify -= OnFileSave;
     part.RegenNotify    -= OnRegen;
 }
示例#27
0
 protected abstract void UnsubscribePartEvents(PartDoc part);
示例#28
0
        private void dump_material_visual_properties(MaterialVisualPropertiesData myMatVisProps, PartDoc myPart)
        {
            string configName = null;
            string databaseName = null;
            string propName = null;
            //bool bBlendColor = false;
            bool bApplyColor = false;
            bool bApplyAppearance = false;
            configName = "default";
            databaseName = null;
            propName = myPart.GetMaterialPropertyName2(configName, out databaseName);

            if ((myMatVisProps != null))
            {
                //bBlendColor = myMatVisProps.BlendColor;
                bApplyColor = myMatVisProps.ApplyMaterialColorToPart;
                bApplyAppearance = myMatVisProps.ApplyAppearance;

                ////MessageBox.Show("   SolidWorks standard texture scale = " + dScale + ", Angle = " + dAngle);
                //if (bBlendColor == false)
                //{
                //    //MessageBox.Show("   Do not blend part color with SolidWorks standard texture.");
                //}
                //else
                //{
                //    //MessageBox.Show("   Blend part color with SolidWorks standard texture.");
                //}

                if (bApplyColor == false)
                {
                    //MessageBox.Show("Do not apply material color to part.");
                }
                else
                {
                    //MessageBox.Show("Apply material color to part.");
                }

                if (bApplyAppearance == false)
                {
                    //MessageBox.Show("Do not apply appearance.");
                }
                else
                {
                    //MessageBox.Show("Apply appearance.");
                }

            }
        }
示例#29
0
 protected override void UnsubscribePartEvents(PartDoc part)
 {
     part.NewSelectionNotify -= OnNewSelection;
 }
示例#30
0
 public PartEventHandler(ModelDoc2 modDoc, CAM_Setup_Sheets_Addin addin)
     : base(modDoc, addin)
 {
     doc = (PartDoc)document;
 }
 protected override void SubscribePartEvents(PartDoc part)
 {
     part.LoadFromStorageNotify += OnLoadFromStreamNotify;
     SubscribeIdleEvent();
 }
示例#32
0
        protected override void Command()
        {
            try
            {
                CreerDossierExport(MdlBase);

                var dic = MdlBase.ListerComposants(false);

                int MdlPct = 0;
                foreach (var mdl in dic.Keys)
                {
                    WindowLog.SautDeLigne();
                    WindowLog.EcrireF("[{1}/{2}] {0}", mdl.eNomSansExt(), ++MdlPct, dic.Count);

                    mdl.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc);
                    var cfgActive = mdl.eNomConfigActive();

                    var ListeNomConfigs = dic[mdl];
                    int CfgPct          = 0;
                    foreach (var NomConfigPliee in ListeNomConfigs.Keys)
                    {
                        WindowLog.SautDeLigne();
                        WindowLog.EcrireF("  [{1}/{2}] Config : \"{0}\"", NomConfigPliee, ++CfgPct, ListeNomConfigs.Count);
                        mdl.ShowConfiguration2(NomConfigPliee);
                        mdl.EditRebuild3();
                        mdl.eEffacerSelection();

                        var     NbConfig = dic[mdl][NomConfigPliee];
                        PartDoc Piece    = mdl.ePartDoc();

                        var ListeDossier = Piece.eListeDesDossiersDePiecesSoudees(
                            dossier =>
                        {
                            if (dossier.eEstExclu() || dossier.IsNull() || (dossier.GetBodyCount() == 0))
                            {
                                return(false);
                            }

                            String Profil   = dossier.eProp(CONSTANTES.PROFIL_NOM);
                            String Longueur = dossier.eProp(CONSTANTES.PROFIL_LONGUEUR);

                            if (String.IsNullOrWhiteSpace(Profil) || String.IsNullOrWhiteSpace(Longueur))
                            {
                                return(false);
                            }

                            foreach (var Barre in dossier.eListeDesCorps())
                            {
                                Barre.Select2(true, null);
                            }

                            return(true);
                        }
                            );

                        if (ListeDossier.Count == 0)
                        {
                            continue;
                        }

                        var NomFichier = String.Format("{0}-{1} (x{2}) - {3}", mdl.eNomSansExt(), NomConfigPliee, NbConfig, Indice);

                        var mdlExport = ExportSelection(Piece, NomFichier, eTypeFichierExport.Piece);

                        if (mdlExport.IsNull())
                        {
                            WindowLog.EcrireF("Erreur : {0}", NomFichier);
                            continue;
                        }

                        WindowLog.EcrireF("     {0}", NomFichier);

                        mdlExport.ViewZoomtofit2();
                        mdlExport.ShowNamedView2("*Isométrique", 7);
                        int lErrors = 0, lWarnings = 0;
                        mdlExport.Save3((int)swSaveAsOptions_e.swSaveAsOptions_Silent, ref lErrors, ref lWarnings);

                        mdlExport.eFermer();

                        mdl.eFermerSiDifferent(MdlBase);
                    }
                }
            }
            catch (Exception e)
            {
                this.LogErreur(new Object[] { e });
            }
        }
示例#33
0
 protected override void UnsubscribePartEvents(PartDoc part)
 {
     part.WeldmentCutListUpdatePostNotify -= OnWeldmentCutListUpdatePostNotify;
 }
示例#34
0
        public View CreerVueToleDvp(DrawingDoc dessin, Sheet feuille, PartDoc piece, String configDepliee, String Ref, String materiau, int quantite, Double epaisseur)
        {
            var NomVue = piece.eModelDoc2().eNomSansExt() + " - " + configDepliee;

            dessin.eModelDoc2().eEffacerSelection();

            View Vue = dessin.CreateFlatPatternViewFromModelView3(piece.eModelDoc2().GetPathName(), configDepliee, 0, 0, 0, !AfficherLignePliage, false);

            Vue.ScaleDecimal = 1;

            if (Vue.IsRef())
            {
                Vue.SetName2(NomVue);

                GeomVue g = AppliquerOptionsVue(dessin, piece, Vue);

                Vue.eSelectionner(dessin);

                try
                {
                    Note Note = dessin.eModelDoc2().InsertNote(String.Format("qté {0} // réf {1} [{2}] (Ep{3})", quantite, Ref, materiau, epaisseur));
                    Note.SetTextJustification((int)swTextJustification_e.swTextJustificationCenter);

                    Annotation Annotation = Note.GetAnnotation();

                    TextFormat swTextFormat = Annotation.GetTextFormat(0);
                    // Hauteur du texte en fonction des dimensions du dvp, 2.5% de la dimension max du dvp
                    swTextFormat.CharHeight = Math.Max(0.005, Math.Floor(Math.Max(g.Ht, g.Lg) * 0.025 * 1000) * 0.001);
                    Annotation.SetTextFormat(0, false, swTextFormat);

                    Annotation.Layer = "QUANTITE";
                    Annotation.SetLeader3((int)swLeaderStyle_e.swNO_LEADER, (int)swLeaderSide_e.swLS_SMART, true, true, false, false);
                    // Décalage du texte en fonction des dimensions du dvp, 0.1% de la dimension max du dvp
                    Annotation.SetPosition(g.ptCentreRectangleX, g.ptMinY - Math.Max(0.005, Math.Floor(Math.Max(g.Ht, g.Lg) * 0.001 * 1000) * 0.001), 0);
                    g.Agrandir(Note);
                }
                catch (Exception e)
                {
                    WindowLog.Ecrire("  - Erreur");
                    this.LogMethode(new Object[] { e });
                }

                if (InscrireNomTole)
                {
                    try
                    {
                        Note Note = dessin.eModelDoc2().InsertNote(Ref);
                        Note.SetTextJustification((int)swTextJustification_e.swTextJustificationCenter);

                        Annotation Annotation = Note.GetAnnotation();

                        TextFormat swTextFormat = Annotation.GetTextFormat(0);
                        // Hauteur du texte en fonction des dimensions du dvp, 2.5% de la dimension max du dvp
                        swTextFormat.CharHeight = TailleInscription * 0.001;
                        Annotation.SetTextFormat(0, false, swTextFormat);

                        Annotation.Layer = "GRAVURE";
                        Annotation.SetLeader3((int)swLeaderStyle_e.swNO_LEADER, (int)swLeaderSide_e.swLS_SMART, true, true, false, false);
                    }
                    catch (Exception e)
                    {
                        WindowLog.Ecrire("  - Erreur");
                        this.LogMethode(new Object[] { e });
                    }
                }

                PositionnerVue(feuille, Vue, g);

                return(Vue);
            }

            WindowLog.Ecrire("  - Erreur : pas de vue dvp");

            return(null);
        }
 public PartEventHandler(ModelDoc2 modDoc, SwAddin addin)
     : base(modDoc, addin)
 {
     doc = (PartDoc)document;
 }
示例#36
0
 public PartEventHandler(ModelDoc2 modDoc, DimensionRecorder addin)
     : base(modDoc,addin)
 {
     doc = (PartDoc)document;
 }