public void Dispose()
 {
     if (!m_IsDisposed)
     {
         m_App.CloseDoc(m_Model.GetTitle());
         m_IsDisposed = true;
     }
 }
Example #2
0
 private void CloseAllModel()
 {
     do
     {
         ModelDoc2 swModel = iSwApp.ActiveDoc as ModelDoc2;
         if (swModel != null)
         {
             iSwApp.CloseDoc(swModel.GetPathName());
         }
         else
         {
             break;
         }
     } while (true);
 }
Example #3
0
        public void Close()
        {
            try
            {
                if (!modelName.Contains("X11502139.SLDASM"))
                {
                    iSwApp.CloseDoc(modelName);
                }

                WriteLog(string.Format("关闭模型{0}!", Path.GetFileName(modelName)), 1);
            }
            catch (Exception ex)
            {
                WriteLog(string.Format("关闭模型失败{0}!", ex.ToString()), 2);
            }
        }
Example #4
0
        public double Build(double width, double height, double length, out int totalModelsBuilt)
        {
            m_TotalModelsBuilt++;

            var templatePath = m_App.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplatePart);

            var part = m_App.NewDocument(templatePath, (int)swDwgPaperSizes_e.swDwgPapersUserDefined, 0, 0) as IPartDoc;

            var box = m_App.IGetModeler().CreateBodyFromBox(
                new double[]
            {
                0, 0, 0,
                1, 0, 0,
                width, length, height
            });

            var feat = part.CreateFeatureFromBody3(box, false, (int)swCreateFeatureBodyOpts_e.swCreateFeatureBodySimplify);

            int errs  = -1;
            int warns = -1;

            var outPath = Path.Combine(m_BuildDir, $"{DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss")}.sldprt");

            var dir = Path.GetDirectoryName(outPath);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            (part as IModelDoc2).Extension.SaveAs(outPath, (int)swSaveAsVersion_e.swSaveAsCurrentVersion,
                                                  (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errs, ref warns);

            totalModelsBuilt = m_TotalModelsBuilt;

            var mass = (part as IModelDoc2).Extension.CreateMassProperty().Mass;

            m_App.CloseDoc((part as IModelDoc2).GetTitle());

            return(mass);
        }
Example #5
0
        private void UpdateCachedBodyIfNeeded(LinkFileMacroFeatureParameters parameters)
        {
            LastError = null;
            IModelDoc2 refDoc         = null;
            bool       isRefDocLoaded = false;

            try
            {
                if (File.Exists(parameters.LinkedFilePath))
                {
                    LastUpdateStamp = File.GetLastWriteTimeUtc(parameters.LinkedFilePath).Ticks;

                    refDoc = m_App.GetOpenDocumentByName(parameters.LinkedFilePath) as IModelDoc2;

                    isRefDocLoaded = refDoc != null;

                    if (LastUpdateStamp != parameters.FileLastUpdateTimeStamp ||
                        (isRefDocLoaded && refDoc.GetSaveFlag()) || CachedBodies == null)
                    {
                        if (!isRefDocLoaded)
                        {
                            m_App.DocumentVisible(false, (int)swDocumentTypes_e.swDocPART);

                            var docSpec = m_App.GetOpenDocSpec(parameters.LinkedFilePath) as IDocumentSpecification;
                            docSpec.Silent   = true;
                            docSpec.ReadOnly = true;

                            refDoc = m_App.OpenDoc7(docSpec);

                            if (refDoc == null)
                            {
                                throw new InvalidOperationException($"Failed to load the referenced file ${docSpec.FileName} with error: {(swFileLoadError_e)docSpec.Error}");
                            }
                        }

                        if (refDoc is IPartDoc)
                        {
                            var bodies = (refDoc as IPartDoc).GetBodies2((int)swBodyType_e.swAllBodies, true) as object[];

                            if (bodies != null && bodies.Any())
                            {
                                var resBodies = bodies.Cast <IBody2>().Select(b => b.ICopy()).ToArray();

                                CachedBodies = resBodies;
                            }
                            else
                            {
                                throw new InvalidOperationException("No bodies in the referenced document");
                            }
                        }
                        else
                        {
                            throw new InvalidOperationException("Referenced document is not a part");
                        }
                    }
                }
                else
                {
                    throw new FileNotFoundException($"Linked file '${parameters.LinkedFilePath}' is not found");
                }
            }
            catch (Exception ex)
            {
                LastError = ex;
            }
            finally
            {
                m_App.DocumentVisible(true, (int)swDocumentTypes_e.swDocPART);

                if (!isRefDocLoaded && refDoc != null)
                {
                    m_App.CloseDoc(refDoc.GetTitle());
                }
            }
        }
