// Opens and returns a model, given a file path. Returns currently-active model if already open
        public ModelDoc2 GetSolidworksModelFromFile(string filePath)
        {
            // Declare variables
            ModelDoc2 currentModel = default(ModelDoc2);
            string    fileName     = new FileInfo(filePath).Name;
            int       i_errors     = 0;
            int       i_warnings   = 0;

            // Check if Solidworks.exe is open
            if (swApp == null)
            {
                ShowNonFatalError("Solidworks.exe is not open (var 'swApp' is null)!\n\nPlease start Solidworks and try again.");
                return(null);
            }

            // If requested model == already-open model, return current model
            currentModel = swApp.ActiveDoc;
            if (currentModel != null)
            {
                Console.WriteLine("Already-open model is titled '{0}'", currentModel.GetTitle());
                if (currentModel.GetTitle() == fileName)
                {
                    return(currentModel);
                }
            }

            // Open document
            try
            {
                Console.Write("Opening Solidworks file '" + fileName + "'... ");
                currentModel = swApp.OpenDoc6(filePath, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref i_errors, ref i_warnings);
                Console.Write("Opened.\n");
                Console.WriteLine("  Errors: " + i_errors);
                Console.WriteLine("  Warnings: " + i_warnings);
            }
            catch (Exception openDocExcept)
            {
                Console.WriteLine(openDocExcept.ToString());
                throw;
            }

            //// Get the current doc (should be the one we just opened)
            //currentModel = (ModelDoc2)swApp.ActiveDoc;

            // Exit if it failed
            if (currentModel == null)
            {
                ShowNonFatalError("Model failed to open (var 'currentModel' is null)!\n\nPlease try again.");
                return(null);
            }

            // Set the working directory to the document directory
            //swApp.SetCurrentWorkingDirectory(currentModel.GetPathName().Substring(0, currentModel.GetPathName().LastIndexOf("\\")));
            //string workingDirectory = swApp.GetCurrentWorkingDirectory();
            //var workingFolder = Path.Combine(Directory.GetParent(workingDirectory).Name, Path.GetFileName(workingDirectory));
            //Console.WriteLine("Current working directory is now " + workingFolder);

            // Return
            return(currentModel);
        }
