private void Button_Click_4(object sender, RoutedEventArgs e) { if (swApp == null) { return; } ModelDocExtension swModelExt = swModel.Extension; string exportStepFileName = PARTNAME.Remove(PARTNAME.IndexOf(".")) + ".step"; string fileName = path.Text + @"set\" + exportStepFileName; Directory.CreateDirectory(path.Text + "set"); ExportPdfData exportPdf = default; int Err, Warn; Err = 0; Warn = 0; bool bRet; swModel.ClearSelection2(true); bRet = swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swStepAP, 214); bRet = swModelExt.SaveAs(fileName, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, 0, exportPdf, Err, Warn); if (bRet) { MessageBox.Show("Completed successfully"); } else { MessageBox.Show("export incomplete"); } }
public static bool saveAs(SldWorks swApp, Component2 swComp0, Component2 swComp1, ModelDocExtension swModelDocExt) { // Initiate variables string stComp0; int Error = 0; int Warnings = 0; bool bRet = false; // Get component name stComp0 = swComp0.GetPathName(); stComp0 = stComp0.Replace(Path.GetExtension(stComp0), ".stl"); // Set file preferences swApp.SetUserPreferenceDoubleValue(2, 0.00002); swApp.SetUserPreferenceDoubleValue(3, 0.174532925199433); swApp.SetUserPreferenceIntegerValue(78, 433); swApp.SetUserPreferenceToggle(69, false); swApp.SetUserPreferenceToggle(70, false); swApp.SetUserPreferenceToggle(191, false); // Save as .stl bRet = swModelDocExt.SaveAs(stComp0, 0, 1, null, ref Error, ref Warnings); // Check for errors if (Error != 0) { return(false); } if (Warnings != 0) { return(false); } // Return status bool return(bRet); }
private bool SaveSTEPorEDrw(List <string> fl) { if (fl.Count < 1) { return(false); } int saveVersion = (int)swSaveAsVersion_e.swSaveAsCurrentVersion; int saveOptions = (int)swSaveAsOptions_e.swSaveAsOptions_Silent; int refErrors = 0; int refWarnings = 0; bool success = true; string tmpPath = Path.GetTempPath(); ModelDocExtension swModExt = default(ModelDocExtension); ExportPdfData swExportPDFData = default(ExportPdfData); string fileName = fl[0]; FileInfo fi = new FileInfo(fileName); string tmpFile = tmpPath + "\\" + fi.Name; swModExt = swModel.Extension; bool stepconf = swApp.GetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExportConfigurationData); bool stepedgeprop = swApp.GetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExportFaceEdgeProps); bool stepsplit = swApp.GetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExportSplitPeriodic); bool stepcurve = swApp.GetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExport3DCurveFeatures); int stepAP = swApp.GetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swStepAP); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExportConfigurationData, true); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExportFaceEdgeProps, true); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExportSplitPeriodic, true); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExport3DCurveFeatures, false); swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swStepAP, 203); swFrame.SetStatusBarText(String.Format("Exporting '{0}'", fileName)); success = swModExt.SaveAs(tmpFile, saveVersion, saveOptions, swExportPDFData, ref refErrors, ref refWarnings); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExportConfigurationData, stepconf); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExportFaceEdgeProps, stepedgeprop); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExportSplitPeriodic, stepsplit); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swStepExport3DCurveFeatures, stepcurve); swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swStepAP, stepAP); foreach (string fn in fl) { CopyFile(tmpFile, fn); } if (fl[0].EndsWith(@"EPRT") || fl[0].EndsWith(@"EASM")) { InsertIntoDb(fl[0], Properties.Settings.Default.eDrawingTable); } return(success); }
private void ExportButtonClick(object sender, EventArgs e) { swModelDoc = swApp.ActiveDoc; swModelDocExt = swModelDoc.Extension; swAssDoc = swApp.ActiveDoc as AssemblyDoc; swFeat = (Feature)swModelDoc.FirstFeature(); swFeatMgr = (FeatureManager)swModelDoc.FeatureManager; while ((swFeat != null)) { sFeatType = swFeat.GetTypeName(); if (sFeatType == "CommentsFolder") { swCommentFolder = (CommentFolder)swFeat.GetSpecificFeature2(); nbrComments = swCommentFolder.GetCommentCount(); vComments = (object[])swCommentFolder.GetComments(); for (i = 0; i <= (nbrComments - 1); i++) { swComment = (Comment)vComments[i]; string name = swComment.Name; Component2 comp = swAssDoc.GetComponentByName(name); swModelDocExt.SelectByID2(comp.GetSelectByIDString(), "COMPONENT", 0, 0, 0, false, 0, null, 0); swAssDoc.HideComponent(); } for (i = 0; i <= (nbrComments - 1); i++) { swComment = (Comment)vComments[i]; string name = swComment.Name; Component2 comp = swAssDoc.GetComponentByName(name); swModelDocExt.SelectByID2(comp.GetSelectByIDString(), "COMPONENT", 0, 0, 0, false, 0, null, 0); swAssDoc.ShowComponent(); swModelDocExt.SetUserPreferenceString((int)swUserPreferenceStringValue_e.swFileSaveAsCoordinateSystem, (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified, "CoordinateSystem"); swModelDocExt.SaveAs("C:/Users/Izmar/Documents/vmpc_models/jan2018/stlexport/" + swComment.Text + ".STL", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, 0, ref errors, ref warnings); swAssDoc.HideComponent(); } for (i = 0; i <= (nbrComments - 1); i++) { swComment = (Comment)vComments[i]; string name = swComment.Name; Component2 comp = swAssDoc.GetComponentByName(name); swModelDocExt.SelectByID2(comp.GetSelectByIDString(), "COMPONENT", 0, 0, 0, false, 0, null, 0); swAssDoc.ShowComponent(); } } // Get next feature in FeatureManager design tree swFeat = (Feature)swFeat.GetNextFeature(); } }
private void button1_Click(object sender, EventArgs e) { if (this.connectToSolidWorks()) { // get the path to the example part String path = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Example.SLDPRT"); if (File.Exists(path)) { // open the example part in solidworks int errors = 0; ModelDoc2 swModel = swApp.OpenDoc2(path, (int)swDocumentTypes_e.swDocPART, true, false, true, ref errors); if (swModel != null) { PartDoc partDoc = (PartDoc)swModel; // get the solid bodies in the part var bodies = partDoc.GetBodies2((int)swBodyType_e.swSolidBody, false); ModelDocExtension swModExt = (ModelDocExtension)swModel.Extension; // iterate through each solid body and delete any hidden solidbodies foreach (Body2 body in bodies) { if (!body.Visible) { swModExt.SelectByID2(body.Name, "SOLIDBODY", 0, 0, 0, false, 0, null, 0); swModel.FeatureManager.InsertDeleteBody(); swModel.ClearSelection(); } } // export the result String desktopPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop); int warnings = 0; swModExt.SaveAs(Path.Combine(desktopPath, "Result.step"), 0, 0, null, ref errors, ref warnings); swApp.CloseAllDocuments(true); } } this.releaseSolidWorks(); } else { MessageBox.Show("Error starting SolidWorks."); } }
private void SalvarPDF() { string nome = Path.GetFileNameWithoutExtension(swModel.GetPathName()); // Pega o nome sem extensão do full path do nome original com extensão. int Error = 0; int Warnings = 0; bool bRet; bRet = swExt.SaveAs($@"C:\ELETROFRIO\ENGENHARIA SMR\PRODUTOS FINAIS ELETROFRIO\MECÂNICA\RACK PADRAO\COLETOR SUCCAO\{nome}.PDF", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref Error, ref Warnings); // Converte um enum do tipo int para a string do enum deixando mais claro o erro // pois será retornada um msg e não um int. swFileSaveError_e e = (swFileSaveError_e)Error; MessageBox.Show(e.ToString()); }
/// <summary> /// This thing does the saving. /// </summary> /// <param name="fl">A <see cref="System.Collections.Generic.List<>"/> of destination paths.</param> /// <returns>Returns a <see cref="System.Boolean"/>, indicating success.</returns> private Boolean SaveFiles(List <String> fl) { Int32 saveVersion = (Int32)swSaveAsVersion_e.swSaveAsCurrentVersion; Int32 saveOptions = (Int32)swSaveAsOptions_e.swSaveAsOptions_Silent; Int32 refErrors = 0; Int32 refWarnings = 0; Boolean success = true; string tmpPath = Path.GetTempPath(); ModelDocExtension swModExt = default(ModelDocExtension); ExportPdfData swExportPDFData = default(ExportPdfData); foreach (String fileName in fl) { FileInfo fi = new FileInfo(fileName); string tmpFile = tmpPath + "\\" + fi.Name; if (drawingPath != String.Empty) { swFrame.SetStatusBarText(String.Format("Checking path: '{0}'", fileName)); if (!CreatePath(fileName)) { ExportPDFException e = new ExportPDFException("Unable to save file, folder could not be created."); //e.Data.Add("who", System.Environment.UserName); //e.Data.Add("when", DateTime.Now); throw e; } String[] obj = (string[])swDraw.GetSheetNames(); object[] objs = new object[obj.Length - 1]; DispatchWrapper[] dr = new DispatchWrapper[obj.Length - 1]; for (int i = 0; i < obj.Length - 1; i++) { swDraw.ActivateSheet(obj[i]); Sheet s = (Sheet)swDraw.GetCurrentSheet(); objs[i] = s; dr[i] = new DispatchWrapper(objs[i]); } swFrame.SetStatusBarText(String.Format("Exporting '{0}'", fileName)); bool layerPrint = swApp.GetUserPreferenceToggle((int)swUserPreferenceToggle_e.swPDFExportIncludeLayersNotToPrint); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swPDFExportIncludeLayersNotToPrint, true); swExportPDFData = swApp.GetExportFileData((int)swExportDataFileType_e.swExportPdfData); swModExt = swModel.Extension; success = swExportPDFData.SetSheets((int)swExportDataSheetsToExport_e.swExportData_ExportAllSheets, (dr)); success = swModExt.SaveAs(tmpFile, saveVersion, saveOptions, swExportPDFData, ref refErrors, ref refWarnings); //success = swModel.SaveAs4(tmpFile, saveVersion, saveOptions, ref refErrors, ref refWarnings); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swPDFExportIncludeLayersNotToPrint, layerPrint); try { File.Copy(tmpFile, fileName, true); } catch (UnauthorizedAccessException uae) { throw new ExportPDFException( String.Format("You don't have the reqired permission to access '{0}'.", fileName), uae); } catch (ArgumentException ae) { throw new ExportPDFException( String.Format("Either '{0}' or '{1}' is not a proper file name.", tmpFile, fileName), ae); } catch (PathTooLongException ptle) { throw new ExportPDFException( String.Format("Source='{0}'; Dest='{1}' <= One of these is too long.", tmpFile, fileName), ptle); } catch (DirectoryNotFoundException dnfe) { throw new ExportPDFException( String.Format("Source='{0}'; Dest='{1}' <= One of these is invalid.", tmpFile, fileName), dnfe); } catch (FileNotFoundException fnfe) { throw new ExportPDFException( String.Format("Crap! I lost '{0}'!", tmpFile), fnfe); } catch (IOException) { System.Windows.Forms.MessageBox.Show( String.Format("If you have the file, '{0}', selected in an Explorer window, " + "you may have to close it.", fileName), "This file is open somewhere.", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); return(false); } catch (NotSupportedException nse) { throw new ExportPDFException( String.Format("Source='{0}'; Dest='{1}' <= One of these is an invalid format.", tmpFile, fileName), nse); } if (!File.Exists(fileName)) { success = false; } if (success) { swFrame.SetStatusBarText(String.Format("Exported '{0}'", fileName)); if (fileName.StartsWith(Properties.Settings.Default.KPath) && APathSet.WriteToDb) { savedFile = fileName; if (fileName.EndsWith("PDF")) { InsertIntoDb(fileName, Properties.Settings.Default.PDFTable); drwKey = GetKeyCol(fi.Name); } if (fileName.EndsWith(@"EPRT") || fileName.EndsWith("EASM")) { InsertIntoDb(fileName, Properties.Settings.Default.eDrawingTable); } } if ((fileName.StartsWith(Properties.Settings.Default.MetalPath) && fileName.EndsWith("PDF")) && APathSet.WriteToDb) { _metalDrawing = true; InsertIntoDb(fileName, Properties.Settings.Default.metalTable); drwKey = GetKeyCol(fi.Name); } } else { ExportPDFException e = new ExportPDFException(String.Format("Failed to save '{0}'", fileName)); //e.Data.Add("who", System.Environment.UserName); //e.Data.Add("when", DateTime.Now); throw e; } } } if (success) { return(true); } else { return(false); } }
private int SavePDFCopy(string fileName) { try { ModelDocExtension swModExt = this.ModelDocument.Extension; ExportPdfData swExportPDFData = (ExportPdfData)this.SolidworksApp.GetExportFileData((int)swExportDataFileType_e.swExportPdfData); bool boolstatus = false; int errors = 0; int warnings = 0; string[] obj = null; string description; string resolvedDescription; bool wasResolved; string revision; string resolverdRevision; CustomPropertyManager swCustProp = swModExt.CustomPropertyManager[string.Empty]; swCustProp.Get5("Description", false, out description, out resolvedDescription, out wasResolved); swCustProp.Get5("Revision", false, out revision, out resolverdRevision, out wasResolved); string pdffilename = fileName.ToUpper().Replace(".SLDDRW", string.Empty); string previousNames = pdffilename.Substring(pdffilename.LastIndexOf('\\') + 1); pdffilename = pdffilename.Substring(pdffilename.LastIndexOf('\\')); if (this.UserAddin.AppendRevision) { pdffilename += ", Rev. " + revision; } if (this.UserAddin.AppendDescription) { pdffilename += ", " + description; } string useDirectory; // find project sub-directory var subDir = new DirectoryInfo(this.UserAddin.PDFLocation + "\\" + previousNames.Substring(0, 2)); if (subDir.Exists) { useDirectory = this.UserAddin.PDFLocation + "\\" + previousNames.Substring(0, 2); } else { useDirectory = this.UserAddin.PDFLocation; } //Delete the old versions if (this.UserAddin.RemovePrevious) { var dir = new DirectoryInfo(useDirectory); foreach (var file in dir.EnumerateFiles(previousNames + "*.pdf")) { file.Delete(); } } pdffilename = useDirectory + pdffilename + ".pdf"; obj = this.doc.GetSheetNames(); int count = 0; count = obj.Length; int i = 0; object[] objs = new object[count - 1]; DispatchWrapper[] arrObjIn = new DispatchWrapper[count - 1]; // Activate each drawing sheet, except the last drawing sheet, for // demonstration purposes only and add each sheet to an array // of drawing sheets for (i = 0; i < count - 1; i++) { boolstatus = this.doc.ActivateSheet(obj[i]); Sheet swSheet = (Sheet)this.doc.GetCurrentSheet(); objs[i] = swSheet; arrObjIn[i] = new DispatchWrapper(objs[i]); } // Save the drawings sheets to a PDF file swExportPDFData.SetSheets((int)swExportDataSheetsToExport_e.swExportData_ExportAllSheets, arrObjIn); swExportPDFData.ViewPdfAfterSaving = this.UserAddin.ShowPDF; swModExt.SaveAs(pdffilename, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, swExportPDFData, ref errors, ref warnings); } catch (Exception e) { System.Windows.Forms.MessageBox.Show("Problem Saving the PDF. " + e.Message); } return(0); }
/// <summary> /// 指定のフォルダ内にある3D モデルファイルを一括で別形式に変換するプログラム /// </summary> /// <param name="args"></param> static void Main(string[] args) { if (args.Count() > 0) { foreach (string arg in args) { switch (arg.Substring(0, arg.IndexOf("="))) { case "--tn": string argVal = arg.Substring(arg.IndexOf("=") + 1); if (argVal == "true") { thumbnail = true; } break; default: break; } } } string[] files = System.IO.Directory.GetFiles(directory); foreach (string file in files) { string filename = file.Substring(file.LastIndexOf("\\") + 1, file.IndexOf(".") - file.LastIndexOf("\\") - 1); swApp = new SldWorks.SldWorks(); swApp.Visible = thumbnail; Console.WriteLine(file); bool bRet = false; string strArg = null; int Err = 0; object importData = swApp.GetImportFileData(file); swModel = swApp.LoadFile4(file, strArg, importData, ref Err); if (thumbnail) { swModel.ShowNamedView2("", 7); swModel.ViewZoomtofit2(); swApp.FrameState = 1; Thread.Sleep(1000); Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); Graphics g = Graphics.FromImage(bmp); g.CopyFromScreen(new Point(0, 0), new Point(0, 0), bmp.Size); string directory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory) + @"\bmp"; if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } filename = System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory) + @"\bmp\" + filename + ".bmp"; bmp.Save(filename, System.Drawing.Imaging.ImageFormat.Bmp); g.Dispose(); } string newfilename = file.Remove(file.IndexOf(".")) + extension; swModel.ClearSelection2(true); bRet = swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swStepAP, 214); ModelDocExtension swExt = swModel.Extension; bRet = swExt.SaveAs(newfilename, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, 0, null, Err, 0); swApp.ExitApp(); } }
/// <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; }
private void button1_Click(object sender, EventArgs e) { SldWorks sw = new SldWorks(); sw.Visible = true; int err = 0, war = 0; ModelDoc2 swModel = sw.OpenDoc6(Application.StartupPath + "\\beam.sldprt", 1, 0, "", ref err, ref war); double a = Convert.ToDouble(textBox1.Text); double b = Convert.ToDouble(textBox2.Text); double l = Convert.ToDouble(textBox3.Text); double E = Convert.ToDouble(textBox4.Text); double nu = Convert.ToDouble(textBox5.Text); double q = Convert.ToDouble(textBox6.Text); if (pictureBox1.Image != null) { pictureBox1.Image.Dispose(); pictureBox1.Image = null; // pictureBox1.Load(); pictureBox1.Update(); pictureBox1.Invalidate(); } if (pictureBox2.Image != null) { pictureBox2.Image.Dispose(); pictureBox2.Image = null; // pictureBox1.Load(); pictureBox2.Update(); pictureBox2.Invalidate(); } double sigma = 3 * q * l * l / b / b / 1e6; label8.Text = sigma.ToString(); swModel.Parameter("D1@Эскиз1").Value = a * 1e3; swModel.Parameter("D2@Эскиз1").Value = b * 1e3; swModel.Parameter("D1@Бобышка-Вытянуть1").Value = l * 1e3; swModel.EditRebuild3(); swModel.ViewZoomtofit2(); CwAddincallback COSMOSObject = (CwAddincallback)sw.GetAddInObject("SldWorks.Simulation"); ICosmosWorks cw = (ICosmosWorks)COSMOSObject.CosmosWorks; CWModelDoc ActDoc = cw.ActiveDoc; CWStudyManager StudyMngr = ActDoc.StudyManager; CWStudy Study = StudyMngr.GetStudy(0); // 0 - номер уже созданного расчета CWSolidManager SolidMgr = Study.SolidManager; int CompCount = SolidMgr.ComponentCount; // кол-во деталей в расчете int errorCode = 0; for (int i = 0; i < CompCount; i++) // Присваеваем свойства материала { CWSolidComponent SolidComponent = SolidMgr.GetComponentAt(i, out errorCode); CWSolidBody SolidBody = SolidComponent.GetSolidBodyAt(0, out errorCode); CWMaterial CWMat = SolidBody.GetSolidBodyMaterial(); CWMat.MaterialUnits = 0; CWMat.MaterialName = "Alloy Steel"; CWMat.SetPropertyByName("EX", E, 0); CWMat.SetPropertyByName("NUXY", nu, 0); SolidBody.SetSolidBodyMaterial(CWMat); SolidBody = null; } CWLoadsAndRestraintsManager LBCMgr = Study.LoadsAndRestraintsManager; for (int i = 0; i < LBCMgr.Count; i++) { CWLoadsAndRestraints CWP = LBCMgr.GetLoadsAndRestraints(i, out errorCode); if (CWP.Type == 1) // давление { CWPressure CWPressure = (CWPressure)CWP; CWPressure.PressureBeginEdit(); CWPressure.Unit = 3; CWPressure.Value = q; CWPressure.PressureEndEdit(); } } double esize = 0, dtol = 0; CWMesh CwMesh = Study.Mesh; // Remesh geometry CwMesh.Quality = 1; CwMesh.GetDefaultElementSizeAndTolerance(0, out esize, out dtol); Study.CreateMesh(0, esize, dtol); errorCode = Study.RunAnalysis(); // Run analysis ModelDocExtension swModelDocExt = swModel.Extension; CWResults CWResult = Study.Results; // Get results ActDoc.DeleteAllDefaultStaticStudyPlots(); //Create displacement plot CWPlot CWCFf = CWResult.CreatePlot((int)swsPlotResultTypes_e.swsResultDisplacementOrAmplitude, (int)swsStaticResultDisplacementComponentTypes_e.swsStaticDisplacement_URES, (int)swsUnit_e.swsUnitSI, false, out err); //Activate plot err = CWCFf.ActivatePlot(); //Get min/max resultant displacements from plot object[] Disp = (object[])CWCFf.GetMinMaxResultValues(out err); double MinDisp = Convert.ToDouble(Disp[1]); double MaxDisp = Convert.ToDouble(Disp[3]); swModelDocExt.SaveAs(Application.StartupPath + "\\Displacement.analysis.jpg", 0, 0, null, ref err, ref war); //Create stress plot CWCFf = CWResult.CreatePlot((int)swsPlotResultTypes_e.swsResultStress, (int)swsStaticResultNodalStressComponentTypes_e.swsStaticNodalStress_VON, (int)swsUnit_e.swsUnitSI, false, out err); //Get min/max von Mises stresses from plot object[] Stress = (object[])CWCFf.GetMinMaxResultValues(out err); double MinStress = Convert.ToDouble(Stress[1]); double MaxStress = Convert.ToDouble(Stress[3]); swModelDocExt.SaveAs(Application.StartupPath + "\\vmStress.analysis.jpg", 0, 0, null, ref err, ref war); pictureBox1.Image = System.Drawing.Image.FromFile(Application.StartupPath + "\\vmStress.analysis.jpg"); pictureBox2.Image = System.Drawing.Image.FromFile(Application.StartupPath + "\\Displacement.analysis.jpg"); label10.Text = (MaxStress / 1e6).ToString(); }
static ModelDoc2 Convert2Part(ModelDoc2 assembly, Dictionary <string, Info> assemblyInfo) { // Used when comparing assemblies. ModelDoc2 model = assembly; ModelDocExtension modelExt = model.Extension; int errors = 0; int warnings = 0; string assemblyPartName; string assemblyPartPath; ModelDoc2 convertedAssembly; object[] bodies_array; bool check; if ((int)assemblyInfo["Type"].Value == (int)swDocumentTypes_e.swDocPART) { Logger.Error("VolumeComparator.cs", "Convert2Part()", "The document provided is not an assembly document."); return(null); } assemblyPartName = assemblyInfo["Name"].Value + "_PartConversion.sldprt"; assemblyPartPath = assemblyInfo["Folder"].Value + assemblyPartName; // Logger.Info("Saving Assembly as '.SLDPRT'..."); // Logger.Info("More Specifically: " + assemblyPartPath); swApp.ActivateDoc3((string)assemblyInfo["Title"].Value, true, (int)swRebuildOnActivation_e.swRebuildActiveDoc, ref errors); check = modelExt.SaveAs(assemblyPartPath, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, errors, warnings); if (errors != 0) { Logger.Error("VolumeComparator", "SaveAsPart", "swSaveAsError: " + errors); } else if (warnings != 0) { Logger.Warn("swFileSaveWarning: " + warnings); } else if (check) { // Logger.Info("Save successful."); } else { Logger.Error("VolumeComparator", "SaveAsPart", "Couldn't save for unknown reason."); } // CloseDocs(new object[] { assembly }); convertedAssembly = SwApp.OpenFile(assemblyPartPath); FeatureManager partFeatureMgr = convertedAssembly.FeatureManager; Feature partFeature; bodies_array = ((PartDoc)convertedAssembly).GetBodies2((int)swBodyType_e.swSolidBody, true); Body2[] bodies = new Body2[bodies_array.Length]; for (int i = 0; i < bodies_array.Length; i++) { bodies[i] = (Body2)bodies_array[i]; } // Logger.Info("Combining all bodies together..."); partFeature = partFeatureMgr.InsertCombineFeature((int)swBodyOperationType_e.SWBODYADD, null, bodies); if (partFeature == null) { Logger.Warn("No Body found to be touching eachother"); return(null); } convertedAssembly.Save(); return(convertedAssembly); }