Example #6
0
 public void Close()
 {
     m_App.CloseDoc(Title);
 }
Example #7
0
 public static Task Using(this IModelDoc2 doc, ISldWorks sldWorks, Func <IModelDoc2, Task> run)
 {
     return(doc.Using(m => sldWorks.CloseDoc(doc.GetTitle()), run));
 }
Example #8
0
 public static void Using(this IModelDoc2 doc, ISldWorks sldWorks, Action <IModelDoc2> run)
 {
     doc.Using(m => sldWorks.CloseDoc(doc.GetTitle()), run);
 }
Example #9
0
 public void close()
 {
     swApp.CloseDoc(fileName);
 }                                                           //关闭模型文件
 /// <summary>
 /// 执行操作然后关闭文档
 /// </summary>
 /// <param name="doc"></param>
 /// <param name="sldWorks"></param>
 /// <param name="run"></param>
 public static void Using(this IModelDoc2 doc, ISldWorks sldWorks, Action <IModelDoc2> run)
 {
     run.Invoke(doc);
     sldWorks.CloseDoc(doc.GetTitle());
 }
Example #11
0
        private void buttonAuto_Click(object sender, EventArgs e)
        {
            //新建一个零件  ,画一条150长度的直线,然后最大化.

            ISldWorks iswApp = Utility.ConnectToSolidWorks();

            string partDefaultPath = iswApp.GetDocumentTemplate(1, "", 0, 0, 0);

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

            ModelDoc2 modelDoc = (ModelDoc2)iswApp.ActiveDoc;

            modelDoc.Extension.SelectByID2("Plane1", "PLANE", 0, 0, 0, false, 0, null, 0);

            modelDoc.SketchManager.InsertSketch(true);

            modelDoc.SketchManager.CreateLine(0, 0.1, 0, 0, 0, 0);

            modelDoc.SketchManager.InsertSketch(true);

            modelDoc.ClearSelection2(true);

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

            var b = modelDoc.InsertCompositeCurve();

            modelDoc.ClearSelection2(true);

            modelDoc.FeatureManager.ViewFeatures = false;

            modelDoc.ViewZoomtofit2();

            ModelView modelView = (ModelView)modelDoc.ActiveView;

            iswApp.FrameState = 1; //最大化solidworks
            modelDoc.ViewZoomtofit2();
            modelView.Scale2 = 0.5;

            //

            modelDoc.ClearSelection2(true);

            string ImagePath = @"D:\temp.JPG";

            modelDoc.SaveAs3(ImagePath, 0, 0);

            int LineInImage = img2color(ImagePath);

            try
            {
                System.IO.File.Delete(ImagePath);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }

            if (LineInImage > 0)
            {
                double ActionScreenHeight = double.Parse(txtSCHeight.Text); //GetScreenRealWeight(double.Parse( textScreenSize.Text));

                //当前视图的比例
                double ActionScale = modelView.Scale2;

                //solidworks中的直线占比
                double defaultSolidworksP = LineInImage / 1200.0;//double.Parse(txtScreenY.Text);

                //当前比例下 1像素  等于多少mm
                double thisSc = 100 / LineInImage;

                //实际屏幕 1 像素尺寸

                double oneP = (ActionScreenHeight) / 1200.0;

                //当比例设置为 1时 1像素能表示的长度:
                double onePshowLength = thisSc / ActionScale;

                //959  1370

                GetWindowsSize getWindowSize = new GetWindowsSize();

                GetWindowsSize.windsize solidworksize = getWindowSize.GetSize("SLDWORKS");

                double getSC = 50.0 / (LineInImage * oneP);

                txtSC.Text = getSC.ToString();// getSC.ToString();

                modelView.Scale2 = getSC;

                modelDoc.GraphicsRedraw2();

                Debug.Print(getSC.ToString());
                // modelView.Scale2 = double.Parse(txtSC.Text);
                // sldWorks.scen
            }

            iswApp.CloseDoc(modelDoc.GetPathName());
        }