Esempio n. 2
0
        public static void ActivateDoc(SldWorks iswApp)
        {
            int err  = -1;
            int warn = -1;

            iswApp.OpenDoc6(AppDomain.CurrentDomain.BaseDirectory + @"RectanglePlug\PlugTopBox.SLDPRT", (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_AutoMissingConfig, "圆壳", ref err, ref warn);
            iswApp.OpenDoc6(AppDomain.CurrentDomain.BaseDirectory + @"RectanglePlug\PlugWire.SLDPRT", (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_AutoMissingConfig, "", ref err, ref warn);
            ModelDoc2 Doc = iswApp.ActiveDoc;

            MessageBox.Show("当前激活文档:" + Doc.GetTitle());
            Doc = iswApp.ActivateDoc3("PlugTopBox.SLDPRT", true, (int)swRebuildOnActivation_e.swRebuildActiveDoc, ref err);
            MessageBox.Show("文档:" + Doc.GetTitle() + "被激活");
            Doc = iswApp.ActiveDoc;
            MessageBox.Show("当前激活文档:" + Doc.GetTitle());
        }
Esempio n. 3
0
        public void Place(PlaceSpec place, Model.CircuitComponent part)
        {
            var partPath = Path.Combine(workingFolder, part.PartName + ".sldprt");

            if (!File.Exists(partPath))
            {
                File.WriteAllBytes(partPath, part.Data);
            }

            var pattDoc = sw.OpenDoc6(partPath,
                                      (int)swDocumentTypes_e.swDocPART,
                                      (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref error, ref warning);

            // Activate main assembly
            sw.ActivateDoc3(doc.GetTitle(), true, (int)swRebuildOnActivation_e.swUserDecision, ref error);

            // In context of top projection place goes X -> -Z, Y -> X, Z -> Y
            var x = (place.YMm) / 1000;
            var y = 0.0;
            var z = (place.XMm) / 1000;

            var component = ((AssemblyDoc)doc).AddComponent5(Path.GetFileNameWithoutExtension(partPath),
                                                             (int)swAddComponentConfigOptions_e.swAddComponentConfigOptions_CurrentSelectedConfig,
                                                             "", false, "", x, y, z);

            RotatePartY(component, new[] { place.YMm / 1000, 0.0, -place.XMm / 1000 }, place.Angle);
        }
Esempio n. 4
0
        internal static bool processModel(SldWorks swApp, string file, List <CustomPropertyObject> CustomProperties, CancellationToken cancellationToken)
        {
            int Warning = 0;
            int Error   = 0;

            try
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return(false);
                }

                string extension = Path.GetExtension(file);
                int    type      = 0;
                if (extension.ToLower().Contains("sldprt"))
                {
                    type = (int)swDocumentTypes_e.swDocPART;
                }
                else
                {
                    type = (int)swDocumentTypes_e.swDocASSEMBLY;
                }


                ModelDoc2 swModel = swApp.OpenDoc6(file, type, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref Error, ref Warning) as ModelDoc2;
                if (Error != 0)
                {
                    return(false);
                }

                if (swModel == null)
                {
                    return(false);
                }

                swModel.Visible = false;
                foreach (CustomPropertyObject obj in CustomProperties)
                {
                    CustomPropertyManager customPropertyManager = swModel.Extension.CustomPropertyManager[""];
                    if (obj.Delete)
                    {
                        DeleteCustomProperty(customPropertyManager, obj.Name);
                    }
                    else
                    {
                        replaceCustomPropertyValue(customPropertyManager, obj.Name, obj.Value, obj.NewVal);
                    }

                    swModel.SaveSilent();
                    swApp.QuitDoc(swModel.GetTitle());

                    swModel = null;
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Esempio n. 5
0
 // Constructor for SW2URDF Exporter class
 public URDFExporter(ISldWorks iSldWorksApp)
 {
     constructExporter(iSldWorksApp);
     iSwApp.GetUserProgressBar(out progressBar);
     mSavePath    = System.Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%");
     mPackageName = ActiveSWModel.GetTitle();
 }
Esempio n. 6
0
        public static void NewDoc(SldWorks iswApp)
        {
            ModelDoc2     PartDoc  = iswApp.NewDocument(AppDomain.CurrentDomain.BaseDirectory + @"SwFile\PartTemplate.PRTDOT", (int)swDwgPaperSizes_e.swDwgPaperA0size, 10, 10);
            ModelDoc2     AssemDoc = iswApp.NewDocument(AppDomain.CurrentDomain.BaseDirectory + @"SwFile\AssemTemplate.ASMDOT", (int)swDwgPaperSizes_e.swDwgPaperA0size, 10, 10);
            ModelDoc2     DrawDoc  = iswApp.NewDocument(AppDomain.CurrentDomain.BaseDirectory + @"SwFile\DrawingTemplate.DRWDOT", (int)swDwgPaperSizes_e.swDwgPaperA0size, 10, 10);
            StringBuilder Sb       = new StringBuilder();

            if (PartDoc != null)
            {
                Sb.Append("零件新建成功" + PartDoc.GetTitle() + "\r\n");
            }
            else
            {
                Sb.Append("零件新建失败!" + "\r\n");
            }
            if (AssemDoc != null)
            {
                Sb.Append("装配体新建成功" + AssemDoc.GetTitle() + "\r\n");
            }
            else
            {
                Sb.Append("装配体新建失败!" + "\r\n");
            }
            if (DrawDoc != null)
            {
                Sb.Append("图纸新建成功" + DrawDoc.GetTitle() + "\r\n");
            }
            else
            {
                Sb.Append("图纸新建失败!" + "\r\n");
            }
            MessageBox.Show(Sb.ToString().Trim());
        }
Esempio n. 7
0
        private Boolean DocCheck()
        {
            if (swModel == null)
            {
                ExportPDFException e = new ExportPDFException("You must have a drawing document open.");
                return(false);
            }
            else if ((Int32)swModel.GetType() != (Int32)swDocumentTypes_e.swDocDRAWING)
            {
                ExportPDFException e = new ExportPDFException("You must have a drawing document open.");
                return(false);
            }
            else if (swModel.GetPathName() == String.Empty)
            {
                swModel.Extension.RunCommand((int)swCommands_e.swCommands_SaveAs, swModel.GetTitle());
                if (swModel.GetPathName() == string.Empty)
                {
                    return(false);
                }

                return(true);
            }
            else
            {
                return(true);
            }
        }
Esempio n. 8
0
        public static void GetDocObject(SldWorks iswApp)
        {
            StringBuilder sb    = new StringBuilder("");
            ModelDoc2     SwDoc = iswApp.ActiveDoc;//获得当前激活的文档

            sb.Append("文档:" + SwDoc.GetTitle() + "\r\n");
            int DocType = SwDoc.GetType();                   //获得激活的文档类型

            if (DocType == (int)swDocumentTypes_e.swDocPART) //若类型是零件
            {
                PartDoc SwPart = (PartDoc)SwDoc;
                sb.Append("文档类型:零部件\r\n");
            }
            else if (DocType == (int)swDocumentTypes_e.swDocASSEMBLY)//若类型是装配体
            {
                AssemblyDoc SwAssem = (AssemblyDoc)SwDoc;
                sb.Append("文档类型:装配体\r\n");
            }
            else if (DocType == (int)swDocumentTypes_e.swDocDRAWING)//若类型是工程图
            {
                DrawingDoc SwAssem = (DrawingDoc)SwDoc;
                sb.Append("文档类型:工程图\r\n");
            }
            ModelDocExtension SwDocEx = SwDoc.Extension;//获得扩展文档对象

            if (SwDocEx != null)
            {
                sb.Append("扩展文档:已获得");
            }
            MessageBox.Show(sb.ToString().Trim());
        }
Esempio n. 9
0
    public void Collect()
    {
        string      fullpath = (SwApp.ActiveDoc as ModelDoc2).GetPathName();
        SWTableType swt      = null;
        ModelDoc2   md       = (ModelDoc2)SwApp.ActiveDoc;

        try {
            swt = new SWTableType(md, Hashes);
        } catch (SWTableTypeException te) {
            OnAppend(new AppendEventArgs(string.Format("{0} {1}", te.Message, md.GetTitle())));
            System.Diagnostics.Debug.WriteLine(te.Message);
        } catch (Exception e) {
            OnAppend(new AppendEventArgs(e.Message));
            System.Diagnostics.Debug.WriteLine(e.Message);
        }
        FileInfo fi = new FileInfo(fullpath);

        create_dwg(fi);
        OnAppend(new AppendEventArgs(string.Format("Added {0}...", fi.Name)));
        FileInfo top_level = d.GetPath(Path.GetFileNameWithoutExtension(fullpath));

        lfi.Add(top_level);
        OnAppend(new AppendEventArgs(string.Format(@"Using {0}...", swt.found_bom.Name)));
        collect_drwgs(md, swt, 1);
        OnDone(EventArgs.Empty);
    }
Esempio n. 10
0
        public List <SheetMetalProperty> GetSheetMetalProperty(ModelDoc2 _swModel, Feature swFeat)
        {
            var getsheetmetalproperty = new List <SheetMetalProperty>();

            var canselect = _swModel.Extension.SelectByID2("Листовой металл1" + "@" + _swModel.GetTitle(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

            if (!canselect)
            {
                _swModel.Extension.SelectByID2("Листовой металл" + "@" + _swModel.GetTitle(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);
            }


            swFeat.Select(true);

            var swSelMgr = _swModel.ISelectionManager;

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

            SheetMetalFeatureData swSheetMetal = swFeat.GetDefinition();

            swFeat.ModifyDefinition(swSheetMetal, _swModel, null);


            var sheetMetalValout = new SheetMetalProperty()
            {
                BendRadius = Math.Abs(swSheetMetal.BendRadius * 1000),
                KFactor    = swSheetMetal.KFactor,
                Thickness  = Math.Abs(swSheetMetal.Thickness * 1000)
            };

            getsheetmetalproperty.Add(sheetMetalValout);

            return(getsheetmetalproperty);
        }
        public void SetupAssemblyExporter()
        {
            ModelDoc2 modeldoc = SwApp.ActiveDoc;

            logger.Info("Assembly export called for file " + modeldoc.GetTitle());
            bool saveAndRebuild = false;

            if (modeldoc.GetSaveFlag())
            {
                saveAndRebuild = true;
                logger.Info("Save is required");
            }
            else if (modeldoc.Extension.NeedsRebuild2 !=
                     (int)swModelRebuildStatus_e.swModelRebuildStatus_FullyRebuilt)
            {
                saveAndRebuild = true;
                logger.Info("A rebuild is required");
            }
            if (saveAndRebuild ||
                MessageBox.Show("The SW to URDF exporter requires saving and/or rebuilding before continuing",
                                "Save and rebuild document?", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                int options = (int)swSaveAsOptions_e.swSaveAsOptions_SaveReferenced |
                              (int)swSaveAsOptions_e.swSaveAsOptions_Silent;
                logger.Info("Saving assembly");
                modeldoc.Save3(options, 0, 0);

                logger.Info("Opening property manager");
                SetupPropertyManager();
            }
        }
Esempio n. 12
0
        // Толщина листового металла
        internal void AddPropThickness(string configName, bool sheet)
        {
            _swapp = new SldWorks {
                Visible = true
            };
            _swmodel = (ModelDoc2)_swapp.ActiveDoc;
            try
            {
                if (sheet)
                {
                    _swmodel.DeleteCustomInfo2(configName, "Толщина листового металла");

                    var titleName = _swmodel.GetTitle();

                    _swmodel.AddCustomInfo3(configName, "Толщина листового металла", 30, "\"Толщина@" + configName + "@" + titleName + ".sldprt" + "\"");
                    _swmodel.ShowConfiguration(configName);
                }
                else
                {
                    _swmodel.DeleteCustomInfo2(configName, "Толщина листового металла");
                }
            }
            catch (Exception ex)
            {
                Error = ex.Message;
            }
        }
        public SwModelWrapper(SwApiWrapper swApi, SldWorks swApp, swDocumentTypes_e swDocType, ModelDoc2 swMainModel, string strConfigName)
        {
            this.swApi       = swApi;
            this.swApp       = swApp;
            this.swMainModel = swMainModel;

            swModelDocExt = (ModelDocExtension)swMainModel.Extension;

            if (swDocType == swDocumentTypes_e.swDocASSEMBLY)
            {
                swMainAssembly = (AssemblyDoc)swMainModel;
            }

            if (strConfigName != null)
            {
                this.swMainConfig = (Configuration)swMainModel.GetConfigurationByName(strConfigName);
            }
            else
            {
                this.swMainConfig = (Configuration)swMainModel.GetActiveConfiguration();
            }
            strConfigName = this.swMainConfig.Name;


            // Write model info to shared variables
            string[] configsArray = swMainModel.GetConfigurationNames();
            this.configNames.AddRange(configsArray);
            this.configNames.Sort();
            this.pathName          = swMainModel.GetPathName();
            this.modelName         = swMainModel.GetTitle();
            this.currentConfigName = strConfigName;
        }
Esempio n. 14
0
                public static void Add(SldWorks swApp, ModelDoc2 parentDoc)
                {
                    swApp.ActivateDoc(parentDoc.GetTitle());
                    var configuration = ((Configuration)parentDoc.GetActiveConfiguration()).Name;
                    var swCustProp    = parentDoc.Extension.CustomPropertyManager[configuration];

                    AddProperty(swCustProp, new KeyValuePair <string, string> ("Наименование", "Новое наименование"));
                }
 private void MessageForm_FormClosing(object sender, FormClosingEventArgs e)
 {
     if (doc != null && swApp != null)
     {
         swApp.QuitDoc(doc.GetTitle());
         doc = null;
     }
 }
Esempio n. 16
0
        public List <SheetMetalProperty> GetSheetMetalProperty(ModelDoc2 swModel, Feature swFeat)
        {
            var getsheetmetalproperty = new List <SheetMetalProperty>();

            try
            {
                //var str = (from value in Sketches() where value == "Листовой металл1" | value ==  "Листовой металл" | value ==  "Sheet-Metal1" select value.ToList());

                //foreach (var sketch in Sketches())
                //{

                //MessageBox.Show(sketch);

                var canSelect = swModel.Extension.SelectByID2("Листовой металл1" + "@" + swModel.GetTitle(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);
                //var canselect = swModel.Extension.SelectByID2(sketch + "@" + swModel.GetTitle(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

                if (!canSelect)
                {
                    var canselect2 = swModel.Extension.SelectByID2("Листовой металл" + "@" + swModel.GetTitle(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

                    if (!canselect2)
                    {
                        swModel.Extension.SelectByID2("Sheet-Metal1" + "@" + swModel.GetTitle(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);
                    }
                }

                swFeat.Select(true);

                var swSelMgr = swModel.ISelectionManager;

                swFeat = swSelMgr.GetSelectedObject6(1, -1);


                //if (swFeat != null)
                //{

                SheetMetalFeatureData swSheetMetal = swFeat.GetDefinition();

                swFeat.ModifyDefinition(swSheetMetal, swModel, null);

                var sheetMetalValout = new SheetMetalProperty()
                {
                    BendRadius = Math.Abs(swSheetMetal.BendRadius * 1000),
                    KFactor    = swSheetMetal.KFactor,
                    Thickness  = Math.Abs(swSheetMetal.Thickness * 1000)
                };

                getsheetmetalproperty.Add(sheetMetalValout);

                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            return(getsheetmetalproperty);
        }
        // Opens a Solidworks part, given a part TreeNode
        private bool OpenPartFromNode(TreeNode partNode)
        {
            // Gets the current part's name (if open), to break if new part is already open
            ModelDoc2 currentPart = default(ModelDoc2);

            currentPart = swApp.IActiveDoc2;
            string currentPartName;

            if (currentPart == null)
            {
                currentPartName = "";
            }
            else
            {
                currentPartName = currentPart.GetTitle();
            }

            // Get custom PartNodeInfo object from this node
            PartNodeInfo pNodeInfo = (PartNodeInfo)partNode.Tag;
            string       fileName  = pNodeInfo.FileName;

            // Exit if same part is already open
            if (fileName == currentPartName)
            {
                Console.WriteLine("Part is already opened. Skipping PartOpen.");
                currentModel = currentPart;

                // Exit out of any opened sketches
                if (currentModel.SketchManager.ActiveSketch != null)
                {
                    currentModel.InsertSketch2(true);
                }

                return(true);
            }

            // Close current part and open new part
            Console.WriteLine("Opening student {0}'s part file: '{1}'.", pNodeInfo.Student.Name, fileName);
            CloseCurrentPart();

            ModelDoc2 newPart = default(ModelDoc2);

            newPart = GetSolidworksModelFromFile(pNodeInfo.FilePath);
            if (newPart == null)  // Opens up the new part
            {
                Console.WriteLine("Failed to open part file '{0}'", fileName);
                return(false);
            }

            currentModel = newPart;

            Console.WriteLine("Opened part successfully.");
            ExpandAllSolidworksFeaturesInTree(newPart);
            return(true);
        }
Esempio n. 18
0
        internal void DeleteOrAddPropertyColor(string ConfigName, string RAL, string ralRus, string ralErp, string coatingtype, string coatingclass, bool color, SldWorks swApp)
        {
            if (swApp == null)
            {
                //_swapp = new SldWorks { Visible = true };
                swApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
            }


            _swmodel = (ModelDoc2)swApp.ActiveDoc;

            try
            {
                if (color)
                {
                    _swmodel.DeleteCustomInfo2(ConfigName, "Площадь покрытия");
                    _swmodel.DeleteCustomInfo2(ConfigName, "RAL");
                    _swmodel.DeleteCustomInfo2(ConfigName, "RALRus");
                    _swmodel.DeleteCustomInfo2(ConfigName, "Ral_ERP");
                    _swmodel.DeleteCustomInfo2(ConfigName, "Тип покрытия");
                    _swmodel.DeleteCustomInfo2(ConfigName, "Класс покрытия");

                    var titleName = _swmodel.GetTitle();

                    _swmodel.AddCustomInfo3(ConfigName, "Площадь покрытия", 30, "\"SW-SurfaceArea@@" + ConfigName + "@" + titleName + ".sldprt" + "\"");
                    _swmodel.AddCustomInfo3(ConfigName, "RAL", 30, RAL);
                    _swmodel.AddCustomInfo3(ConfigName, "RALRus", 30, ralRus);
                    _swmodel.AddCustomInfo3(ConfigName, "Ral_ERP", 30, ralErp);

                    _swmodel.AddCustomInfo3(ConfigName, "Тип покрытия", 30, coatingtype);
                    _swmodel.AddCustomInfo3(ConfigName, "Класс покрытия", 30, coatingclass);

                    _swmodel.ShowConfiguration(ConfigName);

                    GetPropertyBox(ConfigName);
                }
                else
                // Если не красим
                {
                    _swmodel.DeleteCustomInfo2(ConfigName, "Площадь покрытия");
                    _swmodel.DeleteCustomInfo2(ConfigName, "RAL");
                    _swmodel.DeleteCustomInfo2(ConfigName, "RALRus");
                    _swmodel.DeleteCustomInfo2(ConfigName, "Ral_ERP");
                    _swmodel.DeleteCustomInfo2(ConfigName, "Длина");
                    _swmodel.DeleteCustomInfo2(ConfigName, "Ширина");
                    _swmodel.DeleteCustomInfo2(ConfigName, "Высота");
                    _swmodel.DeleteCustomInfo2(ConfigName, "Тип покрытия");
                    _swmodel.DeleteCustomInfo2(ConfigName, "Класс покрытия");
                }
            }
            catch (Exception ex)
            {
                Error = ex.Message;
            }
        }
Esempio n. 19
0
        private string GetNameIfPartAlreadyNamed()
        {
            ModelDoc2 part = ((SldWorks)Marshal.GetActiveObject("SldWorks.Application")).ActiveDoc;

            if (part != null)
            {
                return(Path.GetFileNameWithoutExtension(part.GetTitle()));
            }

            return(string.Empty);
        }
Esempio n. 20
0
                public static void AddAll(SldWorks swApp, ModelDoc2 parentDoc, List <KeyValuePair <string, string> > properties)
                {
                    swApp.ActivateDoc(parentDoc.GetTitle());
                    var configuration = ((Configuration)parentDoc.GetActiveConfiguration()).Name;
                    var swCustProp    = parentDoc.Extension.CustomPropertyManager[configuration];

                    foreach (var property in properties)
                    {
                        AddProperty(swCustProp, property);
                    }
                }
Esempio n. 21
0
                public static List <KeyValuePair <string, string> > GetAll(SldWorks swApp, ModelDoc2 childDoc, string configuration)
                {
                    swApp.ActivateDoc(childDoc.GetTitle());
                    var swCustProp = childDoc.Extension.CustomPropertyManager[configuration];
                    var list       = new List <KeyValuePair <string, string> >();

                    foreach (var item in Properties)
                    {
                        list.Add(new KeyValuePair <string, string>(item.Key, GetProperty(swCustProp, item.Key)));
                    }
                    swApp.CloseDoc(Path.GetFileName(childDoc.GetPathName()));
                    return(list);
                }
Esempio n. 22
0
        /// <summary>
        /// 模型打包
        /// </summary>
        /// <param name="suffix">后缀</param>
        /// <param name="swApp">SW程序</param>
        /// <param name="modelPath">模型地址</param>
        /// <param name="itemPath">目标地址</param>
        /// <returns></returns>
        public static string PackAndGoFunc(string suffix, SldWorks swApp, string modelPath, string itemPath)
        {
            swApp.CommandInProgress = true;
            int               warnings      = 0;
            int               errors        = 0;
            ModelDoc2         swModelDoc    = default(ModelDoc2);
            ModelDocExtension swModelDocExt = default(ModelDocExtension);
            PackAndGo         swPackAndGo   = default(PackAndGo);

            //打开需要pack的模型
            swModelDoc = (ModelDoc2)swApp.OpenDoc6(modelPath, (int)swDocumentTypes_e.swDocASSEMBLY,
                                                   (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
            swModelDocExt = (ModelDocExtension)swModelDoc.Extension;
            swPackAndGo   = (PackAndGo)swModelDocExt.GetPackAndGo();
            // Get number of documents in assembly
            //namesCount = swPackAndGo.GetDocumentNamesCount();
            //Debug.Print("  Number of model documents: " + namesCount);
            // Include any drawings, SOLIDWORKS Simulation results, and SOLIDWORKS Toolbox components
            swPackAndGo.IncludeDrawings          = false;
            swPackAndGo.IncludeSimulationResults = false;
            swPackAndGo.IncludeToolboxComponents = false;

            // Set folder where to save the files,目标存放地址
            swPackAndGo.SetSaveToName(true, itemPath);
            //将文件展开到一个文件夹内,不要原始模型的文件夹结构
            // Flatten the Pack and Go folder structure; save all files to the root directory
            swPackAndGo.FlattenToSingleFolder = true;

            // Add a prefix and suffix to the filenames
            //swPackAndGo.AddPrefix = "SW_";添加后缀
            swPackAndGo.AddSuffix = "_" + suffix;
            try
            {
                // Pack and Go,执行PackAndGo
                swModelDocExt.SavePackAndGo(swPackAndGo);
            }
            catch (Exception ex)
            {
                throw new Exception("PackandGo过程中出现异常:" + ex.Message);
            }
            finally
            {
                swApp.CloseDoc(swModelDoc.GetTitle());
                swModelDoc = null;
                swApp.CommandInProgress = false;//及时关闭外部命令调用,否则影响SolidWorks的使用
            }
            string modelPathName = modelPath.Substring(modelPath.LastIndexOf(@"\") + 1);

            //返回packandgo后模型的地址
            return(itemPath + @"\" + modelPathName.Substring(0, modelPathName.LastIndexOf(".")) + "_" + suffix + ".sldasm");
        }
Esempio n. 23
0
        public static byte[] ModelToBytes(ModelDoc2 model)
        {
            try
            {
                string fileName = model.GetTitle() + ".SLDPRT";

                if (model.GetPathName() == null || model.GetPathName().Length == 0)
                {
                    MessageBox.Show("Please, save model before adding!", "Search 3d Models", MessageBoxButtons.OK);
                    MessageBox.Show("Model in DB will be with with name, that was in 'Model Name' input box!", "Attention!", MessageBoxButtons.OK);
                    bool boolstatus = model.Save3((int)swSaveAsOptions_e.swSaveAsOptions_SaveReferenced, 0, 0);
                }

                string sourcePath = model.GetPathName();

                string targetPath;

                if (GetModelsFolder() == null || GetModelsFolder().Length == 0)
                {
                    string myDocuments = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
                    targetPath = myDocuments + @"\Search3DModels\Temp\";
                }
                else
                {
                    targetPath = GetModelsFolder() + @"\Temp\";
                }

                string destinationFile = System.IO.Path.Combine(targetPath, fileName);

                if (!System.IO.Directory.Exists(targetPath))
                {
                    System.IO.Directory.CreateDirectory(targetPath);
                }

                System.IO.File.Copy(sourcePath, destinationFile, true);

                FileStream fs           = new FileStream(destinationFile, FileMode.Open, FileAccess.Read);
                byte[]     modelInBytes = new byte[fs.Length];
                fs.Read(modelInBytes, 0, System.Convert.ToInt32(fs.Length));
                fs.Close();
                Directory.Delete(targetPath, true);

                return(modelInBytes);
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.StackTrace, "modelToBytes()", MessageBoxButtons.OK);
            }
            return(null);
        }
        public static List <object> GetSelectedFaces(SldWorks swApplication, ModelDoc2 swModel)
        {
            swModel = swApplication.ActiveDoc;
            var swSafeEntityList = new List <object>();

            var modelType    = swModel.GetTitle();
            var documentType = (swDocumentTypes_e)swModel.GetType();

            if (documentType == swDocumentTypes_e.swDocPART)
            {
                var myPartDoc = (PartDoc)swModel;

                Array myBodyVar   = myPartDoc.GetBodies2((int)swBodyType_e.swAllBodies, true);
                int   myBodyCount = 0;
                for (myBodyCount = myBodyVar.GetLowerBound(0); myBodyCount <= myBodyVar.GetUpperBound(0); myBodyCount++)
                {
                    var myBodyComparison = (Body2)myBodyVar.GetValue(myBodyCount);

                    var swFace = (Face2)myBodyComparison.GetFirstFace();
                    while (swFace != null)
                    {
                        var idNode = swFace.GetHashCode();
                        swFace.SetFaceId(idNode);
                        swFace = swFace.GetNextFace();
                    }
                }

                var mySelManager   = (SelectionMgr)swModel.SelectionManager;
                var selectionCount = mySelManager.GetSelectedObjectCount2(-1);
                //swApplication.SendMsgToUser("Numero oggetti selezionati " + selectionCount.ToString());
                for (int i = 0; i < selectionCount; i++)
                {
                    var myFace = (Face2)mySelManager.GetSelectedObject6(i + 1, -1);
                    //  var idNode = myFace.GetHashCode();
                    //  myFace.SetFaceId(idNode);
                    var swEntity     = ((Entity)myFace).GetSafeEntity();
                    var swSafeEntity = (Entity)swEntity.GetSafeEntity();
                    swSafeEntityList.Add(swSafeEntity);
                }
            }

            //var listFace = new List<Face2>();
            //swApplication.SendMsgToUser("Lista facce " + listFace.Count.ToString());
            //foreach (Face2 face2 in listFace)
            //{
            //    swApplication.SendMsgToUser("Id: " + face2.GetFaceId().ToString());
            //}
            //ColorFace.KLColorFace(listFace, swApplication);
            return(swSafeEntityList);
        }
Esempio n. 25
0
                public static void AddAll(SldWorks swApp, ModelDoc2 parentDoc, List <KeyValuePair <string, string> > properties)
                {
                    swApp.ActivateDoc(parentDoc.GetTitle());
                    var configuration = ((Configuration)parentDoc.GetActiveConfiguration()).Name;

                    MessageBox.Show("configuration - " + configuration);
                    var swCustProp = parentDoc.Extension.CustomPropertyManager[configuration];

                    foreach (var property in properties)
                    {
                        MessageBox.Show(property.Key + " - " + property.Value, "Свойство для добавления");
                        AddProperty(swCustProp, property);
                    }
                }
Esempio n. 26
0
        public static void OpenDoc(SldWorks iswApp)
        {
            int       err     = -1;
            int       warn    = -1;
            ModelDoc2 OpenDoc = iswApp.OpenDoc6(AppDomain.CurrentDomain.BaseDirectory + @"RectanglePlug\PlugTopBox.SLDPRT", (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_AutoMissingConfig, "圆壳", ref err, ref warn);

            if (OpenDoc != null)
            {
                MessageBox.Show("零件打开成功:" + OpenDoc.GetTitle() + "\r\n");
            }
            else
            {
                MessageBox.Show("零件打开失败!" + "\r\n");
            }
        }
Esempio n. 27
0
                public static PartProperties Get(SldWorks swApp, ModelDoc2 childDoc, string configuration)
                {
                    swApp.ActivateDoc(childDoc.GetTitle());
                    var swCustProp = childDoc.Extension.CustomPropertyManager[configuration];

                    var configProps = new PartProperties
                    {
                        Config       = configuration,
                        Наименование = GetProperty(swCustProp, "Наименование"),
                        Обозначение  = GetProperty(swCustProp, "Обозначение"),
                        Материал     = GetProperty(swCustProp, "Материал"),
                    };

                    return(configProps);
                }
Esempio n. 28
0
        // Constructor for SW2URDF Exporter class
        public ExportHelper(SldWorks iSldWorksApp)
        {
            ConstructExporter(iSldWorksApp);
            iSwApp.GetUserProgressBar(out progressBar);

            SavePath    = System.Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%");
            PackageName = ActiveSWModel.GetTitle();

            ReferenceCoordinateSystemNames = FindRefGeoNames("CoordSys");
            ReferenceAxesNames             = FindRefGeoNames("RefAxis");

            ComputeInertialValues  = true;
            ComputeVisualCollision = true;
            ComputeJointKinematics = true;
            ComputeJointLimits     = true;
        }
Esempio n. 29
0
        //The following runs when a new instance of the class is created
        public URDFExporterPM(SldWorks swAppPtr)
        {
            swApp                = swAppPtr;
            ActiveSWModel        = swApp.ActiveDoc;
            Exporter             = new URDFExporter(swApp);
            Exporter.mRobot      = new robot();
            Exporter.mRobot.name = ActiveSWModel.GetTitle();

            linksToVisit = new List <link>();
            docMenu      = new ContextMenuStrip();

            string PageTitle   = null;
            string caption     = null;
            string tip         = null;
            long   options     = 0;
            int    longerrors  = 0;
            int    controlType = 0;
            int    alignment   = 0;

            string[] listItems = new string[4];

            ActiveSWModel.ShowConfiguration2("URDF Export");


            #region Create and instantiate components of PM page
            //Set the variables for the page
            PageTitle = "URDF Exporter";
            //options = (int)swPropertyManagerButtonTypes_e.swPropertyManager_OkayButton + (int)swPropertyManagerButtonTypes_e.swPropertyManager_CancelButton + (int)swPropertyManagerPageOptions_e.swPropertyManagerOptions_LockedPage + (int)swPropertyManagerPageOptions_e.swPropertyManagerOptions_PushpinButton;
            options = (int)swPropertyManagerPageOptions_e.swPropertyManagerOptions_OkayButton + (int)swPropertyManagerPageOptions_e.swPropertyManagerOptions_CancelButton + (int)swPropertyManagerPageOptions_e.swPropertyManagerOptions_HandleKeystrokes;

            //Create the PropertyManager page
            pm_Page = (PropertyManagerPage2)swApp.CreatePropertyManagerPage(PageTitle, (int)options, this, ref longerrors);

            //Make sure that the page was created properly
            if (longerrors == (int)swPropertyManagerPageStatus_e.swPropertyManagerPage_Okay)
            {
                setupPropertyManagerPage(ref caption, ref tip, ref options, ref controlType, ref alignment);
            }

            else
            {
                //If the page is not created
                System.Windows.Forms.MessageBox.Show("An error occurred while attempting to create the " + "PropertyManager Page");
            }

            #endregion
        }
Esempio n. 30
0
        public int OnDocLoad(string docTitle, string docPath)
        {
            ModelDoc2 modDoc = (ModelDoc2)iSwApp.GetFirstDocument();

            while (modDoc != null)
            {
                if (modDoc.GetTitle() == docTitle)
                {
                    if (!openDocs.Contains(modDoc))
                    {
                        AttachModelDocEventHandler(modDoc);
                    }
                }
                modDoc = (ModelDoc2)modDoc.GetNext();
            }
            return(0);
        }
Esempio n. 31
0
        // This creates a Link from a Part ModelDoc. It basically just extracts the material properties and saves them to the appropriate fields.
        public link createLinkFromPartModel(ModelDoc2 swModel)
        {
            link Link = new link();
            Link.name = swModel.GetTitle();

            Link.isFixedFrame = false;
            Link.Visual = new visual();
            Link.Inertial = new inertial();
            Link.Collision = new collision();

            //Get link properties from SolidWorks part
            IMassProperty swMass = swModel.Extension.CreateMassProperty();
            Link.Inertial.Mass.value = swMass.Mass;
            double[] moment = swMass.GetMomentOfInertia((int)swMassPropertyMoment_e.swMassPropertyMomentAboutCenterOfMass); // returned as double with values [Lxx, Lxy, Lxz, Lyx, Lyy, Lyz, Lzx, Lzy, Lzz]
            Link.Inertial.Inertia.setMomentMatrix(moment);

            double[] centerOfMass = swMass.CenterOfMass;
            Link.Inertial.Origin.xyz = centerOfMass;
            Link.Inertial.Origin.rpy = new double[3] { 0, 0, 0 };

            // Will this ever not be zeros?
            Link.Visual.Origin.xyz = new double[3] { 0, 0, 0 };
            Link.Visual.Origin.rpy = new double[3] { 0, 0, 0 };
            Link.Collision.Origin.xyz = new double[3] { 0, 0, 0 };
            Link.Collision.Origin.rpy = new double[3] { 0, 0, 0 };

            // [ R, G, B, Ambient, Diffuse, Specular, Shininess, Transparency, Emission ]
            double[] values = swModel.MaterialPropertyValues;
            Link.Visual.Material.Color.Red = values[0];
            Link.Visual.Material.Color.Green = values[1];
            Link.Visual.Material.Color.Blue = values[2];
            Link.Visual.Material.Color.Alpha = 1.0 - values[7];
            Link.Visual.Material.name = "material_" + Link.name;

            return Link;
        }
Esempio n. 32
0
        //The following runs when a new instance of the class is created
        public URDFExporterPM(SldWorks swAppPtr)
        {
            swApp = swAppPtr;
            ActiveSWModel = swApp.ActiveDoc;
            Exporter = new URDFExporter(swApp);
            Exporter.mRobot = new robot();
            Exporter.mRobot.name = ActiveSWModel.GetTitle();

            linksToVisit = new List<link>();
            docMenu = new ContextMenuStrip();

            string PageTitle = null;
            string caption = null;
            string tip = null;
            long options = 0;
            int longerrors = 0;
            int controlType = 0;
            int alignment = 0;
            string[] listItems = new string[4];

            ActiveSWModel.ShowConfiguration2("URDF Export");

            #region Create and instantiate components of PM page
            //Set the variables for the page
            PageTitle = "URDF Exporter";
            //options = (int)swPropertyManagerButtonTypes_e.swPropertyManager_OkayButton + (int)swPropertyManagerButtonTypes_e.swPropertyManager_CancelButton + (int)swPropertyManagerPageOptions_e.swPropertyManagerOptions_LockedPage + (int)swPropertyManagerPageOptions_e.swPropertyManagerOptions_PushpinButton;
            options = (int)swPropertyManagerPageOptions_e.swPropertyManagerOptions_OkayButton + (int)swPropertyManagerPageOptions_e.swPropertyManagerOptions_CancelButton + (int)swPropertyManagerPageOptions_e.swPropertyManagerOptions_HandleKeystrokes;

            //Create the PropertyManager page
            pm_Page = (PropertyManagerPage2)swApp.CreatePropertyManagerPage(PageTitle, (int)options, this, ref longerrors);

            //Make sure that the page was created properly
            if (longerrors == (int)swPropertyManagerPageStatus_e.swPropertyManagerPage_Okay)
            {
                setupPropertyManagerPage(ref caption, ref tip, ref options, ref controlType, ref alignment);
            }

            else
            {
                //If the page is not created
                System.Windows.Forms.MessageBox.Show("An error occurred while attempting to create the " + "PropertyManager Page");
            }

            #endregion
        }