Example #12
0
        public void GetTiff()
        {
            //object obt= iSwApp.GetAddInObject("ConisioSW2.ConisioSWAddIn") as SwAddin;
            //iSwApp.CommandInProgress = true;

            if (Directory.Exists("D:\\PDM\\"))
            {
                pdm_path = "D:\\PDM\\";
            }
            else if (Directory.Exists("C:\\PDM\\"))
            {
                pdm_path = "C:\\PDM\\";
            }
            else
            {
                MessageBox.Show("Не найден путь PDM"); return;
            }

            ModelDoc2         swModel;
            ModelDocExtension swModelDocExt;
            AssemblyDoc       swAssy;
            Component2        swComp;
            DrawingDoc        Part;

            int    errors   = 0;
            int    warnings = 0;
            string fileName;   // GetOpenFileName
            Dictionary <string, string> Dict, Drw;
            string projekt_path, key, pathName;

            string[] сonfNames;
            object[] Comps;

            swModel = (ModelDoc2)iSwApp.ActiveDoc;
            if (swModel == null)
            {
                fileName = iSwApp.GetOpenFileName("File to SLDASM", "", "SLDASM Files (*.SLDASM)|*.SLDASM|", out _, out _, out _);
                //Проверяем путь
                if (fileName == "")
                {
                    return;
                }
                swModel = (ModelDoc2)iSwApp.OpenDoc6(fileName, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
            }

            //Проверяем открыта сборка или нет
            if ((swModel.GetType() != 2) | (swModel == null))
            {
                iSwApp.SendMsgToUser2("Откройте сборку", 4, 2);

                return;
            }

            //FileAttributes attr = File.GetAttributes(@"c:\Temp");
            //attr.HasFlag(FileAttributes.Directory); // файл или дирректория
            //swModel = (ModelDoc2)swApp.ActiveDoc;

            swAssy       = (AssemblyDoc)swModel;
            Dict         = new Dictionary <string, string>();
            projekt_path = swModel.GetPathName().Remove(swModel.GetPathName().LastIndexOf((char)92) + 1);

            int value = iSwApp.SendMsgToUser2("Создать Tiff со всей сборки(Да) или только с её папки(Нет)?", 3, 5);

            iSwApp.UnloadAddIn(sAddinName);
            //iSwApp.SendMsgToUser2("Значение "+ value, 4, 2);
            switch (value)
            {
            case 3:
            {
                List <string> allDRW = new List <string>(Directory.GetFiles(projekt_path, "*.SLDDRW", SearchOption.AllDirectories));
                //iSwApp.SendMsgToUser2("Длина " + allDRW.Count, 4, 2);

                foreach (string pdrw in allDRW)
                {
                    key = pdrw.Substring(pdrw.LastIndexOf((char)92) + 1);
                    key = key.Substring(0, key.Length - 7);
                    if (!Dict.ContainsKey(key))
                    {
                        Dict.Add(key, pdrw.Substring(0, pdrw.Length - 7));
                    }
                }

                break;
            }

            case 6:
            {
                key      = swModel.GetPathName().Substring(swModel.GetPathName().LastIndexOf((char)92) + 1);
                key      = key.Substring(0, key.Length - 7);
                pathName = swModel.GetPathName();
                pathName = pathName.Remove(pathName.Length - 7);
                if (!Dict.ContainsKey(key))
                {
                    Dict.Add(key, pathName);
                }

                //Создаем список путей компонентов для всех конфигураций
                сonfNames = (string[])swModel.GetConfigurationNames();
                swAssy.ResolveAllLightWeightComponents(false);
                for (int i = 0; i < сonfNames.Length; i++)
                {
                    swModel.ShowConfiguration2((string)сonfNames[i]);
                    swModel.ForceRebuild3(false);
                    Comps = (object[])swAssy.GetComponents(false);
                    for (int j = 0; j < Comps.Length; j++)
                    {
                        swComp = (Component2)Comps[j];
                        //compDoc = (ModelDoc2)swComp.GetModelDoc2();
                        if ((swComp.GetSuppression() != (int)swComponentSuppressionState_e.swComponentSuppressed) & (swComp != null))
                        {
                            pathName = swComp.GetPathName();
                            pathName = pathName.Remove(pathName.Length - 7);
                            key      = swComp.GetPathName().Substring(swComp.GetPathName().LastIndexOf((char)92) + 1);
                            key      = key.Substring(0, key.Length - 7);
                            if (!Dict.ContainsKey(key))
                            {
                                Dict.Add(key, pathName);
                            }
                        }
                    }
                }
                break;
            }

            default:
            {
                iSwApp.LoadAddIn(sAddinName);
                return;
            }
            }
            //Находим где могут быть чертежи
            Drw = new Dictionary <string, string>();
            foreach (KeyValuePair <string, string> k in Dict)
            {
                if (value == 6)
                {
                    if ((k.Value.Contains((string)(pdm_path + "Проект"))) | (k.Value.Contains((pdm_path + "Общеприменяемые"))))
                    {
                        Drw.Add(k.Key, k.Value);
                    }
                }
                else
                {
                    Drw.Add(k.Key, k.Value);
                }
            }

            //Создаем папку
            DirectoryInfo dirInfo = new DirectoryInfo(projekt_path + "\\TIF");

            if (!dirInfo.Exists)
            {
                dirInfo.Create();
            }

            //Настройки TIF
            iSwApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swTiffScreenOrPrintCapture, 1); //1-Print capture
            iSwApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swTiffPrintPaperSize, 12);      //12-Papers User Defined
            iSwApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swTiffImageType, 0);            //0-Black And White
            iSwApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swTiffCompressionScheme, 2);    //2-Group 4 Fax Compression
            iSwApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swTiffPrintDPI, 600);           //300-Integer value

            //Сохраняем картинки
            int          itogo  = 0;
            StreamWriter writer = new StreamWriter(projekt_path + "TIF\\" + "Список" + ".txt", false);

            foreach (KeyValuePair <string, string> k in Drw)
            {
                //Настройка размеров картинки
                iSwApp.IGetTemplateSizes(k.Value + ".SLDDRW", out int PaperSize, out double Width, out double Height);
                iSwApp.SetUserPreferenceDoubleValue((int)swUserPreferenceDoubleValue_e.swTiffPrintDrawingPaperWidth, Width);   //Double value in meters
                iSwApp.SetUserPreferenceDoubleValue((int)swUserPreferenceDoubleValue_e.swTiffPrintDrawingPaperHeight, Height); //Double value in meters

                Part = (DrawingDoc)iSwApp.OpenDoc6(k.Value + ".SLDDRW", (int)swDocumentTypes_e.swDocDRAWING, (int)swOpenDocOptions_e.swOpenDocOptions_ViewOnly, "", ref errors, ref warnings);
                if ((errors == 0) & (Part != null))
                {
                    swModel       = (ModelDoc2)Part;
                    swModelDocExt = (ModelDocExtension)swModel.Extension;
                    swModelDocExt.SaveAs2(projekt_path + "TIF\\" + k.Key + ".TIF", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, "", false, ref errors, ref warnings);
                    writer.WriteLine(k.Value.Substring(k.Value.LastIndexOf((char)92) + 1));
                    itogo += 1;
                }
                iSwApp.CloseDoc(k.Value + ".SLDDRW");
                Part = null;
            }
            writer.Close();
            iSwApp.LoadAddIn(sAddinName);
            iSwApp.SendMsgToUser2("Всего частей " + Dict.Count + System.Environment.NewLine + "Чертежей сохранено " + itogo, 2, 2);
            //iSwApp.CommandInProgress = false;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="assemblyName"></param>
        /// <param name="partsname"></param>
        private void CreateNewAssembly(string assemblyName, List <string> partsname)
        {
            string assemblyDefaultPath = iswApp.GetDocumentTemplate(2, "", 0, 0, 0);

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

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

                ModelDoc2 modelDoc2 = assemblyDoc as ModelDoc2;

                ModelDocExtension swModExt = default(ModelDocExtension);

                int errors   = 0;
                int warnings = 0;

                swModExt = (ModelDocExtension)modelDoc2.Extension;

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

                modelDoc2 = (ModelDoc2)iswApp.ActiveDoc;

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

                    ProgressBar.Value = tempV + i;

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

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

                    Component2 swInsertedComponent = default(Component2);

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

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

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

                    assemblyDoc.UnfixComponent();

                    modelDoc2.ClearSelection2(true);

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

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

                    Mate2 mate2 = default(Mate2);

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

                    iswApp.CloseDoc(partN);

                    i = i + 1;
                }

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

            ProgressBar.Value = ProgressBar.Maximum;
        }
Example #14
0
        private void saveSTL(link Link, string windowsMeshFileName)
        {
            int errors   = 0;
            int warnings = 0;

            string coordsysName = "";

            coordsysName = (Link.Joint == null || Link.Joint.CoordinateSystemName == null) ? Link.CoordSysName : Link.Joint.CoordinateSystemName;

            Dictionary <string, string> names = GetComponentRefGeoNames(coordsysName);
            ModelDoc2 ActiveDoc = ActiveSWModel;

            string     ComponentName     = "";
            string     ConfigurationName = "";
            string     DisplayStateName  = "";
            Component2 geoComponent      = default(Component2);

            if (names["component"].Length > 0)
            {
                foreach (Component2 comp in Link.SWcomponents)
                {
                    if (comp.Name2 == names["component"])
                    {
                        geoComponent      = comp;
                        ComponentName     = comp.GetPathName();
                        ConfigurationName = comp.ReferencedConfiguration;
                        DisplayStateName  = comp.ReferencedDisplayState;
                        bool usenamed = comp.UseNamedConfiguration;
                        ActiveDoc = (ModelDoc2)iSwApp.ActivateDoc3(ComponentName, false, 0, 0);

                        Configuration config = ActiveDoc.GetConfigurationByName(ConfigurationName);
                        ActiveDoc.ShowConfiguration2(ConfigurationName);
                        config.ApplyDisplayState(DisplayStateName);
                    }
                    break;
                }
            }

            if (ComponentName.Length == 0)
            {
                Common.showComponents(ActiveSWModel, Link.SWcomponents);
            }

            int saveOptions = (int)swSaveAsOptions_e.swSaveAsOptions_Silent;

            setLinkSpecificSTLPreferences(names["geo"], Link.STLQualityFine, ActiveDoc);

            ActiveDoc.Extension.SaveAs(windowsMeshFileName, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, saveOptions, null, ref errors, ref warnings);
            if (ComponentName.Length > 0)
            {
                iSwApp.CloseDoc(ComponentName);
                geoComponent.ReferencedConfiguration = ConfigurationName;
            }
            else
            {
                Common.hideComponents(ActiveSWModel, Link.SWcomponents);
            }


            correctSTLMesh(windowsMeshFileName);
        }
Example #15
0
 static void CloseModel(IModelDoc2 swModel, ISldWorks swApp)
 {
     swApp.CloseDoc(swModel.GetTitle().ToLower().Contains(".sldprt") ? swModel.GetTitle() : swModel.GetTitle() + ".sldprt");
 }